commit c02e6e55967f7632b09be767ad7846f89100dadd Author: nitrogenoliquido <203537016+nitrogenoliquido@users.noreply.github.com> Date: Tue Nov 24 22:15:30 2026 -0500 added files. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..90a9e3c --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.gradle/ +build/ +out/ +.idea/ +*.iml +.classpath +.project +.settings/ +*.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..4d79fa3 --- /dev/null +++ b/README.md @@ -0,0 +1,55 @@ +

+ Skid Solutions Banner +
+ all credits to SugarMountainfloor Aka. Showman +

+ + Discord + + Version 10.10-2-56528ba + Java 8 + Gradle 8.14.3 +

+ +

+ https://discord.gg/skidsolutions +

+ +

+ +

+ +

+ jak + hack + deobf2 + deobf +

+ +

+ +

+ +## How to build + +### Prerequisites +- **Java Development Kit**: JDK 8 (compile toolchain) and JDK 17 (Gradle 8.14.3 launcher; newer JDKs such as JDK 25 are not supported by Gradle 8.14.3) + +### Building OpenReflex + +Run from this folder: + +```powershell +$env:JAVA_HOME = "C:\Program Files\Java\jdk-17" + +.\gradlew.bat prepareIde +.\gradlew.bat clean build +``` + +Generated `build/libs/`: +- `OpenReflex-10.10-2-56528ba.jar` +- `OpenReflex-10.10-2-56528ba-sources.jar` + +### Installation + +Copy `build\libs\OpenReflex-10.10-2-56528ba.jar` into your Spigot or Paper server's `plugins/` folder (Minecraft 1.8 to 1.13). Requires ProtocolLib; ViaVersion and PlaceholderAPI are optional. diff --git a/assets/deobf.jpg b/assets/deobf.jpg new file mode 100644 index 0000000..fa8dbde Binary files /dev/null and b/assets/deobf.jpg differ diff --git a/assets/deobf2.png b/assets/deobf2.png new file mode 100644 index 0000000..1d4014d Binary files /dev/null and b/assets/deobf2.png differ diff --git a/assets/divider.svg b/assets/divider.svg new file mode 100644 index 0000000..f473231 --- /dev/null +++ b/assets/divider.svg @@ -0,0 +1,26 @@ + diff --git a/assets/hack.jpg b/assets/hack.jpg new file mode 100644 index 0000000..c4252ef Binary files /dev/null and b/assets/hack.jpg differ diff --git a/assets/jak.jpg b/assets/jak.jpg new file mode 100644 index 0000000..162bfe5 Binary files /dev/null and b/assets/jak.jpg differ diff --git a/assets/ss.png b/assets/ss.png new file mode 100644 index 0000000..041b33a Binary files /dev/null and b/assets/ss.png differ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..ab111dc --- /dev/null +++ b/build.gradle @@ -0,0 +1,116 @@ +plugins { + id 'java' + id 'idea' + id 'eclipse' +} + +group = 'rip.reflex' +version = '10.10-2-56528ba' + +def javaVersion = 8 + +repositories { + mavenCentral() + maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') } + maven { url = uri('https://repo.dmulloy2.net/repository/public/') } + maven { url = uri('https://repo.extendedclip.com/content/repositories/placeholderapi/') } +} + +configurations { + apiGenerator +} + +def generatorClasses = layout.buildDirectory.dir('api-generator/classes') +tasks.register('compileApiGenerator', JavaCompile) { + source = files('gradle/GenerateCompileApis.java') + classpath = configurations.apiGenerator + destinationDirectory = generatorClasses + javaCompiler = javaToolchains.compilerFor { languageVersion = JavaLanguageVersion.of(javaVersion) } + options.encoding = 'UTF-8' +} + +tasks.register('generateCompileApis', JavaExec) { + group = 'build setup' + description = 'Generates compile-only API headers from text declarations.' + dependsOn tasks.named('compileApiGenerator') + inputs.dir('gradle/api-signatures') + outputs.dir(layout.buildDirectory.dir('compile-apis')) + classpath = files(generatorClasses) + configurations.apiGenerator + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(javaVersion) } + mainClass = 'GenerateCompileApis' + args file('gradle/api-signatures').absolutePath, layout.buildDirectory.dir('compile-apis').get().asFile.absolutePath +} + +def compileApi = { String name -> + files(layout.buildDirectory.file("compile-apis/${name}.jar")).builtBy(tasks.named('generateCompileApis')) +} + +tasks.register('prepareIde') { + group = 'ide' + description = 'Generates the compile-only API headers used by the IDE import.' + dependsOn tasks.named('generateCompileApis') +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(javaVersion) + } + withSourcesJar() +} + +dependencies { + apiGenerator 'org.ow2.asm:asm:9.8' + apiGenerator 'com.google.code.gson:gson:2.10.1' + + compileOnly compileApi('reflex') + compileOnly('org.spigotmc:spigot-api:1.13.2-R0.1-SNAPSHOT') { + exclude group: 'net.md-5', module: 'bungeecord-chat' + } + compileOnly 'net.md-5:bungeecord-chat:1.16-R0.4' + compileOnly 'com.comphenix.protocol:ProtocolLib:4.4.0' + compileOnly 'me.clip:placeholderapi:2.11.6' + compileOnly 'org.mongodb:mongo-java-driver:3.12.14' + compileOnly 'com.google.guava:guava:21.0' + compileOnly 'com.google.code.gson:gson:2.8.9' + compileOnly 'commons-codec:commons-codec:1.11' + compileOnly 'commons-io:commons-io:2.4' + compileOnly 'commons-lang:commons-lang:2.6' + compileOnly 'org.apache.httpcomponents:httpcore:4.4.16' + compileOnly 'org.bouncycastle:bcprov-jdk18on:1.78.1' + compileOnly 'com.googlecode.json-simple:json-simple:1.1.1' +} + +tasks.withType(JavaCompile).configureEach { + if (name != 'compileApiGenerator') { + dependsOn tasks.named('generateCompileApis') + } + options.encoding = 'UTF-8' + options.compilerArgs += ['-Xlint:none', '-Xmaxerrs', '1000'] +} + +tasks.withType(AbstractArchiveTask).configureEach { + preserveFileTimestamps = false + reproducibleFileOrder = true +} + +jar { + manifest { + attributes( + 'Implementation-Title': 'OpenReflex', + 'Implementation-Version': project.version) + } +} + +idea { + module { + downloadSources = true + downloadJavadoc = true + } +} + +eclipse { + classpath { + downloadSources = true + downloadJavadoc = true + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..a31b0e0 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +org.gradle.parallel=true +org.gradle.caching=true diff --git a/gradle/GenerateCompileApis.java b/gradle/GenerateCompileApis.java new file mode 100644 index 0000000..9d0faba --- /dev/null +++ b/gradle/GenerateCompileApis.java @@ -0,0 +1,228 @@ +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.TypePath; + +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public final class GenerateCompileApis implements Opcodes { + private interface Factory { + AnnotationVisitor create(JsonObject annotation); + } + + private static String text(JsonObject obj, String key) { + return obj.has(key) && !obj.get(key).isJsonNull() ? obj.get(key).getAsString() : null; + } + + private static int number(JsonObject obj, String key) { + return obj.get(key).getAsInt(); + } + + private static JsonArray array(JsonObject obj, String key) { + return obj.has(key) ? obj.getAsJsonArray(key) : new JsonArray(); + } + + private static String[] strings(JsonObject obj, String key) { + List list = new ArrayList<>(); + for (JsonElement el : array(obj, key)) { + list.add(el.getAsString()); + } + return list.toArray(new String[0]); + } + + private static Object scalar(JsonObject obj) { + String value = text(obj, "value"); + String type = text(obj, "type"); + if ("Long".equals(type)) return Long.valueOf(value); + if ("Integer".equals(type)) return Integer.valueOf(value); + if ("Float".equals(type)) return Float.valueOf(value); + if ("Double".equals(type)) return Double.valueOf(value); + if ("Byte".equals(type)) return Byte.valueOf(value); + if ("Short".equals(type)) return Short.valueOf(value); + if ("Character".equals(type)) return value.charAt(0); + throw new IllegalArgumentException(obj.toString()); + } + + private static Object constant(JsonElement el) { + if (el == null || el.isJsonNull()) return null; + if (el.isJsonObject()) return scalar(el.getAsJsonObject()); + return el.getAsString(); + } + + private static void annotationValue(AnnotationVisitor visitor, String name, JsonElement value) { + if (value.isJsonArray()) { + AnnotationVisitor nested = visitor.visitArray(name); + for (JsonElement el : value.getAsJsonArray()) { + annotationValue(nested, null, el); + } + nested.visitEnd(); + } else if (value.isJsonObject()) { + JsonObject obj = value.getAsJsonObject(); + String kind = text(obj, "kind"); + if ("scalar".equals(kind)) { + visitor.visit(name, scalar(obj)); + } else if ("type".equals(kind)) { + visitor.visit(name, Type.getType(text(obj, "descriptor"))); + } else if ("enum".equals(kind)) { + visitor.visitEnum(name, text(obj, "descriptor"), text(obj, "name")); + } else if ("annotation".equals(kind)) { + JsonObject ann = obj.getAsJsonObject("annotation"); + writeAnnotation(visitor.visitAnnotation(name, text(ann, "descriptor")), ann); + } else { + throw new IllegalArgumentException(obj.toString()); + } + } else if (value.getAsJsonPrimitive().isBoolean()) { + visitor.visit(name, value.getAsBoolean()); + } else { + visitor.visit(name, value.getAsString()); + } + } + + private static void writeAnnotation(AnnotationVisitor visitor, JsonObject annotation) { + if (visitor == null) return; + for (Map.Entry entry : annotation.getAsJsonObject("values").entrySet()) { + annotationValue(visitor, entry.getKey(), entry.getValue()); + } + visitor.visitEnd(); + } + + private static void annotations(JsonObject obj, String key, Factory factory) { + for (JsonElement el : array(obj, key)) { + JsonObject ann = el.getAsJsonObject(); + writeAnnotation(factory.create(ann), ann); + } + } + + private static byte[] compile(JsonObject cls) { + ClassWriter cw = new ClassWriter(0); + cw.visit( + number(cls, "version"), + number(cls, "access"), + text(cls, "name"), + text(cls, "signature"), + text(cls, "superName"), + strings(cls, "interfaces") + ); + if (cls.has("outerClass")) { + cw.visitOuterClass(text(cls, "outerClass"), text(cls, "outerMethod"), text(cls, "outerMethodDescriptor")); + } + annotations(cls, "annotations", a -> cw.visitAnnotation(text(a, "descriptor"), a.get("visible").getAsBoolean())); + annotations(cls, "typeAnnotations", a -> cw.visitTypeAnnotation( + number(a, "typeRef"), TypePath.fromString(text(a, "typePath")), text(a, "descriptor"), a.get("visible").getAsBoolean())); + for (JsonElement el : array(cls, "innerClasses")) { + JsonObject inner = el.getAsJsonObject(); + cw.visitInnerClass(text(inner, "name"), text(inner, "outerName"), text(inner, "innerName"), number(inner, "access")); + } + for (JsonElement el : array(cls, "fields")) { + JsonObject f = el.getAsJsonObject(); + FieldVisitor fv = cw.visitField( + number(f, "access"), + text(f, "name"), + text(f, "descriptor"), + text(f, "signature"), + constant(f.get("constant")) + ); + annotations(f, "annotations", a -> fv.visitAnnotation(text(a, "descriptor"), a.get("visible").getAsBoolean())); + fv.visitEnd(); + } + for (JsonElement el : array(cls, "methods")) { + JsonObject m = el.getAsJsonObject(); + int access = number(m, "access"); + String descriptor = text(m, "descriptor"); + MethodVisitor mv = cw.visitMethod(access, text(m, "name"), descriptor, text(m, "signature"), strings(m, "exceptions")); + for (JsonElement pe : array(m, "parameters")) { + JsonObject p = pe.getAsJsonObject(); + mv.visitParameter(text(p, "name"), number(p, "access")); + } + annotations(m, "annotations", a -> mv.visitAnnotation(text(a, "descriptor"), a.get("visible").getAsBoolean())); + if (m.has("annotationDefault")) { + AnnotationVisitor av = mv.visitAnnotationDefault(); + annotationValue(av, null, m.get("annotationDefault")); + av.visitEnd(); + } + if ((access & (ACC_ABSTRACT | ACC_NATIVE)) == 0) { + mv.visitCode(); + mv.visitTypeInsn(NEW, "java/lang/UnsupportedOperationException"); + mv.visitInsn(DUP); + mv.visitLdcInsn("Compile-only API header; use the real server or library at runtime"); + mv.visitMethodInsn(INVOKESPECIAL, "java/lang/UnsupportedOperationException", "", "(Ljava/lang/String;)V", false); + mv.visitInsn(ATHROW); + int locals = (access & ACC_STATIC) == 0 ? 1 : 0; + for (Type t : Type.getArgumentTypes(descriptor)) { + locals += t.getSize(); + } + mv.visitMaxs(3, locals); + } + mv.visitEnd(); + } + cw.visitEnd(); + return cw.toByteArray(); + } + + private static SortedMap declarations(Path input, Path schema, Set active) throws Exception { + if (!active.add(schema)) { + throw new IllegalArgumentException("Cyclic API declaration inheritance: " + schema); + } + JsonObject data; + try (Reader reader = Files.newBufferedReader(schema, StandardCharsets.UTF_8)) { + data = JsonParser.parseReader(reader).getAsJsonObject(); + } + SortedMap classes = new TreeMap<>(); + if (data.has("base")) { + classes.putAll(declarations(input, input.resolve(text(data, "base") + ".json"), active)); + } + for (JsonElement entry : array(data, "classes")) { + JsonObject cls = entry.getAsJsonObject(); + classes.put(text(cls, "name"), cls); + } + active.remove(schema); + return classes; + } + + public static void main(String[] args) throws Exception { + Path input = Paths.get(args[0]); + Path output = Paths.get(args[1]); + Files.createDirectories(output); + List schemas; + try (Stream stream = Files.list(input)) { + schemas = stream.filter(p -> p.toString().endsWith(".json")).sorted().collect(Collectors.toList()); + } + for (Path schema : schemas) { + SortedMap classes = declarations(input, schema, new HashSet<>()); + String name = schema.getFileName().toString().replace(".json", ".jar"); + Path jar = output.resolve(name); + try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) { + for (JsonObject cls : classes.values()) { + JarEntry entry = new JarEntry(text(cls, "name") + ".class"); + entry.setTime(0); + out.putNextEntry(entry); + out.write(compile(cls)); + out.closeEntry(); + } + } + System.out.println("Generated compile API " + name + " (" + classes.size() + " declarations)"); + } + } +} diff --git a/gradle/api-signatures/reflex.json b/gradle/api-signatures/reflex.json new file mode 100644 index 0000000..58814f0 --- /dev/null +++ b/gradle/api-signatures/reflex.json @@ -0,0 +1,125 @@ +{ + "classes": [ + { + "version": 52, + "access": 33, + "name": "org/spigotmc/SpigotConfig", + "superName": "java/lang/Object", + "fields": [ + { + "access": 9, + "name": "unknownCommandMessage", + "descriptor": "Ljava/lang/String;" + }, + { + "access": 9, + "name": "bungee", + "descriptor": "Z" + } + ], + "methods": [ + { + "access": 1, + "name": "", + "descriptor": "()V" + } + ] + }, + { + "version": 52, + "access": 33, + "name": "org/spigotmc/AsyncCatcher", + "superName": "java/lang/Object", + "fields": [ + { + "access": 9, + "name": "enabled", + "descriptor": "Z" + } + ], + "methods": [ + { + "access": 1, + "name": "", + "descriptor": "()V" + }, + { + "access": 9, + "name": "catchOp", + "descriptor": "(Ljava/lang/String;)V" + } + ] + }, + { + "version": 52, + "access": 33, + "name": "us/myles/ViaVersion/api/Via", + "superName": "java/lang/Object", + "methods": [ + { + "access": 9, + "name": "getAPI", + "descriptor": "()Lus/myles/ViaVersion/api/ViaAPI;" + } + ] + }, + { + "version": 52, + "access": 1537, + "name": "us/myles/ViaVersion/api/ViaAPI", + "superName": "java/lang/Object", + "methods": [ + { + "access": 1025, + "name": "getPlayerVersion", + "descriptor": "(Ljava/util/UUID;)I" + } + ] + }, + { + "version": 52, + "access": 33, + "name": "us/myles/ViaVersion/api/protocol/ProtocolVersion", + "superName": "java/lang/Object", + "fields": [ + { + "access": 25, + "name": "v1_8", + "descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;" + }, + { + "access": 25, + "name": "v1_9", + "descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;" + }, + { + "access": 25, + "name": "v1_10", + "descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;" + }, + { + "access": 25, + "name": "v1_11", + "descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;" + }, + { + "access": 25, + "name": "v1_12", + "descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;" + }, + { + "access": 25, + "name": "v1_13", + "descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;" + } + ], + "methods": [ + { + "access": 1, + "name": "getId", + "descriptor": "()I" + } + ] + } + ] +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9251069 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531 diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/platforms/jvm/plugins-application/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##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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="\\\"\\\"" + + +# 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=SC2039,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=SC2039,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 optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +: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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..5879538 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,8 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + } +} + +rootProject.name = 'OpenReflex' diff --git a/src/main/java/me/darksidecode/e2eep4j/E2EException.java b/src/main/java/me/darksidecode/e2eep4j/E2EException.java new file mode 100644 index 0000000..b2f1cb8 --- /dev/null +++ b/src/main/java/me/darksidecode/e2eep4j/E2EException.java @@ -0,0 +1,18 @@ +package me.darksidecode.e2eep4j; + +public class E2EException extends RuntimeException { + public E2EException() { + } + + public E2EException(String s) { + super(s); + } + + public E2EException(Exception e) { + super(e); + } + + public E2EException(String s, Exception e) { + super(s, e); + } +} diff --git a/src/main/java/me/darksidecode/e2eep4j/E2EKey.java b/src/main/java/me/darksidecode/e2eep4j/E2EKey.java new file mode 100644 index 0000000..1835c75 --- /dev/null +++ b/src/main/java/me/darksidecode/e2eep4j/E2EKey.java @@ -0,0 +1,75 @@ +package me.darksidecode.e2eep4j; + +import me.darksidecode.e2eep4j.util.Validate; + +public class E2EKey { + private byte[] iv; + private byte[] aes; + private byte[] base; + private Object[] coverage; + + public E2EKey(byte[] iv, byte[] aes, byte[] base) { + this(iv, aes, base, null); + } + + public E2EKey(byte[] iv, byte[] aes, byte[] base, Object[] coverage) { + this.iv = Validate.ivLength( + Validate.notEmpty(Validate.notNull(iv, "Init vector cannot be null"), "Init vector cannot be empty"), "Illegal input vector length" + ); + this.aes = Validate.aesLength(Validate.notEmpty(Validate.notNull(aes, "AES cannot be null"), "AES cannot be empty"), "Illegal AES length"); + this.base = Validate.baseLength(Validate.notEmpty(Validate.notNull(base, "Base cannot be null"), "Base cannot be empty"), "Illegal base length"); + this.coverage = coverage == null ? null : Validate.cvgLength(Validate.notEmpty(coverage, "Coverage cannot be empty"), "Illegal coverage length"); + } + + public byte[] getIV() { + byte[] r = (byte[])Validate.notEmpty(this.iv, "Input vector was already used").clone(); + this.iv = new byte[0]; + return r; + } + + public byte[] getAES() { + byte[] r = (byte[])Validate.notEmpty(this.aes, "AES was already used").clone(); + this.aes = new byte[0]; + return r; + } + + public byte[] getBase() { + byte[] r = (byte[])Validate.notEmpty(this.base, "Base was already used").clone(); + this.base = new byte[0]; + return r; + } + + public Object[] getCoverage() { + Object[] r = Validate.notEmpty(Validate.notNull(this.coverage, "Coverage is not set"), "Coverage was already used").clone(); + this.coverage = new Object[0]; + return r; + } + + public boolean shallCoverage() { + return this.coverage != null; + } + + public boolean isUsed() { + return this.iv.length == 0 || this.aes.length == 0 || this.base.length == 0 || this.coverage != null && this.coverage.length == 0; + } + + @Override + public boolean equals(Object obj) { + throw new E2EException("E2E keys cannot be compared"); + } + + @Override + public int hashCode() { + throw new E2EException("E2E keys cannot be hashed"); + } + + @Override + public String toString() { + throw new E2EException("E2E keys cannot be converted to a string"); + } + + @Override + public Object clone() { + throw new E2EException("E2E keys cannot be cloned"); + } +} diff --git a/src/main/java/me/darksidecode/e2eep4j/api/E2EEP4J.java b/src/main/java/me/darksidecode/e2eep4j/api/E2EEP4J.java new file mode 100644 index 0000000..c3010d0 --- /dev/null +++ b/src/main/java/me/darksidecode/e2eep4j/api/E2EEP4J.java @@ -0,0 +1,49 @@ +package me.darksidecode.e2eep4j.api; + +import java.io.File; +import java.nio.file.Files; +import me.darksidecode.e2eep4j.E2EException; +import me.darksidecode.e2eep4j.E2EKey; +import me.darksidecode.e2eep4j.enc.CryptoSession; +import me.darksidecode.e2eep4j.enc.DecryptionSession; +import me.darksidecode.e2eep4j.enc.EncryptionSession; +import me.darksidecode.e2eep4j.util.Convert; +import me.darksidecode.e2eep4j.util.Generate; + +public class E2EEP4J { + public static byte[] encryptBytes(byte[] input, E2EKey key) { + return cryptBytes(new EncryptionSession(input, key)); + } + + public static byte[] decryptBytes(byte[] input, E2EKey key) { + return cryptBytes(new DecryptionSession(input, key)); + } + + public static byte[] cryptBytes(CryptoSession session) { + return session.run().result(); + } + + public static E2EKey generateKey() { + return Generate.e2eKey(); + } + + public static E2EKey generateKey(Object[] coverage) { + return Generate.e2eKey(coverage); + } + + public static void safeKeyToFile(E2EKey key, File f) { + try { + Files.write(f.toPath(), Convert.e2eKey2Bytes(key)); + } catch (Exception ex) { + throw new E2EException("Failed to save key to file", ex); + } + } + + public static E2EKey readKeyFromFile(File f) { + try { + return Convert.bytes2e2ekey(Files.readAllBytes(f.toPath())); + } catch (Exception e) { + throw new E2EException("Failed to read key from file", e); + } + } +} diff --git a/src/main/java/me/darksidecode/e2eep4j/enc/CryptoSession.java b/src/main/java/me/darksidecode/e2eep4j/enc/CryptoSession.java new file mode 100644 index 0000000..91b5255 --- /dev/null +++ b/src/main/java/me/darksidecode/e2eep4j/enc/CryptoSession.java @@ -0,0 +1,9 @@ +package me.darksidecode.e2eep4j.enc; + +public interface CryptoSession { + CryptoSession run(); + + CryptoSession end(); + + byte[] result(); +} diff --git a/src/main/java/me/darksidecode/e2eep4j/enc/DecryptionSession.java b/src/main/java/me/darksidecode/e2eep4j/enc/DecryptionSession.java new file mode 100644 index 0000000..3ef90e0 --- /dev/null +++ b/src/main/java/me/darksidecode/e2eep4j/enc/DecryptionSession.java @@ -0,0 +1,52 @@ +package me.darksidecode.e2eep4j.enc; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import me.darksidecode.e2eep4j.E2EException; +import me.darksidecode.e2eep4j.E2EKey; +import me.darksidecode.e2eep4j.util.Validate; +import org.apache.commons.codec.binary.Base64; + +public class DecryptionSession implements CryptoSession { + private byte[] input; + private byte[] result; + private E2EKey k; + + public DecryptionSession(byte[] input, E2EKey k) { + this.input = Validate.notEmpty(Validate.notNull(input, "Input cannot be null"), "Input cannot be empty"); + this.k = Validate.notNull(k, "Key cannot be null"); + } + + @Override + public CryptoSession run() { + try { + IvParameterSpec iv = new IvParameterSpec(this.k.getIV()); + SecretKeySpec skeySpec = new SecretKeySpec(this.k.getAES(), "AES"); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + cipher.init(2, skeySpec, iv); + this.result = cipher.doFinal(Base64.decodeBase64(this.input)); + return this; + } catch (Exception ex) { + throw new E2EException("Failed to decrypt " + this.input.length + " bytes", ex); + } + } + + @Override + public CryptoSession end() { + this.input = this.result = new byte[0]; + this.k = null; + return this; + } + + @Override + public byte[] result() { + if (Validate.notNull(this.result, "The session was never ran").length != 0 && this.k != null) { + byte[] r = (byte[])this.result.clone(); + this.end(); + return r; + } else { + throw new E2EException("Result was already used"); + } + } +} diff --git a/src/main/java/me/darksidecode/e2eep4j/enc/EncryptionSession.java b/src/main/java/me/darksidecode/e2eep4j/enc/EncryptionSession.java new file mode 100644 index 0000000..d1832ad --- /dev/null +++ b/src/main/java/me/darksidecode/e2eep4j/enc/EncryptionSession.java @@ -0,0 +1,52 @@ +package me.darksidecode.e2eep4j.enc; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import me.darksidecode.e2eep4j.E2EException; +import me.darksidecode.e2eep4j.E2EKey; +import me.darksidecode.e2eep4j.util.Validate; +import org.apache.commons.codec.binary.Base64; + +public class EncryptionSession implements CryptoSession { + private byte[] input; + private byte[] result; + private E2EKey k; + + public EncryptionSession(byte[] input, E2EKey k) { + this.input = Validate.notEmpty(Validate.notNull(input, "Input cannot be null"), "Input cannot be empty"); + this.k = Validate.notNull(k, "Key cannot be null"); + } + + @Override + public CryptoSession run() { + try { + IvParameterSpec iv = new IvParameterSpec(this.k.getIV()); + SecretKeySpec skc = new SecretKeySpec(this.k.getAES(), "AES"); + Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + c.init(1, skc, iv); + this.result = Base64.encodeBase64(c.doFinal(this.input)); + return this; + } catch (Exception ex) { + throw new E2EException("Failed to encrypt " + this.input.length + " bytes", ex); + } + } + + @Override + public CryptoSession end() { + this.input = this.result = new byte[0]; + this.k = null; + return this; + } + + @Override + public byte[] result() { + if (Validate.notNull(this.result, "The session was never ran").length != 0 && this.k != null) { + byte[] r = (byte[])this.result.clone(); + this.end(); + return r; + } else { + throw new E2EException("Result was already used"); + } + } +} diff --git a/src/main/java/me/darksidecode/e2eep4j/enc/Tools.java b/src/main/java/me/darksidecode/e2eep4j/enc/Tools.java new file mode 100644 index 0000000..27b4357 --- /dev/null +++ b/src/main/java/me/darksidecode/e2eep4j/enc/Tools.java @@ -0,0 +1,165 @@ +package me.darksidecode.e2eep4j.enc; + +import java.util.ArrayList; +import java.util.List; +import me.darksidecode.e2eep4j.E2EException; + +class Tools { + static void reverse(int[] v) { + int x = 0; + + for (int y = v.length - 1; y > x; x++) { + int tmp = v[y]; + v[y] = v[x]; + v[x] = tmp; + y--; + } + } + + static void swapAdjacent(int[] v) { + int[] cp = (int[])v.clone(); + + for (int i = 0; i < cp.length && i + 2 <= cp.length; i += 2) { + v[i] = cp[i + 1]; + v[i + 1] = cp[i]; + } + } + + static byte[] toBytes(int[] arr) { + try { + StringBuilder result = new StringBuilder(); + + for (int i : arr) { + result.append(i).append("\u0000"); + } + + return result.deleteCharAt(result.length() - 1).toString().getBytes("UTF-8"); + } catch (Exception ex) { + throw new E2EException("Failed to encode " + arr.length + " ints", ex); + } + } + + static int[] fromBytes(byte[] bytes) { + try { + String s = new String(bytes, "UTF-8"); + List buf = new ArrayList<>(); + + for (String i : s.split("\u0000")) { + buf.add(Integer.parseInt(i)); + } + + int[] res = new int[buf.size()]; + + for (int i = 0; i < buf.size(); i++) { + res[i] = buf.get(i); + } + + return res; + } catch (Exception e) { + throw new E2EException("Failed to decode " + bytes.length + " bytes", e); + } + } + + static int cover(Object[] coverage, int i) { + if (coverage == null) { + return i; + } else { + int[] var_1 = (int[])coverage[0]; + int[] var_2 = (int[])coverage[1]; + int[] var_3 = (int[])coverage[2]; + int[] var_4 = (int[])coverage[3]; + int[] var_5 = (int[])coverage[4]; + int[] var_6 = (int[])coverage[5]; + int var_7 = ((int[])coverage[5])[1]; + int var_8 = 0 & var_3[0] & 28 & 28 & ((int[])coverage[5])[2] & 23179 & var_1[0] | 263; + int var_9 = 11414; + int var_11 = ((int[])coverage[5])[2]; + int var_12 = var_4[var_2[0] >>> var_11] >> 4827; + int var_13 = var_8 & 11410; + int var_10 = var_8 & 11414 + -((int[])coverage[5])[3]; + i ^= 20; + var_7++; + if (++var_12 != var_12++) { + var_1[0] = i; + } + + while (true) { + i = i ^ var_1[var_2[var_10] >>> var_11] ^ var_2[var_2[var_10] >>> var_11] ^ ~var_3[0] >>> var_11; + i = i + ^ var_3[var_4[var_2[var_10] >>> var_11] >> 4827] + ^ var_2[var_2[var_10] >>> var_11] + ^ var_7 + ^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827]))) + ^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11; + i = i ^ var_1[var_2[var_10] >>> var_11] ^ var_7 ^ var_2[var_2[var_10] >>> var_11] ^ var_3[0] >>> var_11; + i = var_7 ^ var_2[var_2[var_10] >>> var_11] ^ var_3[0] >>> var_11 ^ i ^ var_1[var_2[var_10] >>> var_11]; + i = i + ^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] + ^ var_2[var_2[var_10] >>> var_11] + ^ var_7 + ^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827]))) + ^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11; + i = i ^ var_3[var_2[var_10] >>> var_11] ^ var_2[var_2[var_10] >>> var_11] ^ ~(~var_6[var_2[var_10] >>> var_11]) ^ ~var_3[0] >>> var_11; + i = i + ^ var_1[var_4[var_2[var_2[var_4[var_2[var_10] >>> var_11] >>> var_11] >> 4827] >>> var_11] >> 4827] + ^ var_6[var_2[var_4[var_2[var_10] >>> var_11] >>> var_11] >> 4827] + ^ var_2[var_2[var_10] >>> var_11] + ^ var_7 + ^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827]))) + ^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11; + i = i + ^ var_3[var_4[var_2[var_10] >>> var_11] >> 4827] + ^ var_2[var_2[var_10] >>> var_11] + ^ var_7 + ^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827]))) + ^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11; + i = i ^ var_3[var_2[var_10] >>> var_11] ^ var_2[var_2[var_10] >>> var_11] ^ ~(~var_6[var_2[var_10] >>> var_11]) ^ ~var_3[0] >>> var_11; + i = var_7 ^ var_2[var_2[var_10] >>> var_11] ^ var_3[0] >>> var_11 ^ i ^ var_1[var_2[var_10] >>> var_11]; + i = i ^ var_1[var_2[var_10] >>> var_11] ^ var_4[var_2[var_10] >>> var_11] ^ var_2[var_2[var_10] >>> var_11] ^ var_3[0] >>> var_11; + i = i + ^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] + ^ var_2[var_2[var_10] >>> var_11] + ^ var_7 + ^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827]))) + ^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11; + i = i ^ var_1[var_2[var_10] >>> var_11] ^ var_11 ^ var_2[var_2[var_10] >>> var_11] ^ ~var_3[0] >>> var_11; + i = i + ^ var_1[var_4[var_2[var_2[var_4[var_2[var_10] >>> var_11] >>> var_11] >> 4827] >>> var_11] >> 4827] + ^ var_6[var_2[var_4[var_2[var_10] >>> var_11] >>> var_11] >> 4827] + ^ var_2[var_2[var_10] >>> var_11] + ^ var_7 + ^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827]))) + ^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11; + if (++var_12 > 9999) { + return i; + } + + if (var_12 == 37) { + return i; + } + + if (var_12 == 3462) { + return i; + } + + if (i != var_11 + (i | i | i & i | i)) { + if (i == var_11 + (i & i)) { + i = i + ^ var_1[var_2[var_4[var_10] >>> var_11] >> 4827] + ^ var_2[var_2[var_10] >>> var_11] + ^ var_7 + ^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827]))) + ^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11; + return i ^ var_3[var_4[var_10] >>> var_11] ^ var_11 ^ var_4[var_2[var_10] >>> var_11] ^ ~var_1[0] >>> var_11; + } + + if (var_12 != var_13 && var_7 != var_7 + var_12) { + continue; + } + } + + return i; + } + } + } +} diff --git a/src/main/java/me/darksidecode/e2eep4j/util/Convert.java b/src/main/java/me/darksidecode/e2eep4j/util/Convert.java new file mode 100644 index 0000000..2609c63 --- /dev/null +++ b/src/main/java/me/darksidecode/e2eep4j/util/Convert.java @@ -0,0 +1,80 @@ +package me.darksidecode.e2eep4j.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import me.darksidecode.e2eep4j.E2EException; +import me.darksidecode.e2eep4j.E2EKey; + +public class Convert { + public static byte[] e2eKey2Bytes(E2EKey k) { + try { + byte[] iv = k.getIV(); + byte[] aes = k.getAES(); + byte[] base = k.getBase(); + Object[] cvg = k.shallCoverage() ? k.getCoverage() : new Object[0]; + Object[] r = new Object[iv.length + aes.length + base.length + cvg.length]; + int idx = 0; + + for (byte n : iv) { + r[idx++] = n; + } + + for (byte n : aes) { + r[idx++] = n; + } + + for (byte n : base) { + r[idx++] = n; + } + + for (Object n : cvg) { + r[idx++] = n; + } + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(r); + oos.flush(); + oos.close(); + baos.close(); + return baos.toByteArray(); + } catch (Exception ex) { + throw new E2EException("E2EKey conversion failed", ex); + } + } + + public static E2EKey bytes2e2ekey(byte[] bytes) { + try { + ByteArrayInputStream bis = new ByteArrayInputStream(bytes); + ObjectInputStream ois = new ObjectInputStream(bis); + Object[] r = (Object[])ois.readObject(); + int idx = 0; + byte[] iv = new byte[16]; + byte[] aes = new byte[16]; + byte[] base = new byte[32]; + Object[] cvg = new Object[r.length - 64]; + + for (int i = 0; i < iv.length; i++) { + iv[i] = (Byte)r[idx++]; + } + + for (int i = 0; i < aes.length; i++) { + aes[i] = (Byte)r[idx++]; + } + + for (int i = 0; i < base.length; i++) { + base[i] = (Byte)r[idx++]; + } + + for (int i = 0; i < cvg.length; i++) { + cvg[i] = r[idx++]; + } + + return new E2EKey(iv, aes, base, cvg.length == 0 ? null : cvg); + } catch (Exception e) { + throw new E2EException("Bytes conversion failed", e); + } + } +} diff --git a/src/main/java/me/darksidecode/e2eep4j/util/Generate.java b/src/main/java/me/darksidecode/e2eep4j/util/Generate.java new file mode 100644 index 0000000..1fa4b71 --- /dev/null +++ b/src/main/java/me/darksidecode/e2eep4j/util/Generate.java @@ -0,0 +1,34 @@ +package me.darksidecode.e2eep4j.util; + +import java.security.SecureRandom; +import me.darksidecode.e2eep4j.E2EKey; + +public class Generate { + private static final SecureRandom r = new SecureRandom(); + + public static E2EKey e2eKey() { + return e2eKey(null); + } + + public static E2EKey e2eKey(Object[] cvg) { + return new E2EKey(iv(), aes(), base(), cvg); + } + + public static byte[] iv() { + return byteStream(16); + } + + public static byte[] aes() { + return byteStream(16); + } + + public static byte[] base() { + return byteStream(32); + } + + public static byte[] byteStream(int len) { + byte[] bytes = new byte[Validate.multipleOf(len, 4, "Length must be a multiple of 4")]; + r.nextBytes(bytes); + return (byte[])bytes.clone(); + } +} diff --git a/src/main/java/me/darksidecode/e2eep4j/util/KeySpecs.java b/src/main/java/me/darksidecode/e2eep4j/util/KeySpecs.java new file mode 100644 index 0000000..0482b16 --- /dev/null +++ b/src/main/java/me/darksidecode/e2eep4j/util/KeySpecs.java @@ -0,0 +1,8 @@ +package me.darksidecode.e2eep4j.util; + +public class KeySpecs { + public static final int IV = 16; + public static final int AES = 16; + public static final int BASE = 32; + public static final int COVERAGE = 6; +} diff --git a/src/main/java/me/darksidecode/e2eep4j/util/Validate.java b/src/main/java/me/darksidecode/e2eep4j/util/Validate.java new file mode 100644 index 0000000..4bd4daa --- /dev/null +++ b/src/main/java/me/darksidecode/e2eep4j/util/Validate.java @@ -0,0 +1,67 @@ +package me.darksidecode.e2eep4j.util; + +public class Validate { + public static T notNull(T obj, String msg) { + if (obj == null) { + throw new NullPointerException(msg); + } else { + return obj; + } + } + + public static byte[] notEmpty(byte[] arr, String msg) { + if (arr.length == 0) { + throw new IllegalArgumentException(msg); + } else { + return arr; + } + } + + public static T[] notEmpty(T[] arr, String msg) { + if (arr.length == 0) { + throw new IllegalArgumentException(msg); + } else { + return arr; + } + } + + public static int multipleOf(int i, int m, String msg) { + if (i % m == 0 && i != 0) { + return i; + } else { + throw new ArithmeticException(msg + " (" + i + "%" + m + "!=0)"); + } + } + + public static byte[] ivLength(byte[] n, String msg) { + if (n.length != 16) { + throw new IllegalArgumentException(msg + " (" + n.length + "!=" + 16 + ")"); + } else { + return n; + } + } + + public static byte[] aesLength(byte[] n, String msg) { + if (n.length != 16) { + throw new IllegalArgumentException(msg + " (" + n.length + "!=" + 16 + ")"); + } else { + return n; + } + } + + public static byte[] baseLength(byte[] n, String msg) { + if (n.length != 32) { + throw new IllegalArgumentException(msg + " (" + n.length + "!=" + 32 + ")"); + } else { + return n; + } + } + + public static Object[] cvgLength(Object[] n, String msg) { + if (n.length != 6) { + throw new IllegalArgumentException(msg + " (" + n.length + "!=" + 6 + ")"); + } else { + return n; + } + } +} diff --git a/src/main/java/me/darksidecode/easysockets/client/BasicSocketClient.java b/src/main/java/me/darksidecode/easysockets/client/BasicSocketClient.java new file mode 100644 index 0000000..58640d0 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/client/BasicSocketClient.java @@ -0,0 +1,197 @@ +package me.darksidecode.easysockets.client; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import javax.net.SocketFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; +import me.darksidecode.easysockets.client.config.SocketClientConfig; +import me.darksidecode.easysockets.event.EventCancelledException; +import me.darksidecode.easysockets.event.EventManager; +import me.darksidecode.easysockets.event.EventState; +import me.darksidecode.easysockets.event.client.ClientStartEvent; +import me.darksidecode.easysockets.event.client.ClientStopEvent; +import me.darksidecode.easysockets.event.client.ClientTimeoutEvent; +import me.darksidecode.easysockets.protocol.packet.Packet; +import me.darksidecode.easysockets.util.io.Compressor; + +public class BasicSocketClient { + private final int protocolVersion; + private final String host; + private final int port; + private final Socket socket; + private final DataInputStream input; + private final DataOutputStream output; + private final ProtocolManager protocolManager; + private final EventManager eventManager; + private final SocketClientConfig config; + private SSLContext sslContext; + private boolean stopped; + + @Deprecated + public BasicSocketClient(int protocolVersion, String host, int port, Object __, SocketClientConfig config) { + this(protocolVersion, host, port, config); + } + + public BasicSocketClient(int protocolVersion, String host, int port, SocketClientConfig config) { + if (config.isUseSSL()) { + if (config.getTrustStoreStream() == null) { + throw new RuntimeException("TrustStore stream is null"); + } + + try { + TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + KeyStore trustStore = KeyStore.getInstance("jks"); + trustStore.load(config.getTrustStoreStream(), config.getTrustStorePassword().toCharArray()); + factory.init(trustStore); + this.sslContext = SSLContext.getInstance("TLSv1.2"); + this.sslContext.init(null, factory.getTrustManagers(), SecureRandom.getInstanceStrong()); + } catch (CertificateException | KeyStoreException | KeyManagementException | IOException | NoSuchAlgorithmException ex) { + this.shutdown(); + throw new RuntimeException("failed to start a BasicSocketClient: SSL creation error", ex); + } + } + + try { + if ((this.eventManager = new EventManager()).callEvent(new ClientStartEvent(EventState.PRE, System.currentTimeMillis()))) { + throw new EventCancelledException("Client startup aborted"); + } else { + this.protocolVersion = protocolVersion; + this.host = host; + this.port = port; + this.config = config; + this.socket = config.isUseSSL() + ? this.sslContext.getSocketFactory().createSocket(host, port) + : SocketFactory.getDefault().createSocket(host, port); + this.socket.setSoTimeout(config.getTimeout()); + this.socket.setTcpNoDelay(true); + this.socket.setKeepAlive(true); + if (config.isUseSSL()) { + List ciphers = new ArrayList<>( + Arrays.asList( + "TLS_RSA_WITH_AES_128_CBC_SHA256", + "TLS_RSA_WITH_AES_256_CBC_SHA256", + "TLS_DH_RSA_WITH_AES_128_CBC_SHA256", + "TLS_DH_RSA_WITH_AES_256_CBC_SHA256", + "TLS_RSA_WITH_AES_128_GCM_SHA256", + "TLS_RSA_WITH_AES_256_GCM_SHA384", + "TLS_DH_RSA_WITH_AES_128_GCM_SHA256", + "TLS_DH_RSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", + "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", + "TLS_AES_128_CCM_SHA256", + "TLS_AES_128_GCM_SHA256", + "TLS_AES_256_GCM_SHA384", + "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256", + "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", + "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", + "TLS_CHACHA20_POLY1305_SHA256" + ) + ); + ciphers.retainAll(Arrays.asList(this.sslContext.getServerSocketFactory().getSupportedCipherSuites())); + ((SSLSocket)this.socket).setEnabledCipherSuites(ciphers.toArray(new String[0])); + ((SSLSocket)this.socket).setEnabledProtocols(new String[]{"TLSv1.2"}); + } + + this.input = new DataInputStream(Compressor.newInflateInput(this.socket.getInputStream())); + this.output = new DataOutputStream(Compressor.newDeflateOutput(this.socket.getOutputStream())); + this.protocolManager = new ProtocolManager(protocolVersion, this.socket, this.input, this.output, this.eventManager, config); + new Thread(() -> { + this.eventManager.callEvent(new ClientStartEvent(EventState.POST, System.currentTimeMillis())); + + try { + while (this.socket.isConnected() && !this.socket.isClosed() && !this.stopped) { + try { + int len = this.input.readInt(); + if (len > 0 && len <= config.getMaxPacketSize()) { + byte[] bytes = new byte[len]; + this.input.readFully(bytes, 0, len); + Packet packet = Packet.receivePacket(bytes); + this.protocolManager.receivePacket(packet); + this.protocolManager.getReceiveTracker().reset(); + } + } catch (Exception ignored) { + this.eventManager.callEvent(new ClientTimeoutEvent(EventState.POST, System.currentTimeMillis())); + this.shutdown(); + } + } + } catch (Exception e) { + throw new RuntimeException("Exception in packet processing thread", e); + } finally { + this.shutdown(); + } + }, "Packet Processing Thread").start(); + } + } catch (Exception err) { + throw new RuntimeException("Failed to start a BasicSocketClient", err); + } + } + + public void shutdown() { + this.stopped = true; + + try { + if (this.socket.isConnected() && !this.socket.isClosed()) { + this.socket.close(); + } + + this.input.close(); + this.output.close(); + } catch (Exception ignored) { + } + + this.eventManager.callEvent(new ClientStopEvent(EventState.POST, System.currentTimeMillis())); + } + + public int getProtocolVersion() { + return this.protocolVersion; + } + + public String getHost() { + return this.host; + } + + public int getPort() { + return this.port; + } + + public ProtocolManager getProtocolManager() { + return this.protocolManager; + } + + public EventManager getEventManager() { + return this.eventManager; + } + + public boolean isStopped() { + return this.stopped; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/client/ProtocolManager.java b/src/main/java/me/darksidecode/easysockets/client/ProtocolManager.java new file mode 100644 index 0000000..5785b63 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/client/ProtocolManager.java @@ -0,0 +1,93 @@ +package me.darksidecode.easysockets.client; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.net.Socket; +import java.util.List; +import me.darksidecode.easysockets.client.config.SocketClientConfig; +import me.darksidecode.easysockets.event.EventManager; +import me.darksidecode.easysockets.event.EventState; +import me.darksidecode.easysockets.event.client.ClientPacketReceiveEvent; +import me.darksidecode.easysockets.event.client.ClientPacketSendEvent; +import me.darksidecode.easysockets.protocol.packet.Packet; +import me.darksidecode.easysockets.util.LimitedList; +import me.darksidecode.easysockets.util.Timer; + +public class ProtocolManager { + private final Object sendLock = new Object(); + private final Object receiveLock = new Object(); + private final List recentSent = new LimitedList<>(100); + private final List recentReceived = new LimitedList<>(100); + private final int protocolVersion; + private final Socket socket; + private final DataInputStream in; + private final DataOutputStream out; + private final Timer sendTracker = new Timer(0L); + private final Timer receiveTracker = new Timer(0L); + private final EventManager eventManager; + private final SocketClientConfig config; + + public void sendPacket(Packet packet) { + synchronized (this.sendLock) { + ClientPacketSendEvent e = new ClientPacketSendEvent(EventState.PRE, packet); + if (!this.eventManager.callEvent(e)) { + packet = e.getPacket(); + + try { + packet.writeAll(); + byte[] bytesToSend = packet.send(); + this.out.writeInt(bytesToSend.length); + this.out.write(bytesToSend); + this.out.flush(); + this.recentSent.add(packet); + this.sendTracker.reset(); + this.eventManager.callEvent(new ClientPacketSendEvent(EventState.POST, packet)); + } catch (Exception ex) { + throw new RuntimeException("Failed to send packet", ex); + } + } + } + } + + public void receivePacket(Packet packet) { + ClientPacketReceiveEvent e = new ClientPacketReceiveEvent(EventState.PRE, packet); + if (!this.eventManager.callEvent(e)) { + (packet = e.getPacket()).process(); + this.recentReceived.add(packet); + this.eventManager.callEvent(new ClientPacketReceiveEvent(EventState.POST, packet)); + } + } + + public ProtocolManager(int protocolVersion, Socket socket, DataInputStream in, DataOutputStream out, EventManager eventManager, SocketClientConfig config) { + this.protocolVersion = protocolVersion; + this.socket = socket; + this.in = in; + this.out = out; + this.eventManager = eventManager; + this.config = config; + } + + Object getSendLock() { + return this.sendLock; + } + + Object getReceiveLock() { + return this.receiveLock; + } + + public List getRecentSent() { + return this.recentSent; + } + + public List getRecentReceived() { + return this.recentReceived; + } + + Timer getSendTracker() { + return this.sendTracker; + } + + Timer getReceiveTracker() { + return this.receiveTracker; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/client/config/SCConfigBuilder.java b/src/main/java/me/darksidecode/easysockets/client/config/SCConfigBuilder.java new file mode 100644 index 0000000..8a58a78 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/client/config/SCConfigBuilder.java @@ -0,0 +1,50 @@ +package me.darksidecode.easysockets.client.config; + +import java.io.InputStream; + +public class SCConfigBuilder { + private final SocketClientConfig config = new SocketClientConfig(30000, 65536, 50, 0, false, null, null); + + public SCConfigBuilder timeout(int timeout) { + this.config.setTimeout(timeout); + return this; + } + + public SCConfigBuilder maxPacketSize(int maxPacketSize) { + this.config.setMaxPacketSize(maxPacketSize); + return this; + } + + public SCConfigBuilder sendRateLimit(int sendRateLimit) { + this.config.setSendRateLimit(sendRateLimit); + return this; + } + + public SCConfigBuilder receiveRateLimit(int receive) { + this.config.setReceiveRateLimit(receive); + return this; + } + + public SCConfigBuilder useSSL(boolean use) { + this.config.setUseSSL(use); + return this; + } + + public SCConfigBuilder trustStoreStream(InputStream trustStoreStream) { + this.config.setTrustStoreStream(trustStoreStream); + return this; + } + + public SCConfigBuilder trustStorePassword(String trustStorePassword) { + this.config.setTrustStorePassword(trustStorePassword); + return this; + } + + public SocketClientConfig build() { + return this.config; + } + + public static SocketClientConfig def() { + return new SCConfigBuilder().build(); + } +} diff --git a/src/main/java/me/darksidecode/easysockets/client/config/SocketClientConfig.java b/src/main/java/me/darksidecode/easysockets/client/config/SocketClientConfig.java new file mode 100644 index 0000000..722a1b5 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/client/config/SocketClientConfig.java @@ -0,0 +1,81 @@ +package me.darksidecode.easysockets.client.config; + +import java.io.InputStream; + +public class SocketClientConfig { + private int timeout; + private int maxPacketSize; + private int sendRateLimit; + private int receiveRateLimit; + private boolean useSSL; + private InputStream trustStoreStream; + private String trustStorePassword; + + public SocketClientConfig( + int timeout, int maxPacketSize, int sendRateLimit, int receiveRateLimit, boolean useSSL, InputStream trustStoreStream, String trustStorePassword + ) { + this.timeout = timeout; + this.maxPacketSize = maxPacketSize; + this.sendRateLimit = sendRateLimit; + this.receiveRateLimit = receiveRateLimit; + this.useSSL = useSSL; + this.trustStoreStream = trustStoreStream; + this.trustStorePassword = trustStorePassword; + } + + public int getTimeout() { + return this.timeout; + } + + public int getMaxPacketSize() { + return this.maxPacketSize; + } + + public int getSendRateLimit() { + return this.sendRateLimit; + } + + public int getReceiveRateLimit() { + return this.receiveRateLimit; + } + + public boolean isUseSSL() { + return this.useSSL; + } + + public InputStream getTrustStoreStream() { + return this.trustStoreStream; + } + + public String getTrustStorePassword() { + return this.trustStorePassword; + } + + public void setTimeout(int timeout) { + this.timeout = timeout; + } + + public void setMaxPacketSize(int maxPacketSize) { + this.maxPacketSize = maxPacketSize; + } + + public void setSendRateLimit(int sendRateLimit) { + this.sendRateLimit = sendRateLimit; + } + + public void setReceiveRateLimit(int receiveRateLimit) { + this.receiveRateLimit = receiveRateLimit; + } + + public void setUseSSL(boolean useSSL) { + this.useSSL = useSSL; + } + + public void setTrustStoreStream(InputStream trustStoreStream) { + this.trustStoreStream = trustStoreStream; + } + + public void setTrustStorePassword(String trustStorePassword) { + this.trustStorePassword = trustStorePassword; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/Event.java b/src/main/java/me/darksidecode/easysockets/event/Event.java new file mode 100644 index 0000000..d555356 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/Event.java @@ -0,0 +1,30 @@ +package me.darksidecode.easysockets.event; + +public abstract class Event { + private final EventState state; + private boolean cancelled; + + public boolean isPre() { + return this.state == EventState.PRE; + } + + public boolean isPost() { + return this.state == EventState.POST; + } + + public Event(EventState state) { + this.state = state; + } + + public EventState getState() { + return this.state; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/EventCancelledException.java b/src/main/java/me/darksidecode/easysockets/event/EventCancelledException.java new file mode 100644 index 0000000..8f6add5 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/EventCancelledException.java @@ -0,0 +1,18 @@ +package me.darksidecode.easysockets.event; + +public class EventCancelledException extends RuntimeException { + public EventCancelledException() { + } + + public EventCancelledException(String message) { + super(message); + } + + public EventCancelledException(String message, Throwable cause) { + super(message, cause); + } + + public EventCancelledException(Throwable cause) { + super(cause); + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/EventException.java b/src/main/java/me/darksidecode/easysockets/event/EventException.java new file mode 100644 index 0000000..d4825bf --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/EventException.java @@ -0,0 +1,18 @@ +package me.darksidecode.easysockets.event; + +public class EventException extends RuntimeException { + public EventException() { + } + + public EventException(String message) { + super(message); + } + + public EventException(String message, Throwable cause) { + super(message, cause); + } + + public EventException(Throwable cause) { + super(cause); + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/EventListener.java b/src/main/java/me/darksidecode/easysockets/event/EventListener.java new file mode 100644 index 0000000..cb54e64 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/EventListener.java @@ -0,0 +1,5 @@ +package me.darksidecode.easysockets.event; + +public interface EventListener { + void onEvent(Event event); +} diff --git a/src/main/java/me/darksidecode/easysockets/event/EventManager.java b/src/main/java/me/darksidecode/easysockets/event/EventManager.java new file mode 100644 index 0000000..048452b --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/EventManager.java @@ -0,0 +1,33 @@ +package me.darksidecode.easysockets.event; + +import java.util.ArrayList; +import java.util.List; + +public class EventManager { + private final Object registryLock = new Object(); + private final Object eventLock = new Object(); + private final List listeners = new ArrayList<>(); + + public void registerListener(EventListener listener) { + synchronized (this.registryLock) { + if (!this.listeners.contains(listener)) { + this.listeners.add(listener); + } + } + } + + public void unregisterListener(EventListener listener) { + synchronized (this.registryLock) { + this.listeners.remove(listener); + } + } + + public boolean callEvent(Event e) { + try { + ((ArrayList)((ArrayList)this.listeners).clone()).forEach(listener -> listener.onEvent(e)); + return e.isCancelled(); + } catch (Exception ex) { + throw new EventException("Error processing event " + e.getClass().getSimpleName() + "/" + e.getState().name(), ex); + } + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/EventState.java b/src/main/java/me/darksidecode/easysockets/event/EventState.java new file mode 100644 index 0000000..8d53f55 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/EventState.java @@ -0,0 +1,6 @@ +package me.darksidecode.easysockets.event; + +public enum EventState { + PRE, + POST; +} diff --git a/src/main/java/me/darksidecode/easysockets/event/client/ClientKeyExchangeCompleteEvent.java b/src/main/java/me/darksidecode/easysockets/event/client/ClientKeyExchangeCompleteEvent.java new file mode 100644 index 0000000..431943c --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/client/ClientKeyExchangeCompleteEvent.java @@ -0,0 +1,10 @@ +package me.darksidecode.easysockets.event.client; + +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventState; + +public class ClientKeyExchangeCompleteEvent extends Event { + public ClientKeyExchangeCompleteEvent() { + super(EventState.POST); + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/client/ClientPacketReceiveEvent.java b/src/main/java/me/darksidecode/easysockets/event/client/ClientPacketReceiveEvent.java new file mode 100644 index 0000000..e13764c --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/client/ClientPacketReceiveEvent.java @@ -0,0 +1,22 @@ +package me.darksidecode.easysockets.event.client; + +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventState; +import me.darksidecode.easysockets.protocol.packet.Packet; + +public class ClientPacketReceiveEvent extends Event { + private Packet packet; + + public ClientPacketReceiveEvent(EventState state, Packet packet) { + super(state); + this.packet = packet; + } + + public Packet getPacket() { + return this.packet; + } + + public void setPacket(Packet packet) { + this.packet = packet; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/client/ClientPacketSendEvent.java b/src/main/java/me/darksidecode/easysockets/event/client/ClientPacketSendEvent.java new file mode 100644 index 0000000..b745dff --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/client/ClientPacketSendEvent.java @@ -0,0 +1,22 @@ +package me.darksidecode.easysockets.event.client; + +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventState; +import me.darksidecode.easysockets.protocol.packet.Packet; + +public class ClientPacketSendEvent extends Event { + private Packet packet; + + public ClientPacketSendEvent(EventState state, Packet packet) { + super(state); + this.packet = packet; + } + + public Packet getPacket() { + return this.packet; + } + + public void setPacket(Packet packet) { + this.packet = packet; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/client/ClientStartEvent.java b/src/main/java/me/darksidecode/easysockets/event/client/ClientStartEvent.java new file mode 100644 index 0000000..4fa270d --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/client/ClientStartEvent.java @@ -0,0 +1,17 @@ +package me.darksidecode.easysockets.event.client; + +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventState; + +public class ClientStartEvent extends Event { + private final long time; + + public ClientStartEvent(EventState state, long time) { + super(state); + this.time = time; + } + + public long getTime() { + return this.time; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/client/ClientStopEvent.java b/src/main/java/me/darksidecode/easysockets/event/client/ClientStopEvent.java new file mode 100644 index 0000000..12ea1e1 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/client/ClientStopEvent.java @@ -0,0 +1,17 @@ +package me.darksidecode.easysockets.event.client; + +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventState; + +public class ClientStopEvent extends Event { + private final long time; + + public ClientStopEvent(EventState state, long time) { + super(state); + this.time = time; + } + + public long getTime() { + return this.time; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/client/ClientTimeoutEvent.java b/src/main/java/me/darksidecode/easysockets/event/client/ClientTimeoutEvent.java new file mode 100644 index 0000000..3be3d0a --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/client/ClientTimeoutEvent.java @@ -0,0 +1,17 @@ +package me.darksidecode.easysockets.event.client; + +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventState; + +public class ClientTimeoutEvent extends Event { + private final long time; + + public ClientTimeoutEvent(EventState state, long time) { + super(state); + this.time = time; + } + + public long getTime() { + return this.time; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/server/ServerKeyExchangeCompleteEvent.java b/src/main/java/me/darksidecode/easysockets/event/server/ServerKeyExchangeCompleteEvent.java new file mode 100644 index 0000000..c6cf667 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/server/ServerKeyExchangeCompleteEvent.java @@ -0,0 +1,18 @@ +package me.darksidecode.easysockets.event.server; + +import java.net.Socket; +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventState; + +public class ServerKeyExchangeCompleteEvent extends Event { + private final Socket client; + + public ServerKeyExchangeCompleteEvent(Socket client) { + super(EventState.POST); + this.client = client; + } + + public Socket getClient() { + return this.client; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/server/ServerStartEvent.java b/src/main/java/me/darksidecode/easysockets/event/server/ServerStartEvent.java new file mode 100644 index 0000000..4a6ea4e --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/server/ServerStartEvent.java @@ -0,0 +1,17 @@ +package me.darksidecode.easysockets.event.server; + +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventState; + +public class ServerStartEvent extends Event { + private final long time; + + public ServerStartEvent(EventState state, long time) { + super(state); + this.time = time; + } + + public long getTime() { + return this.time; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/server/ServerStopEvent.java b/src/main/java/me/darksidecode/easysockets/event/server/ServerStopEvent.java new file mode 100644 index 0000000..1f150e4 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/server/ServerStopEvent.java @@ -0,0 +1,17 @@ +package me.darksidecode.easysockets.event.server; + +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventState; + +public class ServerStopEvent extends Event { + private final long time; + + public ServerStopEvent(EventState state, long time) { + super(state); + this.time = time; + } + + public long getTime() { + return this.time; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketConnectEvent.java b/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketConnectEvent.java new file mode 100644 index 0000000..52ff7d7 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketConnectEvent.java @@ -0,0 +1,10 @@ +package me.darksidecode.easysockets.event.server.socket; + +import java.net.Socket; +import me.darksidecode.easysockets.event.EventState; + +public class SocketConnectEvent extends SocketEvent { + public SocketConnectEvent(EventState state, Socket socket) { + super(state, socket); + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketDisconnectEvent.java b/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketDisconnectEvent.java new file mode 100644 index 0000000..0d01282 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketDisconnectEvent.java @@ -0,0 +1,10 @@ +package me.darksidecode.easysockets.event.server.socket; + +import java.net.Socket; +import me.darksidecode.easysockets.event.EventState; + +public class SocketDisconnectEvent extends SocketEvent { + public SocketDisconnectEvent(EventState state, Socket socket) { + super(state, socket); + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketEvent.java b/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketEvent.java new file mode 100644 index 0000000..152555c --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketEvent.java @@ -0,0 +1,18 @@ +package me.darksidecode.easysockets.event.server.socket; + +import java.net.Socket; +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventState; + +public class SocketEvent extends Event { + private final Socket socket; + + public SocketEvent(EventState state, Socket socket) { + super(state); + this.socket = socket; + } + + public Socket getSocket() { + return this.socket; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketPacketReceiveEvent.java b/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketPacketReceiveEvent.java new file mode 100644 index 0000000..8c446d3 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketPacketReceiveEvent.java @@ -0,0 +1,22 @@ +package me.darksidecode.easysockets.event.server.socket; + +import java.net.Socket; +import me.darksidecode.easysockets.event.EventState; +import me.darksidecode.easysockets.protocol.packet.Packet; + +public class SocketPacketReceiveEvent extends SocketEvent { + private Packet packet; + + public SocketPacketReceiveEvent(EventState state, Socket socket, Packet packet) { + super(state, socket); + this.packet = packet; + } + + public Packet getPacket() { + return this.packet; + } + + public void setPacket(Packet packet) { + this.packet = packet; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketPacketSendEvent.java b/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketPacketSendEvent.java new file mode 100644 index 0000000..573bc89 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/event/server/socket/SocketPacketSendEvent.java @@ -0,0 +1,22 @@ +package me.darksidecode.easysockets.event.server.socket; + +import java.net.Socket; +import me.darksidecode.easysockets.event.EventState; +import me.darksidecode.easysockets.protocol.packet.Packet; + +public class SocketPacketSendEvent extends SocketEvent { + private Packet packet; + + public SocketPacketSendEvent(EventState state, Socket socket, Packet packet) { + super(state, socket); + this.packet = packet; + } + + public Packet getPacket() { + return this.packet; + } + + public void setPacket(Packet packet) { + this.packet = packet; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/protocol/packet/Packet.java b/src/main/java/me/darksidecode/easysockets/protocol/packet/Packet.java new file mode 100644 index 0000000..411de71 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/protocol/packet/Packet.java @@ -0,0 +1,79 @@ +package me.darksidecode.easysockets.protocol.packet; + +import me.darksidecode.easysockets.protocol.processing.PacketProcessing; +import me.darksidecode.easysockets.util.io.IO; + +public class Packet { + private PacketContents contents; + private final String type; + + public Packet(String type) { + this(type, new PacketContents()); + } + + public Packet(String type, PacketContents contents) { + this.type = type; + this.contents = contents; + } + + public boolean process() { + return PacketProcessing.process(this); + } + + public Packet setContents(PacketContents contents) { + this.contents = contents; + return this; + } + + public byte[] send() { + return sendPacket(this); + } + + public Packet receive(byte[] in) { + RawPacket raw = receiveRaw(in); + if (!raw.getType().equals(this.type)) { + throw new PacketSignatureError("Packet type mismatch: " + raw.getType() + ", expected " + this.type); + } else { + return this.setContents(new PacketContents(raw.getContents())); + } + } + + public Packet writeAll() { + return this; + } + + public Packet readAll() { + return this; + } + + public static byte[] sendPacket(Packet p) { + return IO.ser(new RawPacket(p.getType(), p.getContents().getRaw())); + } + + @Override + public String toString() { + return this.type + this.contents.toString(); + } + + public static Packet receivePacket(byte[] in) { + RawPacket raw = receiveRaw(in); + return new Packet(raw.getType(), new PacketContents(raw.getContents())); + } + + public static RawPacket receiveRaw(byte[] in) { + Object obj = IO.deser(in); + if (obj != null && obj instanceof RawPacket) { + return (RawPacket)obj; + } else { + throw new PacketSignatureError("Invalid packet received"); + } + } + + public PacketContents getContents() { + return this.contents; + } + + public String getType() { + return this.type; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/protocol/packet/PacketContents.java b/src/main/java/me/darksidecode/easysockets/protocol/packet/PacketContents.java new file mode 100644 index 0000000..7d54304 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/protocol/packet/PacketContents.java @@ -0,0 +1,144 @@ +package me.darksidecode.easysockets.protocol.packet; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class PacketContents { + private final Map raw; + + public PacketContents() { + this(new ConcurrentHashMap<>()); + } + + public PacketContents(Map source) { + this.raw = source; + } + + public PacketContents write(int index, Object obj) { + if (obj == null) { + throw new NullPointerException("Cannot write NULL object"); + } else { + this.raw.put(index, obj); + return this; + } + } + + public String readString(int index) { + return this.read(index); + } + + public String readStringSafely(int index) { + return this.readSafely(index); + } + + public Integer readInteger(int index) { + return this.read(index); + } + + public Integer readIntegerSafely(int index) { + return this.readSafely(index); + } + + public Short readShort(int index) { + return this.read(index); + } + + public Short readShortSafely(int index) { + return this.readSafely(index); + } + + public Long readLong(int index) { + return this.read(index); + } + + public Long readLongSafely(int index) { + return this.readSafely(index); + } + + public Double readDouble(int index) { + return this.read(index); + } + + public Double readDoubleSafely(int index) { + return this.readSafely(index); + } + + public Float readFloat(int index) { + return this.read(index); + } + + public Float readFloatSafely(int index) { + return this.readSafely(index); + } + + public Byte readByte(int index) { + return this.read(index); + } + + public Byte readByteSafely(int index) { + return this.readSafely(index); + } + + public Boolean readBoolean(int index) { + return this.read(index); + } + + public Boolean readBooleanSafely(int index) { + return this.readSafely(index); + } + + public Object readObject(int index) { + return this.read(index); + } + + public Object readObjectSafely(int index) { + return this.readSafely(index); + } + + public T read(int index) { + return (T)this.readRaw(index); + } + + public T readSafely(int index) { + Object obj = this.readRawSafely(index); + return (T)(obj == null ? null : obj); + } + + public Object readRaw(int index) { + if (!this.raw.containsKey(index)) { + throw new IndexOutOfBoundsException("Index out of packet content range: " + index); + } else { + return this.raw.get(index); + } + } + + public Object readRawSafely(int index) { + return this.raw.getOrDefault(index, null); + } + + public Class getClass(int index) { + Object obj = this.readRawSafely(index); + return obj == null ? null : obj.getClass(); + } + + @Override + public String toString() { + StringBuilder s = new StringBuilder(); + s.append('['); + + for (Integer k : this.raw.keySet()) { + s.append(k).append(": ").append(this.raw.get(k).toString()).append(','); + } + + if (s.length() > 1) { + s.deleteCharAt(s.length() - 1); + } + + s.append(']'); + return s.toString(); + } + + public Map getRaw() { + return this.raw; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/protocol/packet/PacketSignatureError.java b/src/main/java/me/darksidecode/easysockets/protocol/packet/PacketSignatureError.java new file mode 100644 index 0000000..580f07b --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/protocol/packet/PacketSignatureError.java @@ -0,0 +1,18 @@ +package me.darksidecode.easysockets.protocol.packet; + +public class PacketSignatureError extends RuntimeException { + public PacketSignatureError() { + } + + public PacketSignatureError(String message) { + super(message); + } + + public PacketSignatureError(String message, Throwable cause) { + super(message, cause); + } + + public PacketSignatureError(Throwable cause) { + super(cause); + } +} diff --git a/src/main/java/me/darksidecode/easysockets/protocol/packet/RawPacket.java b/src/main/java/me/darksidecode/easysockets/protocol/packet/RawPacket.java new file mode 100644 index 0000000..0cd2879 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/protocol/packet/RawPacket.java @@ -0,0 +1,23 @@ +package me.darksidecode.easysockets.protocol.packet; + +import java.io.Serializable; +import java.util.Map; + +public class RawPacket implements Serializable { + private static final long serialVersionUID = 331896648141185773L; + private final String type; + private final Map contents; + + public RawPacket(String type, Map contents) { + this.type = type; + this.contents = contents; + } + + public String getType() { + return this.type; + } + + public Map getContents() { + return this.contents; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/protocol/processing/PacketProcessing.java b/src/main/java/me/darksidecode/easysockets/protocol/processing/PacketProcessing.java new file mode 100644 index 0000000..eed3539 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/protocol/processing/PacketProcessing.java @@ -0,0 +1,18 @@ +package me.darksidecode.easysockets.protocol.processing; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import me.darksidecode.easysockets.protocol.packet.Packet; + +public class PacketProcessing { + private static final Map processors = new ConcurrentHashMap<>(); + + public static boolean process(Packet packet) { + PacketProcessor pp = processors.get(packet.getType()); + return pp == null ? false : pp.process(packet); + } + + public static void setProcessor(String type, PacketProcessor pp) { + processors.put(type, pp); + } +} diff --git a/src/main/java/me/darksidecode/easysockets/protocol/processing/PacketProcessor.java b/src/main/java/me/darksidecode/easysockets/protocol/processing/PacketProcessor.java new file mode 100644 index 0000000..935b632 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/protocol/processing/PacketProcessor.java @@ -0,0 +1,7 @@ +package me.darksidecode.easysockets.protocol.processing; + +import me.darksidecode.easysockets.protocol.packet.Packet; + +public interface PacketProcessor { + boolean process(Packet packet); +} diff --git a/src/main/java/me/darksidecode/easysockets/server/BasicSocketServer.java b/src/main/java/me/darksidecode/easysockets/server/BasicSocketServer.java new file mode 100644 index 0000000..b172d62 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/server/BasicSocketServer.java @@ -0,0 +1,225 @@ +package me.darksidecode.easysockets.server; + +import java.io.File; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.security.Security; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import javax.net.ServerSocketFactory; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import me.darksidecode.easysockets.event.EventCancelledException; +import me.darksidecode.easysockets.event.EventManager; +import me.darksidecode.easysockets.event.EventState; +import me.darksidecode.easysockets.event.server.ServerStartEvent; +import me.darksidecode.easysockets.event.server.ServerStopEvent; +import me.darksidecode.easysockets.server.config.SocketServerConfig; +import org.bouncycastle.jce.provider.BouncyCastleProvider; + +public class BasicSocketServer { + private static final long KICK_FREQ = TimeUnit.MINUTES.toMillis(1L); + private final Object kickQueueLock = new Object(); + private final int protocolVersion; + private final int port; + private final ServerSocket serverSocket; + private final ProtocolManager protocolManager; + private final EventManager eventManager; + private final SocketServerConfig config; + private final Map socketListeners = new ConcurrentHashMap<>(); + private final Set kickQueue = new HashSet<>(); + private final int maxConnections; + private final ServerStats stats; + + @Deprecated + public BasicSocketServer(int protocolVersion, int port, int backlog, int maxConnections, Object __, SocketServerConfig config) { + this(protocolVersion, port, backlog, maxConnections, config); + } + + public BasicSocketServer(int protocolVersion, int port, int backlog, int maxConnections, SocketServerConfig config) { + if ((this.eventManager = new EventManager()).callEvent(new ServerStartEvent(EventState.PRE, System.currentTimeMillis()))) { + throw new EventCancelledException("Server startup aborted"); + } else { + if (config.isUseSSL()) { + File keyStoreFile = new File(config.getPathToKeyStore()); + if (!keyStoreFile.exists()) { + throw new RuntimeException("KeyStore file does not exist: " + keyStoreFile.getAbsolutePath()); + } + + Security.addProvider(new BouncyCastleProvider()); + System.setProperty("javax.net.ssl.keyStore", keyStoreFile.getAbsolutePath()); + System.setProperty("javax.net.ssl.keyStorePassword", config.getKeyStorePassword()); + } + + this.protocolVersion = protocolVersion; + this.port = port; + this.maxConnections = maxConnections; + this.config = config; + + try { + this.serverSocket = config.isUseSSL() + ? SSLServerSocketFactory.getDefault().createServerSocket() + : ServerSocketFactory.getDefault().createServerSocket(); + this.stats = new ServerStats(System.currentTimeMillis()); + this.protocolManager = new ProtocolManager(this, protocolVersion, this.serverSocket, this.stats, this.eventManager, config); + if (config.isUseSSL()) { + List ciphers = new ArrayList<>( + Arrays.asList( + "TLS_RSA_WITH_AES_128_CBC_SHA256", + "TLS_RSA_WITH_AES_256_CBC_SHA256", + "TLS_DH_RSA_WITH_AES_128_CBC_SHA256", + "TLS_DH_RSA_WITH_AES_256_CBC_SHA256", + "TLS_RSA_WITH_AES_128_GCM_SHA256", + "TLS_RSA_WITH_AES_256_GCM_SHA384", + "TLS_DH_RSA_WITH_AES_128_GCM_SHA256", + "TLS_DH_RSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", + "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", + "TLS_AES_128_CCM_SHA256", + "TLS_AES_128_GCM_SHA256", + "TLS_AES_256_GCM_SHA384", + "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256", + "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", + "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", + "TLS_CHACHA20_POLY1305_SHA256" + ) + ); + ciphers.retainAll(Arrays.asList(((SSLServerSocketFactory)SSLServerSocketFactory.getDefault()).getSupportedCipherSuites())); + ((SSLServerSocket)this.serverSocket).setEnabledCipherSuites(ciphers.toArray(new String[0])); + ((SSLServerSocket)this.serverSocket).setEnabledProtocols(new String[]{"TLSv1.2"}); + } + + this.serverSocket.bind(new InetSocketAddress("0.0.0.0", this.port), backlog); + new Thread(() -> { + new Timer().schedule(new TimerTask() { + @Override + public void run() { + synchronized (BasicSocketServer.this.kickQueueLock) { + BasicSocketServer.this.kickQueue.forEach(x$0 -> BasicSocketServer.this.kick0(x$0)); + BasicSocketServer.this.kickQueue.clear(); + } + } + }, KICK_FREQ, KICK_FREQ); + this.eventManager.callEvent(new ServerStartEvent(EventState.POST, System.currentTimeMillis())); + + try { + while (!this.serverSocket.isClosed()) { + try { + if (this.socketListeners.keySet().size() < maxConnections) { + Socket client = this.serverSocket.accept(); + SocketListener listener = new SocketListener(this, client, this.protocolManager, this.stats, this.eventManager, config); + this.socketListeners.put(client, listener); + listener.start(); + } + } catch (Exception ex) { + if (!(ex instanceof EventCancelledException)) { + System.err.println("[EasySockets] Error accepting new socket connection"); + ex.printStackTrace(); + } + } + } + } catch (Exception e) { + throw new RuntimeException("Exception starting packet processing thread", e); + } + + this.shutdown(); + }, "Packet Processing Thread").start(); + } catch (Exception cause) { + throw new RuntimeException("Failed to start a BasicSocketServer", cause); + } + } + } + + private void kick0(Socket s) { + SocketListener listener = this.socketListeners.get(s); + if (listener != null) { + this.socketListeners.remove(s); + } + } + + void addToKickQueue(Socket s) { + synchronized (this.kickQueue) { + this.kickQueue.add(s); + } + } + + public void kick(Socket s) { + SocketListener listener = this.socketListeners.get(s); + if (listener != null) { + this.socketListeners.remove(s); + listener.endQuietly(); + } + } + + public void shutdown() { + try { + if (!this.serverSocket.isClosed()) { + this.serverSocket.close(); + } + } catch (Exception ignored) { + } + + this.eventManager.callEvent(new ServerStopEvent(EventState.POST, System.currentTimeMillis())); + } + + public int getProtocolVersion() { + return this.protocolVersion; + } + + public int getPort() { + return this.port; + } + + public ProtocolManager getProtocolManager() { + return this.protocolManager; + } + + public EventManager getEventManager() { + return this.eventManager; + } + + public SocketServerConfig getConfig() { + return this.config; + } + + Map getSocketListeners() { + return this.socketListeners; + } + + public Set getKickQueue() { + return this.kickQueue; + } + + public int getMaxConnections() { + return this.maxConnections; + } + + public ServerStats getStats() { + return this.stats; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/server/ProtocolManager.java b/src/main/java/me/darksidecode/easysockets/server/ProtocolManager.java new file mode 100644 index 0000000..eb5e1f4 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/server/ProtocolManager.java @@ -0,0 +1,186 @@ +package me.darksidecode.easysockets.server; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import me.darksidecode.easysockets.event.EventManager; +import me.darksidecode.easysockets.event.EventState; +import me.darksidecode.easysockets.event.server.socket.SocketDisconnectEvent; +import me.darksidecode.easysockets.event.server.socket.SocketPacketReceiveEvent; +import me.darksidecode.easysockets.event.server.socket.SocketPacketSendEvent; +import me.darksidecode.easysockets.protocol.packet.Packet; +import me.darksidecode.easysockets.server.config.SocketServerConfig; +import me.darksidecode.easysockets.util.LimitedList; +import me.darksidecode.easysockets.util.Timer; +import me.darksidecode.easysockets.util.io.Compressor; + +public class ProtocolManager { + private final BasicSocketServer server; + private final Map sendLocks = new ConcurrentHashMap<>(); + private final Map receiveLocks = new ConcurrentHashMap<>(); + private final Map dosMap = new ConcurrentHashMap<>(); + private final List recentSent = new LimitedList<>(100); + private final List recentReceived = new LimitedList<>(100); + private final int protocolVersion; + private final ServerSocket socket; + private final ServerStats stats; + private final Map sendTrackers = new ConcurrentHashMap<>(); + private final Map receiveTrackers = new ConcurrentHashMap<>(); + private final EventManager eventManager; + private final SocketServerConfig config; + + public void sendPacketSynchronouslyLazily(Socket target, Packet packet) { + if (target.isClosed()) { + this.socketDisconnected(target); + } else { + SocketListener listenerThread = this.server.getSocketListeners().get(target); + if (listenerThread != null) { + listenerThread.addToSyncLazySendQueue(packet); + } else { + System.err + .println( + "Unable to send packet " + + packet.toString() + + " synchronously lazily to " + + target.getInetAddress().getHostAddress() + + ": no listener thread bound" + ); + } + } + } + + public void sendPacket(Socket target, Packet packet) { + if (target.isClosed()) { + this.socketDisconnected(target); + } else { + Timer sendTracker = this.getSendTracker(target); + SocketPacketSendEvent e = new SocketPacketSendEvent(EventState.PRE, target, packet); + if (!this.eventManager.callEvent(e)) { + packet = e.getPacket(); + long debugId = System.nanoTime() % 1000L; + long beginTime = System.currentTimeMillis(); + + try { + packet.writeAll(); + long serBegin = System.currentTimeMillis(); + byte[] bytesToSend = packet.send(); + long serEnd = System.currentTimeMillis(); + + try { + long dosBegin = System.currentTimeMillis(); + DataOutputStream dataOut = this.getDataOutputStream(target); + long dosEnd = System.currentTimeMillis(); + if (dataOut == null) { + return; + } + + long wintBegin = System.currentTimeMillis(); + dataOut.writeInt(bytesToSend.length); + long wintEnd = System.currentTimeMillis(); + long wbytesBegin = System.currentTimeMillis(); + dataOut.write(bytesToSend); + long wbytesEnd = System.currentTimeMillis(); + dataOut.flush(); + this.stats.bytesSent += (long)bytesToSend.length; + long endTime = System.currentTimeMillis(); + long elapsed = endTime - beginTime; + } catch (SocketException ignored) { + this.socketDisconnected(target); + return; + } + + this.recentSent.add(packet); + sendTracker.reset(); + this.eventManager.callEvent(new SocketPacketSendEvent(EventState.POST, target, packet)); + } catch (Exception ex) { + System.err.println("### pain in the ass ###"); + System.err.println("socket: " + target.getInetAddress().getHostAddress() + ", packet: " + packet.toString() + ", stacktrace:"); + ex.printStackTrace(); + } + } + } + } + + public void receivePacket(Socket sender, Packet packet) { + SocketPacketReceiveEvent e = new SocketPacketReceiveEvent(EventState.PRE, sender, packet); + if (!this.eventManager.callEvent(e)) { + (packet = e.getPacket()).process(); + this.recentReceived.add(packet); + this.eventManager.callEvent(new SocketPacketReceiveEvent(EventState.POST, sender, packet)); + } + } + + public void socketDisconnected(Socket s) { + this.receiveTrackers.remove(s); + this.receiveLocks.remove(s); + this.sendTrackers.remove(s); + this.sendLocks.remove(s); + this.dosMap.remove(s); + this.eventManager.callEvent(new SocketDisconnectEvent(EventState.POST, s)); + } + + private DataOutputStream getDataOutputStream(Socket s) { + return this.dosMap.computeIfAbsent(s, k -> { + try { + return new DataOutputStream(Compressor.newDeflateOutput(s.getOutputStream())); + } catch (SocketException ignored) { + this.socketDisconnected(s); + return null; + } catch (IOException ex) { + throw new RuntimeException("Failed to obtain DOS of " + s.getInetAddress().getHostAddress(), ex); + } + }); + } + + private Timer getSendTracker(Socket s) { + return this.sendTrackers.computeIfAbsent(s, k -> new Timer()); + } + + Timer getReceiveTracker(Socket s) { + return this.receiveTrackers.computeIfAbsent(s, k -> new Timer(0L)); + } + + public ProtocolManager( + BasicSocketServer server, int protocolVersion, ServerSocket socket, ServerStats stats, EventManager eventManager, SocketServerConfig config + ) { + this.server = server; + this.protocolVersion = protocolVersion; + this.socket = socket; + this.stats = stats; + this.eventManager = eventManager; + this.config = config; + } + + Map getSendLocks() { + return this.sendLocks; + } + + Map getReceiveLocks() { + return this.receiveLocks; + } + + public Map getDosMap() { + return this.dosMap; + } + + public List getRecentSent() { + return this.recentSent; + } + + public List getRecentReceived() { + return this.recentReceived; + } + + Map getSendTrackers() { + return this.sendTrackers; + } + + Map getReceiveTrackers() { + return this.receiveTrackers; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/server/ServerStats.java b/src/main/java/me/darksidecode/easysockets/server/ServerStats.java new file mode 100644 index 0000000..c4c82dd --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/server/ServerStats.java @@ -0,0 +1,15 @@ +package me.darksidecode.easysockets.server; + +import java.io.Serializable; + +public class ServerStats implements Serializable { + private static final long serialVersionUID = 2770526316580474952L; + public final long startTime; + public volatile long bytesSent; + public volatile long bytesReceived; + public volatile long connectionsRegistered; + + public ServerStats(long startTime) { + this.startTime = startTime; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/server/SocketListener.java b/src/main/java/me/darksidecode/easysockets/server/SocketListener.java new file mode 100644 index 0000000..479f82c --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/server/SocketListener.java @@ -0,0 +1,169 @@ +package me.darksidecode.easysockets.server; + +import java.io.DataInputStream; +import java.io.IOException; +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; +import me.darksidecode.easysockets.event.EventCancelledException; +import me.darksidecode.easysockets.event.EventManager; +import me.darksidecode.easysockets.event.EventState; +import me.darksidecode.easysockets.event.server.socket.SocketConnectEvent; +import me.darksidecode.easysockets.protocol.packet.Packet; +import me.darksidecode.easysockets.server.config.SocketServerConfig; +import me.darksidecode.easysockets.util.io.Compressor; + +class SocketListener extends Thread { + private final BasicSocketServer server; + private final Socket socket; + private final EventManager eventManager; + private final ProtocolManager protocolManager; + private final ServerStats stats; + private final SocketServerConfig config; + private boolean closed; + private boolean error; + private final List syncLazySendQueue = new ArrayList<>(); + private final Object syncLazySendQueueLock = new Object(); + + SocketListener( + BasicSocketServer server, Socket socket, ProtocolManager protocolManager, ServerStats stats, EventManager eventManager, SocketServerConfig config + ) throws IOException { + this.setName(socket.getInetAddress().getHostName() + " Socket Listener Thread #" + System.nanoTime()); + this.server = server; + this.socket = socket; + this.config = config; + this.eventManager = eventManager; + this.protocolManager = protocolManager; + this.stats = stats; + if (eventManager.callEvent(new SocketConnectEvent(EventState.PRE, socket))) { + if (!socket.isClosed()) { + socket.close(); + } + + throw new EventCancelledException(); + } + } + + @Override + public void run() { + this.establishConnection(); + + try { + DataInputStream in = new DataInputStream(Compressor.newInflateInput(this.socket.getInputStream())); + + while (this.socket.isConnected() && !this.socket.isClosed() && !this.closed) { + int len = in.readInt(); + if (len > 0 && len <= this.config.getMaxPacketSize()) { + byte[] bytes = new byte[len]; + in.readFully(bytes, 0, len); + this.stats.bytesReceived += (long)bytes.length; + Packet packet = Packet.receivePacket(bytes); + this.protocolManager.receivePacket(this.socket, packet); + } + + synchronized (this.syncLazySendQueueLock) { + int i = 0; + + for (Packet packet : this.syncLazySendQueue) { + try { + this.protocolManager.sendPacket(this.socket, packet); + } catch (Exception ex) { + System.err + .println( + "Failed to send packet " + + packet.toString() + + " (index " + + i + + ") synchronously to " + + this.socket.getInetAddress().getHostAddress() + + " (through socket listener thread: " + + this.getName() + + "). Stacktrace:" + ); + ex.printStackTrace(); + } finally { + i++; + } + } + + this.syncLazySendQueue.clear(); + } + } + + if (!this.error && !this.closed) { + this.end(null); + } + } catch (IOException e) { + this.end(new RuntimeException("Exception in " + this.getName(), e)); + } + } + + void addToSyncLazySendQueue(Packet packet) { + synchronized (this.syncLazySendQueueLock) { + this.syncLazySendQueue.add(packet); + } + } + + private void establishConnection() { + try { + this.socket.setSoTimeout(this.config.getTimeout()); + this.stats.connectionsRegistered++; + this.protocolManager.getReceiveLocks().put(this.socket, new Object()); + this.protocolManager.getSendLocks().put(this.socket, new Object()); + this.socket.setTcpNoDelay(true); + this.socket.setKeepAlive(true); + } catch (Exception ex) { + throw new RuntimeException("Failed to setup a socket listener", ex); + } + + this.eventManager.callEvent(new SocketConnectEvent(EventState.POST, this.socket)); + } + + void end(Throwable problem) { + if (!this.closed || problem != null) { + this.error = problem != null; + this.closed = true; + if (this.error) { + problem.printStackTrace(); + } + + if (!this.socket.isClosed()) { + try { + this.socket.close(); + } catch (Exception ignored) { + } + } + + this.protocolManager.socketDisconnected(this.socket); + this.server.addToKickQueue(this.socket); + } + } + + void endQuietly() { + this.closed = true; + if (!this.socket.isClosed()) { + try { + this.socket.close(); + } catch (Exception ignoredEx) { + } + } + + this.protocolManager.socketDisconnected(this.socket); + } + + public boolean isClosed() { + return this.closed; + } + + public boolean isError() { + return this.error; + } + + public void setClosed(boolean closed) { + this.closed = closed; + } + + public void setError(boolean error) { + this.error = error; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/server/config/SSConfigBuilder.java b/src/main/java/me/darksidecode/easysockets/server/config/SSConfigBuilder.java new file mode 100644 index 0000000..23bce42 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/server/config/SSConfigBuilder.java @@ -0,0 +1,48 @@ +package me.darksidecode.easysockets.server.config; + +public class SSConfigBuilder { + private final SocketServerConfig config = new SocketServerConfig(30000, 65536, 50, 0, false, null, null); + + public SSConfigBuilder timeout(int timeout) { + this.config.setTimeout(timeout); + return this; + } + + public SSConfigBuilder maxPacketSize(int maxPacketSize) { + this.config.setMaxPacketSize(maxPacketSize); + return this; + } + + public SSConfigBuilder sendRateLimit(int sendRateLimit) { + this.config.setSendRateLimit(sendRateLimit); + return this; + } + + public SSConfigBuilder receiveRateLimit(int receive) { + this.config.setReceiveRateLimit(receive); + return this; + } + + public SSConfigBuilder useSSL(boolean use) { + this.config.setUseSSL(use); + return this; + } + + public SSConfigBuilder pathToKeyStore(String pathToKeyStore) { + this.config.setPathToKeyStore(pathToKeyStore); + return this; + } + + public SSConfigBuilder keyStorePassword(String keyStorePassword) { + this.config.setKeyStorePassword(keyStorePassword); + return this; + } + + public SocketServerConfig build() { + return this.config; + } + + public static SocketServerConfig def() { + return new SSConfigBuilder().build(); + } +} diff --git a/src/main/java/me/darksidecode/easysockets/server/config/SocketServerConfig.java b/src/main/java/me/darksidecode/easysockets/server/config/SocketServerConfig.java new file mode 100644 index 0000000..e0be326 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/server/config/SocketServerConfig.java @@ -0,0 +1,79 @@ +package me.darksidecode.easysockets.server.config; + +public class SocketServerConfig { + private int timeout; + private int maxPacketSize; + private int sendRateLimit; + private int receiveRateLimit; + private boolean useSSL; + private String pathToKeyStore; + private String keyStorePassword; + + public SocketServerConfig( + int timeout, int maxPacketSize, int sendRateLimit, int receiveRateLimit, boolean useSSL, String pathToKeyStore, String keyStorePassword + ) { + this.timeout = timeout; + this.maxPacketSize = maxPacketSize; + this.sendRateLimit = sendRateLimit; + this.receiveRateLimit = receiveRateLimit; + this.useSSL = useSSL; + this.pathToKeyStore = pathToKeyStore; + this.keyStorePassword = keyStorePassword; + } + + public int getTimeout() { + return this.timeout; + } + + public int getMaxPacketSize() { + return this.maxPacketSize; + } + + public int getSendRateLimit() { + return this.sendRateLimit; + } + + public int getReceiveRateLimit() { + return this.receiveRateLimit; + } + + public boolean isUseSSL() { + return this.useSSL; + } + + public String getPathToKeyStore() { + return this.pathToKeyStore; + } + + public String getKeyStorePassword() { + return this.keyStorePassword; + } + + public void setTimeout(int timeout) { + this.timeout = timeout; + } + + public void setMaxPacketSize(int maxPacketSize) { + this.maxPacketSize = maxPacketSize; + } + + public void setSendRateLimit(int sendRateLimit) { + this.sendRateLimit = sendRateLimit; + } + + public void setReceiveRateLimit(int receiveRateLimit) { + this.receiveRateLimit = receiveRateLimit; + } + + public void setUseSSL(boolean useSSL) { + this.useSSL = useSSL; + } + + public void setPathToKeyStore(String pathToKeyStore) { + this.pathToKeyStore = pathToKeyStore; + } + + public void setKeyStorePassword(String keyStorePassword) { + this.keyStorePassword = keyStorePassword; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/util/LimitedList.java b/src/main/java/me/darksidecode/easysockets/util/LimitedList.java new file mode 100644 index 0000000..584829d --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/util/LimitedList.java @@ -0,0 +1,35 @@ +package me.darksidecode.easysockets.util; + +import java.io.Serializable; +import java.util.ArrayList; + +public class LimitedList extends ArrayList implements Serializable { + private static final long serialVersionUID = -3776468374308090201L; + private final int capacity; + + public LimitedList(int capacity) { + if (capacity <= 50000 && capacity >= 2) { + this.capacity = capacity; + } else { + throw new IllegalArgumentException("Invalid capacity: " + capacity); + } + } + + @Override + public boolean add(T t) { + boolean r = super.add(t); + if (this.size() > this.capacity) { + this.remove(0); + } + + return r; + } + + public boolean isFull() { + return this.size() == this.capacity; + } + + public int getCapacity() { + return this.capacity; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/util/Timer.java b/src/main/java/me/darksidecode/easysockets/util/Timer.java new file mode 100644 index 0000000..320232b --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/util/Timer.java @@ -0,0 +1,93 @@ +package me.darksidecode.easysockets.util; + +public class Timer { + private long startTime; + + public Timer(long startTime) { + this.startTime = startTime; + } + + public Timer() { + this(System.currentTimeMillis()); + } + + public Timer add(long millis) { + this.startTime = this.startTime + Math.abs(millis); + return this; + } + + public Timer addTicks(long ticks) { + this.startTime = this.startTime + Math.abs(ticks * 50L); + return this; + } + + public Timer addSeconds(long seconds) { + this.startTime = this.startTime + Math.abs(seconds * 1000L); + return this; + } + + public Timer subtract(long millis) { + this.startTime = this.startTime - Math.abs(millis); + return this; + } + + public Timer subtractTicks(long ticks) { + this.startTime = this.startTime - Math.abs(ticks) * 50L; + return this; + } + + public Timer subtractSeconds(long seconds) { + this.startTime = this.startTime - Math.abs(seconds * 1000L); + return this; + } + + public Timer offset(long millis) { + this.startTime += millis; + return this; + } + + public Timer offsetTicks(long ticks) { + this.startTime += ticks * 50L; + return this; + } + + public Timer offsetSeconds(long seconds) { + this.startTime += seconds * 1000L; + return this; + } + + public boolean hasPassed(long millis) { + return this.getTimePassed() >= millis; + } + + public boolean hasTicked(long ticks) { + return this.getTimeTicked() >= ticks; + } + + public long getTimePassed() { + return System.currentTimeMillis() - this.startTime; + } + + public long getTimeTicked() { + return this.getTimePassed() / 50L; + } + + public long getStartTime() { + return this.startTime; + } + + public Timer setStartTime(long newTime) { + if (newTime < 1L) { + this.reset(); + } else { + this.startTime = newTime; + } + + return this; + } + + public Timer reset() { + this.setStartTime(System.currentTimeMillis()); + return this; + } +} diff --git a/src/main/java/me/darksidecode/easysockets/util/Validate.java b/src/main/java/me/darksidecode/easysockets/util/Validate.java new file mode 100644 index 0000000..553dbc9 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/util/Validate.java @@ -0,0 +1,19 @@ +package me.darksidecode.easysockets.util; + +public class Validate { + public static T notNull(T object, String message) { + if (object == null) { + throw new NullPointerException(message); + } else { + return object; + } + } + + public static char[] notEmpty(char[] array, String message) { + if (notNull(array, message).length == 0) { + throw new ArrayIndexOutOfBoundsException(message); + } else { + return array; + } + } +} diff --git a/src/main/java/me/darksidecode/easysockets/util/crypto/AES128Encryptor.java b/src/main/java/me/darksidecode/easysockets/util/crypto/AES128Encryptor.java new file mode 100644 index 0000000..2f4af89 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/util/crypto/AES128Encryptor.java @@ -0,0 +1,48 @@ +package me.darksidecode.easysockets.util.crypto; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +public class AES128Encryptor implements Encryptor { + private static final String ALGO = "AES/CBC/PKCS5PADDING"; + private final byte[] key; + private final byte[] iv; + + public AES128Encryptor(byte[] key, byte[] iv) { + if (key == null || key.length != 16) { + throw new IllegalArgumentException("Invalid key. Required length: 16"); + } else if (iv != null && iv.length == 16) { + this.key = key; + this.iv = iv; + } else { + throw new IllegalArgumentException("Invalid init vector. Required length: 16"); + } + } + + @Override + public byte[] encrypt(byte[] input) { + try { + IvParameterSpec iv = new IvParameterSpec(this.iv); + SecretKeySpec skc = new SecretKeySpec(this.key, "AES"); + Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + c.init(1, skc, iv); + return c.doFinal(input); + } catch (Exception ex) { + throw new RuntimeException("failed to encrypt " + input.length + " bytes with AES (128)", ex); + } + } + + @Override + public byte[] decrypt(byte[] input) { + try { + IvParameterSpec iv = new IvParameterSpec(this.iv); + SecretKeySpec skeySpec = new SecretKeySpec(this.key, "AES"); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + cipher.init(2, skeySpec, iv); + return cipher.doFinal(input); + } catch (Exception e) { + throw new RuntimeException("failed to decrypt " + input.length + " bytes with AES (128)", e); + } + } +} diff --git a/src/main/java/me/darksidecode/easysockets/util/crypto/AES256Encryptor.java b/src/main/java/me/darksidecode/easysockets/util/crypto/AES256Encryptor.java new file mode 100644 index 0000000..efab4e5 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/util/crypto/AES256Encryptor.java @@ -0,0 +1,105 @@ +package me.darksidecode.easysockets.util.crypto; + +import java.security.AlgorithmParameters; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; + +public class AES256Encryptor implements Encryptor { + public static final int DEFAULT_ITERATIONS = 65536; + private static final String KEYGEN_ALGO = "PBKDF2WithHmacSHA256"; + private static final String CRYPT_ALGO = "AES/CBC/PKCS5PADDING"; + private final char[] key; + private final byte[] salt; + private final int iterations; + + public AES256Encryptor(char[] key, byte[] salt) { + this(key, salt, 65536); + } + + public AES256Encryptor(char[] key, byte[] salt, int iterations) { + if (key != null && key.length != 0) { + if (salt == null || salt.length != 8) { + throw new IllegalArgumentException("Invalid salt. Required length: 8"); + } else if (iterations < 2) { + throw new IllegalArgumentException("Too few iterations. Expected at least 2"); + } else { + this.key = key; + this.salt = salt; + this.iterations = iterations; + } + } else { + throw new IllegalArgumentException("key cannot be null or empty"); + } + } + + private SecretKey getSecret() throws InvalidKeySpecException, NoSuchAlgorithmException { + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); + KeySpec spec = new PBEKeySpec(this.key, this.salt, this.iterations, 256); + SecretKey secret = factory.generateSecret(spec); + return new SecretKeySpec(secret.getEncoded(), "AES"); + } + + @Override + public byte[] encrypt(byte[] input) { + try { + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + cipher.init(1, this.getSecret()); + AlgorithmParameters params = cipher.getParameters(); + byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); + byte[] cipherData = cipher.doFinal(input); + return new AES256Encryptor.CipherObj(cipherData, iv).getBytes(); + } catch (Exception ex) { + throw new RuntimeException("failed to encrypt " + input.length + " bytes with AES (256)", ex); + } + } + + @Override + public byte[] decrypt(byte[] input) { + try { + AES256Encryptor.CipherObj cObj = AES256Encryptor.CipherObj.from(input); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(2, this.getSecret(), new IvParameterSpec(cObj.iv)); + return cipher.doFinal(cObj.cipherData); + } catch (Exception e) { + throw new RuntimeException("failed to decrypt " + input.length + " bytes with AES (256)", e); + } + } + + private static class CipherObj { + private final byte[] cipherData; + private final byte[] iv; + + private CipherObj(byte[] cipherData, byte[] iv) { + if (cipherData == null || cipherData.length == 0 || cipherData.length % 16 != 0) { + throw new RuntimeException("invalid cipherdata"); + } else if (iv != null && iv.length == 16) { + this.cipherData = cipherData; + this.iv = iv; + } else { + throw new RuntimeException("invalid init vector"); + } + } + + private byte[] getBytes() { + byte[] b = new byte[16 + this.cipherData.length]; + System.arraycopy(this.iv, 0, b, 0, 16); + System.arraycopy(this.cipherData, 0, b, 16, this.cipherData.length); + return b; + } + + private static AES256Encryptor.CipherObj from(byte[] b) { + byte[] iv = new byte[16]; + byte[] cipherData = new byte[b.length - 16]; + System.arraycopy(b, 0, iv, 0, 16); + System.arraycopy(b, 16, cipherData, 0, cipherData.length); + return new AES256Encryptor.CipherObj(cipherData, iv); + } + } +} diff --git a/src/main/java/me/darksidecode/easysockets/util/crypto/Encryptor.java b/src/main/java/me/darksidecode/easysockets/util/crypto/Encryptor.java new file mode 100644 index 0000000..7704082 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/util/crypto/Encryptor.java @@ -0,0 +1,7 @@ +package me.darksidecode.easysockets.util.crypto; + +public interface Encryptor { + byte[] encrypt(byte[] input); + + byte[] decrypt(byte[] input); +} diff --git a/src/main/java/me/darksidecode/easysockets/util/io/Compressor.java b/src/main/java/me/darksidecode/easysockets/util/io/Compressor.java new file mode 100644 index 0000000..2f951d5 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/util/io/Compressor.java @@ -0,0 +1,17 @@ +package me.darksidecode.easysockets.util.io; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.zip.Deflater; +import java.util.zip.DeflaterOutputStream; +import java.util.zip.InflaterInputStream; + +public class Compressor { + public static InputStream newInflateInput(InputStream input) { + return new InflaterInputStream(input); + } + + public static OutputStream newDeflateOutput(OutputStream output) { + return new DeflaterOutputStream(output, new Deflater(-1), true); + } +} diff --git a/src/main/java/me/darksidecode/easysockets/util/io/IO.java b/src/main/java/me/darksidecode/easysockets/util/io/IO.java new file mode 100644 index 0000000..f79d478 --- /dev/null +++ b/src/main/java/me/darksidecode/easysockets/util/io/IO.java @@ -0,0 +1,43 @@ +package me.darksidecode.easysockets.util.io; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +public class IO { + public static byte[] ser(Object obj) { + if (obj == null) { + return new byte[0]; + } else { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(obj); + oos.close(); + byte[] bytes = baos.toByteArray(); + baos.close(); + return bytes; + } catch (Exception ex) { + throw new RuntimeException("failed to serialize " + obj.getClass().getName(), ex); + } + } + } + + public static Object deser(byte[] bytes) { + if (bytes != null && bytes.length != 0) { + try { + ByteArrayInputStream bain = new ByteArrayInputStream(bytes); + ObjectInputStream ois = new ObjectInputStream(bain); + Object obj = ois.readObject(); + bain.close(); + ois.close(); + return obj; + } catch (Exception e) { + throw new RuntimeException("failed to deserialize " + bytes.length + " bytes", e); + } + } else { + return null; + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/crypto/AES128Encryptor.java b/src/main/java/me/darksidecode/kantanj/crypto/AES128Encryptor.java new file mode 100644 index 0000000..99c72a2 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/crypto/AES128Encryptor.java @@ -0,0 +1,48 @@ +package me.darksidecode.kantanj.crypto; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +public class AES128Encryptor implements Encryptor { + private static final String ALGO = "AES/CBC/PKCS5PADDING"; + private final byte[] key; + private final byte[] iv; + + public AES128Encryptor(byte[] key, byte[] iv) { + if (key == null || key.length != 16) { + throw new IllegalArgumentException("Invalid key. Required length: 16"); + } else if (iv != null && iv.length == 16) { + this.key = key; + this.iv = iv; + } else { + throw new IllegalArgumentException("Invalid init vector. Required length: 16"); + } + } + + @Override + public byte[] encrypt(byte[] input) { + try { + IvParameterSpec iv = new IvParameterSpec(this.iv); + SecretKeySpec skc = new SecretKeySpec(this.key, "AES"); + Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + c.init(1, skc, iv); + return c.doFinal(input); + } catch (Exception ex) { + throw new RuntimeException("failed to encrypt " + input.length + " bytes with AES (128)", ex); + } + } + + @Override + public byte[] decrypt(byte[] input) { + try { + IvParameterSpec iv = new IvParameterSpec(this.iv); + SecretKeySpec skeySpec = new SecretKeySpec(this.key, "AES"); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + cipher.init(2, skeySpec, iv); + return cipher.doFinal(input); + } catch (Exception e) { + throw new RuntimeException("failed to decrypt " + input.length + " bytes with AES (128)", e); + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/crypto/AES256Encryptor.java b/src/main/java/me/darksidecode/kantanj/crypto/AES256Encryptor.java new file mode 100644 index 0000000..a152bb6 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/crypto/AES256Encryptor.java @@ -0,0 +1,105 @@ +package me.darksidecode.kantanj.crypto; + +import java.security.AlgorithmParameters; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; + +public class AES256Encryptor implements Encryptor { + public static final int DEFAULT_ITERATIONS = 65536; + private static final String KEYGEN_ALGO = "PBKDF2WithHmacSHA256"; + private static final String CRYPT_ALGO = "AES/CBC/PKCS5PADDING"; + private final char[] key; + private final byte[] salt; + private final int iterations; + + public AES256Encryptor(char[] key, byte[] salt) { + this(key, salt, 65536); + } + + public AES256Encryptor(char[] key, byte[] salt, int iterations) { + if (key != null && key.length != 0) { + if (salt == null || salt.length != 8) { + throw new IllegalArgumentException("Invalid salt. Required length: 8"); + } else if (iterations < 2) { + throw new IllegalArgumentException("Too few iterations. Expected at least 2"); + } else { + this.key = (char[])key.clone(); + this.salt = salt; + this.iterations = iterations; + } + } else { + throw new IllegalArgumentException("key cannot be null or empty"); + } + } + + private SecretKey getSecret() throws InvalidKeySpecException, NoSuchAlgorithmException { + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); + KeySpec spec = new PBEKeySpec(this.key, this.salt, this.iterations, 256); + SecretKey secret = factory.generateSecret(spec); + return new SecretKeySpec(secret.getEncoded(), "AES"); + } + + @Override + public byte[] encrypt(byte[] input) { + try { + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + cipher.init(1, this.getSecret()); + AlgorithmParameters params = cipher.getParameters(); + byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); + byte[] cipherData = cipher.doFinal(input); + return new AES256Encryptor.CipherObj(cipherData, iv).getBytes(); + } catch (Exception ex) { + throw new RuntimeException("failed to encrypt " + input.length + " bytes with AES (256)", ex); + } + } + + @Override + public byte[] decrypt(byte[] input) { + try { + AES256Encryptor.CipherObj cObj = AES256Encryptor.CipherObj.from(input); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(2, this.getSecret(), new IvParameterSpec(cObj.iv)); + return cipher.doFinal(cObj.cipherData); + } catch (Exception e) { + throw new RuntimeException("failed to decrypt " + input.length + " bytes with AES (256)", e); + } + } + + private static class CipherObj { + private final byte[] cipherData; + private final byte[] iv; + + private CipherObj(byte[] cipherData, byte[] iv) { + if (cipherData == null || cipherData.length == 0 || cipherData.length % 16 != 0) { + throw new RuntimeException("invalid cipherdata"); + } else if (iv != null && iv.length == 16) { + this.cipherData = cipherData; + this.iv = iv; + } else { + throw new RuntimeException("invalid init vector"); + } + } + + private byte[] getBytes() { + byte[] b = new byte[16 + this.cipherData.length]; + System.arraycopy(this.iv, 0, b, 0, 16); + System.arraycopy(this.cipherData, 0, b, 16, this.cipherData.length); + return b; + } + + private static AES256Encryptor.CipherObj from(byte[] b) { + byte[] iv = new byte[16]; + byte[] cipherData = new byte[b.length - 16]; + System.arraycopy(b, 0, iv, 0, 16); + System.arraycopy(b, 16, cipherData, 0, cipherData.length); + return new AES256Encryptor.CipherObj(cipherData, iv); + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/crypto/Encryptor.java b/src/main/java/me/darksidecode/kantanj/crypto/Encryptor.java new file mode 100644 index 0000000..bd92f28 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/crypto/Encryptor.java @@ -0,0 +1,7 @@ +package me.darksidecode.kantanj.crypto; + +public interface Encryptor { + byte[] encrypt(byte[] input); + + byte[] decrypt(byte[] input); +} diff --git a/src/main/java/me/darksidecode/kantanj/currency/Currency.java b/src/main/java/me/darksidecode/kantanj/currency/Currency.java new file mode 100644 index 0000000..2995e48 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/currency/Currency.java @@ -0,0 +1,59 @@ +package me.darksidecode.kantanj.currency; + +import java.util.Arrays; +import java.util.NoSuchElementException; +import me.darksidecode.kantanj.types.Check; + +public enum Currency { + USD("US Dollar", (short)840), + EUR("Euro", (short)978), + RUB("Russian Ruble", (short)643), + CNY("Yuan Renminbi", (short)156), + GBP("Pound Sterling", (short)826), + JPY("Yen", (short)392), + CHF("Swiss Franc", (short)756), + AUD("Australian Dollar", (short)30), + CAD("Canadian Dollar", (short)124), + SEK("Swedish Krona", (short)752), + NZD("New Zealand Dollar", (short)554); + + private final String name; + private final short number; + + private Currency(String name, short number) { + this.name = name; + this.number = number; + } + + @Override + public String toString() { + return this.name() + '/' + this.number + " (" + this.name + ")"; + } + + public static Currency byHumanReadableName(String name) throws NoSuchElementException { + Check.notNull(name, "currency name cannot be null"); + return Arrays.stream(values()) + .filter(currency -> currency.getName().equalsIgnoreCase(name)) + .findAny() + .orElseThrow(() -> new NoSuchElementException("unsupported currency: name: " + name)); + } + + public static Currency byNumber(short number) throws NoSuchElementException { + if (number >= 0 && number <= 999) { + return Arrays.stream(values()) + .filter(currency -> currency.getNumber() == number) + .findAny() + .orElseThrow(() -> new NoSuchElementException("unsupported currency: number: " + number)); + } else { + throw new IllegalArgumentException("currency number must be between 0 and 999 (inclusive)"); + } + } + + public String getName() { + return this.name; + } + + public short getNumber() { + return this.number; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/currency/CurrencyConverter.java b/src/main/java/me/darksidecode/kantanj/currency/CurrencyConverter.java new file mode 100644 index 0000000..2dce00a --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/currency/CurrencyConverter.java @@ -0,0 +1,5 @@ +package me.darksidecode.kantanj.currency; + +public interface CurrencyConverter { + float convert(float amount, Currency from, Currency to); +} diff --git a/src/main/java/me/darksidecode/kantanj/currency/SimpleCurrencyConverter.java b/src/main/java/me/darksidecode/kantanj/currency/SimpleCurrencyConverter.java new file mode 100644 index 0000000..0327711 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/currency/SimpleCurrencyConverter.java @@ -0,0 +1,59 @@ +package me.darksidecode.kantanj.currency; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import me.darksidecode.kantanj.networking.GetHttpRequest; +import me.darksidecode.kantanj.networking.Networking; +import me.darksidecode.kantanj.types.Check; +import org.apache.http.entity.ContentType; + +public class SimpleCurrencyConverter implements CurrencyConverter { + public static final String FREE_URL = "https://free.currencyconverterapi.com"; + public static final String PREMIUM_URL = "https://api.currencyconverterapi.com"; + public static final String V6 = "v6"; + private final String baseUrl; + private final String apiKey; + private String apiVersion = "v6"; + + public SimpleCurrencyConverter(String apiKey) { + this(false, apiKey); + } + + public SimpleCurrencyConverter(boolean premium, String apiKey) { + this.baseUrl = premium ? "https://api.currencyconverterapi.com" : "https://free.currencyconverterapi.com"; + this.apiKey = Check.notNull(apiKey, "API key cannot be null"); + } + + public SimpleCurrencyConverter apiVersion(String apiVersion) { + this.apiVersion = Check.notNull(apiVersion, "API version cannot be null"); + return this; + } + + @Override + public float convert(float amount, Currency from, Currency to) { + if (amount < 0.0F) { + throw new IllegalArgumentException("amount cannot be negative"); + } else if (amount == 0.0F) { + return 0.0F; + } else { + Check.notNull(from, "source currency cannot be null"); + Check.notNull(to, "target currency cannot be null"); + + try { + String arg = from.name() + '_' + to.name(); + GetHttpRequest getRequest = (GetHttpRequest)new GetHttpRequest() + .baseUrl(this.baseUrl) + .path("api/" + this.apiVersion + "/convert") + .queryParams("q", arg, "compact", "ultra", "apiKey", this.apiKey) + .requestProperty("Content-Type", ContentType.APPLICATION_JSON.toString()) + .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101"); + String response = Networking.Http.get(getRequest); + JsonObject json = new JsonParser().parse(response).getAsJsonObject(); + float conversionRate = json.get(arg).getAsFloat(); + return amount * conversionRate; + } catch (Exception ex) { + throw new RuntimeException("failed to convert " + amount + " " + from.name() + " to " + to.name(), ex); + } + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/db/Database.java b/src/main/java/me/darksidecode/kantanj/db/Database.java new file mode 100644 index 0000000..99b21a2 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/db/Database.java @@ -0,0 +1,44 @@ +package me.darksidecode.kantanj.db; + +import java.io.Serializable; +import java.util.function.Predicate; + +public interface Database { + int prepare(DatabaseConfiguration config) throws DatabaseAuthenticationException; + + DatabaseObject fetch(String key); + + DatabaseObject fetch(Predicate predicate); + + void insert(DatabaseObject object) throws IllegalStateException; + + boolean remove(DatabaseObject object); + + boolean remove(String key); + + boolean remove(Predicate predicate); + + void update(DatabaseObject target, DatabaseObject replacement); + + void update(String key, DatabaseObject replacement); + + void update(Predicate predicate, DatabaseObject replacement); + + boolean contains(DatabaseObject object); + + boolean contains(String key); + + boolean contains(Predicate predicate); + + DatabaseObject[] allObjects(); + + long size(); + + default void drop() throws DropConfirmationException { + throw new DropConfirmationException(this); + } + + void __dropConfirm00__(); + + boolean save(); +} diff --git a/src/main/java/me/darksidecode/kantanj/db/DatabaseAuthenticationException.java b/src/main/java/me/darksidecode/kantanj/db/DatabaseAuthenticationException.java new file mode 100644 index 0000000..8a7e473 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/db/DatabaseAuthenticationException.java @@ -0,0 +1,15 @@ +package me.darksidecode.kantanj.db; + +public class DatabaseAuthenticationException extends Exception { + public DatabaseAuthenticationException(String message) { + super(message); + } + + public DatabaseAuthenticationException(Throwable cause) { + super(cause); + } + + public DatabaseAuthenticationException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/me/darksidecode/kantanj/db/DatabaseConfiguration.java b/src/main/java/me/darksidecode/kantanj/db/DatabaseConfiguration.java new file mode 100644 index 0000000..4989ba1 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/db/DatabaseConfiguration.java @@ -0,0 +1,7 @@ +package me.darksidecode.kantanj.db; + +import me.darksidecode.kantanj.crypto.Encryptor; + +public interface DatabaseConfiguration { + Encryptor getEncryptor(); +} diff --git a/src/main/java/me/darksidecode/kantanj/db/DatabaseObject.java b/src/main/java/me/darksidecode/kantanj/db/DatabaseObject.java new file mode 100644 index 0000000..05c2141 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/db/DatabaseObject.java @@ -0,0 +1,70 @@ +package me.darksidecode.kantanj.db; + +import com.google.gson.internal.LinkedTreeMap; +import java.io.Serializable; +import me.darksidecode.kantanj.formatting.CommonJson; +import me.darksidecode.kantanj.formatting.Formatting; +import me.darksidecode.kantanj.types.Check; +import org.bson.Document; + +public class DatabaseObject implements Serializable, Cloneable { + private static final long serialVersionUID = 6177749799489717775L; + private static final String DB_OBJ_LINE = "\u0000"; + private String uniqueId; + private T value; + + @Override + public String toString() { + String json = Formatting.unixLines(CommonJson.toJson(this)); + if (json.contains("\u0000")) { + throw new UnknownError("json contains invalid null chars"); + } else { + return json.replace("\n", "\u0000"); + } + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = Check.notNull(uniqueId, "uniqueId cannot be null"); + } + + public void setValue(T value) { + this.value = Check.notNull(value, "value cannot be null"); + } + + public DatabaseObject clone() { + return new DatabaseObject(this.uniqueId, this.value); + } + + public static DatabaseObject fromString(String dbJson) { + if (dbJson.contains("\n")) { + throw new IllegalArgumentException("json contains illegal non-db line chars"); + } else { + DatabaseObject obj = CommonJson.fromJson(dbJson.replace("\u0000", "\n"), DatabaseObject.class); + if (obj.getValue() instanceof LinkedTreeMap && GlobalDatabasesOptions.isConvertLinkedTreeMapToBsonDocument()) { + try { + obj.setValue((T)(new Document((LinkedTreeMap)obj.getValue()))); + } catch (ClassCastException ex) { + throw new RuntimeException( + "failed to convert a LinkedTreeMap to a BSON Document (unexpected T generic type); see me.darksidecode.kantanj.db.GlobalDatabasesOptions#convertLinkedTreeMapToBsonDocument", + ex + ); + } + } + + return obj; + } + } + + public DatabaseObject(String uniqueId, T value) { + this.uniqueId = uniqueId; + this.value = value; + } + + public String getUniqueId() { + return this.uniqueId; + } + + public T getValue() { + return this.value; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/db/DropConfirmationException.java b/src/main/java/me/darksidecode/kantanj/db/DropConfirmationException.java new file mode 100644 index 0000000..3b84a09 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/db/DropConfirmationException.java @@ -0,0 +1,16 @@ +package me.darksidecode.kantanj.db; + +import me.darksidecode.kantanj.types.Check; + +public class DropConfirmationException extends Exception { + private final Database database; + + public DropConfirmationException(Database database) { + this.database = Check.notNull(database, "database cannot be null"); + } + + public Database confirmAndDrop() { + this.database.__dropConfirm00__(); + return this.database; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/db/GlobalDatabasesOptions.java b/src/main/java/me/darksidecode/kantanj/db/GlobalDatabasesOptions.java new file mode 100644 index 0000000..789c5bd --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/db/GlobalDatabasesOptions.java @@ -0,0 +1,13 @@ +package me.darksidecode.kantanj.db; + +public class GlobalDatabasesOptions { + private static volatile boolean convertLinkedTreeMapToBsonDocument = true; + + public static boolean isConvertLinkedTreeMapToBsonDocument() { + return convertLinkedTreeMapToBsonDocument; + } + + public static void setConvertLinkedTreeMapToBsonDocument(boolean convertLinkedTreeMapToBsonDocument) { + GlobalDatabasesOptions.convertLinkedTreeMapToBsonDocument = convertLinkedTreeMapToBsonDocument; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/db/file/KantanjFileDatabase.java b/src/main/java/me/darksidecode/kantanj/db/file/KantanjFileDatabase.java new file mode 100644 index 0000000..27e25ab --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/db/file/KantanjFileDatabase.java @@ -0,0 +1,271 @@ +package me.darksidecode.kantanj.db.file; + +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.HashSet; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.function.Predicate; +import javax.crypto.BadPaddingException; +import me.darksidecode.kantanj.db.Database; +import me.darksidecode.kantanj.db.DatabaseAuthenticationException; +import me.darksidecode.kantanj.db.DatabaseConfiguration; +import me.darksidecode.kantanj.db.DatabaseObject; +import me.darksidecode.kantanj.system.FileUtils; +import me.darksidecode.kantanj.types.Check; + +public class KantanjFileDatabase implements Database { + public static final String FILE_HEADER = "![kantanj.sfdb]\n"; + private static final byte[] HEADER_BYTES = "![kantanj.sfdb]\n".getBytes(StandardCharsets.UTF_8); + private final Object lock = new Object(); + private boolean prepared; + private KantanjFileDatabaseConfiguration conf; + private final Set objects = new HashSet<>(); + private int initialHash; + + @Override + public int prepare(DatabaseConfiguration dbConf) throws DatabaseAuthenticationException { + Check.state(this.prepared, "already prepared"); + this.conf = Check.instanceOf(dbConf, KantanjFileDatabaseConfiguration.class, "illegal database configuration"); + if (this.conf.getSourceFile().exists()) { + byte[] db; + try { + db = dbConf.getEncryptor() == null + ? FileUtils.readGZIP(this.conf.getSourceFile()) + : FileUtils.readEncryptedGZIP(this.conf.getSourceFile(), this.conf.getEncryptor()); + } catch (Exception ex) { + if (ex.getCause() instanceof RuntimeException && ex.getCause().getCause() instanceof BadPaddingException) { + throw new DatabaseAuthenticationException("invalid credentials"); + } + + throw ex; + } + + String dbStr = new String(db, StandardCharsets.UTF_8); + if (!dbStr.startsWith("![kantanj.sfdb]\n")) { + throw new IllegalArgumentException("not a kantanj SimpleFileDatabase file"); + } else { + dbStr = dbStr.replace("![kantanj.sfdb]\n", ""); + String[] lines = dbStr.split("\n"); + synchronized (this.lock) { + for (String line : lines) { + line = line.trim(); + if (!line.isEmpty() && !line.startsWith("#")) { + DatabaseObject obj = DatabaseObject.fromString(line); + this.objects.add(obj); + } + } + + this.prepared = true; + this.initialHash = this.objects.hashCode(); + this.addShutdownHookIfEnabled(); + return this.objects.size(); + } + } + } else { + if (this.conf.getEncryptor() == null) { + FileUtils.writeGZIP(this.conf.getSourceFile(), HEADER_BYTES, FileUtils.OverwriteMode.THROW_STATE_EXCEPTION); + } else { + FileUtils.writeEncryptedGZIP(this.conf.getSourceFile(), HEADER_BYTES, this.conf.getEncryptor(), FileUtils.OverwriteMode.THROW_STATE_EXCEPTION); + } + + this.prepared = true; + this.initialHash = 0; + this.addShutdownHookIfEnabled(); + return -1; + } + } + + private void addShutdownHookIfEnabled() { + if (this.conf.isFlushOnExit()) { + Runtime.getRuntime().addShutdownHook(new Thread(this::save, "KantanjFileDatabase Shutdown Hook | " + System.nanoTime())); + } + } + + @Override + public DatabaseObject fetch(String uniqueId) { + Check.notNull(uniqueId, "uniqueId cannot be null"); + return this.fetch(obj -> obj.getUniqueId().equals(uniqueId)); + } + + @Override + public DatabaseObject fetch(Predicate predicate) { + Check.state(!this.prepared, "database must be prepared first"); + synchronized (this.lock) { + return (DatabaseObject)this.objects.stream().filter(Check.notNull(predicate, "predicate cannot be null")).findFirst().orElse(null); + } + } + + @Override + public void insert(DatabaseObject obj) throws IllegalStateException { + Check.state(!this.prepared, "database must be prepared first"); + Check.notNull(obj, "cannot insert null object into database"); + synchronized (this.lock) { + Check.state(this.contains(obj.getUniqueId()), "object with uniqueId " + obj.getUniqueId() + " is already present in the database"); + this.objects.add(obj); + if (this.conf.isFlushInstantly()) { + this.save(); + } + } + } + + @Override + public boolean remove(DatabaseObject obj) { + Check.state(!this.prepared, "database must be prepared first"); + synchronized (this.lock) { + boolean anythingRemoved = this.objects.remove(Check.notNull(obj, "obj cannot be null")); + if (this.conf.isFlushInstantly()) { + this.save(); + } + + return anythingRemoved; + } + } + + @Override + public boolean remove(String uniqueId) { + Check.notNull(uniqueId, "uniqueId cannot be null"); + return this.remove(obj -> obj.getUniqueId().equals(uniqueId)); + } + + @Override + public boolean remove(Predicate predicate) { + synchronized (this.lock) { + DatabaseObject obj = this.fetch(predicate); + if (obj != null) { + this.objects.remove(obj); + } + + if (this.conf.isFlushInstantly()) { + this.save(); + } + + return obj != null; + } + } + + @Override + public void update(DatabaseObject oldObj, DatabaseObject newObj) { + Check.state(!this.prepared, "database must be prepared first"); + Check.notNull(oldObj, "oldObj cannot be null"); + Check.notNull(newObj, "newObj cannot be null"); + synchronized (this.lock) { + if (this.objects.contains(oldObj)) { + this.objects.remove(oldObj); + this.objects.add(newObj); + if (this.conf.isFlushInstantly()) { + this.save(); + } + } else { + throw new NoSuchElementException("no such object in the database"); + } + } + } + + @Override + public void update(String uniqueId, DatabaseObject newObj) { + Check.notNull(uniqueId, "uniqueId cannot be null"); + this.update(obj -> obj.getUniqueId().equals(uniqueId), newObj); + } + + @Override + public void update(Predicate oldObjPredicate, DatabaseObject newObj) { + synchronized (this.lock) { + DatabaseObject oldObj = this.fetch(oldObjPredicate); + if (oldObj != null) { + this.objects.remove(oldObj); + this.objects.add(newObj); + if (this.conf.isFlushInstantly()) { + this.save(); + } + } else { + throw new NoSuchElementException("no such object in the database"); + } + } + } + + @Override + public boolean contains(DatabaseObject obj) { + Check.state(!this.prepared, "database must be prepared first"); + synchronized (this.lock) { + return this.objects.contains(Check.notNull(obj, "obj cannot be null")); + } + } + + @Override + public boolean contains(String uniqueId) { + Check.notNull(uniqueId, "uniqueId cannot be null"); + return this.contains(obj -> obj.getUniqueId().equals(uniqueId)); + } + + @Override + public boolean contains(Predicate predicate) { + Check.state(!this.prepared, "database must be prepared first"); + synchronized (this.lock) { + return this.objects.stream().anyMatch(Check.notNull(predicate, "predicate cannot be null")); + } + } + + @Override + public DatabaseObject[] allObjects() { + Check.state(!this.prepared, "database must be prepared first"); + synchronized (this.lock) { + return this.objects.toArray(new DatabaseObject[0]); + } + } + + @Override + public long size() { + Check.state(!this.prepared, "database must be prepared first"); + synchronized (this.lock) { + return (long)this.objects.size(); + } + } + + @Override + public void __dropConfirm00__() { + Check.state(!this.prepared, "database must be prepared first"); + synchronized (this.lock) { + this.objects.clear(); + if (this.conf.isFlushInstantly()) { + this.save(); + } + } + } + + @Override + public boolean save() { + Check.state(!this.prepared, "database must be prepared first"); + synchronized (this.lock) { + if (this.objects.hashCode() == this.initialHash) { + return false; + } else { + try { + StringBuilder dbStr = new StringBuilder(); + dbStr.append("![kantanj.sfdb]\n"); + + for (DatabaseObject obj : this.objects) { + dbStr.append(obj.toString()).append('\n'); + } + + byte[] dbBytes = dbStr.toString().getBytes(StandardCharsets.UTF_8); + File newFile = new File(this.conf.getSourceFile().getAbsolutePath() + ".tmp" + System.nanoTime() + '~'); + if (this.conf.getEncryptor() == null) { + FileUtils.writeGZIP(newFile, dbBytes, FileUtils.OverwriteMode.THROW_STATE_EXCEPTION); + } else { + FileUtils.writeEncryptedGZIP(newFile, dbBytes, this.conf.getEncryptor(), FileUtils.OverwriteMode.THROW_STATE_EXCEPTION); + } + + Files.move(newFile.toPath(), this.conf.getSourceFile().toPath(), StandardCopyOption.REPLACE_EXISTING); + return true; + } catch (IOException e) { + throw new RuntimeException("failed to save the database to file", e); + } + } + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/db/file/KantanjFileDatabaseConfiguration.java b/src/main/java/me/darksidecode/kantanj/db/file/KantanjFileDatabaseConfiguration.java new file mode 100644 index 0000000..60ebf68 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/db/file/KantanjFileDatabaseConfiguration.java @@ -0,0 +1,92 @@ +package me.darksidecode.kantanj.db.file; + +import java.io.File; +import java.nio.file.Path; +import me.darksidecode.kantanj.crypto.AES256Encryptor; +import me.darksidecode.kantanj.crypto.Encryptor; +import me.darksidecode.kantanj.db.DatabaseConfiguration; +import me.darksidecode.kantanj.types.Check; + +public class KantanjFileDatabaseConfiguration implements DatabaseConfiguration { + private File sourceFile; + private boolean flushInstantly; + private boolean flushOnExit; + private Encryptor encryptor; + + public static KantanjFileDatabaseConfiguration.Builder builder() { + return new KantanjFileDatabaseConfiguration.Builder(); + } + + public File getSourceFile() { + return this.sourceFile; + } + + public boolean isFlushInstantly() { + return this.flushInstantly; + } + + public boolean isFlushOnExit() { + return this.flushOnExit; + } + + @Override + public Encryptor getEncryptor() { + return this.encryptor; + } + + public static final class Builder { + private static final byte[] ENC_SALT = new byte[]{-128, 62, 60, 10, -11, -101, -70, -112}; + private final KantanjFileDatabaseConfiguration conf = new KantanjFileDatabaseConfiguration(); + private int aesIterations = 65536; + + Builder() { + } + + public KantanjFileDatabaseConfiguration build() { + return this.conf; + } + + public KantanjFileDatabaseConfiguration.Builder file(String path) { + return this.file(new File(path)); + } + + public KantanjFileDatabaseConfiguration.Builder file(Path path) { + return this.file(path.toFile()); + } + + public KantanjFileDatabaseConfiguration.Builder file(File sourceFile) { + this.conf.sourceFile = Check.notNull(sourceFile, "sourceFile cannot be null"); + return this; + } + + public KantanjFileDatabaseConfiguration.Builder flushInstantly(boolean flushInstantly) { + this.conf.flushInstantly = flushInstantly; + return this; + } + + public KantanjFileDatabaseConfiguration.Builder flushOnExit(boolean flushOnExit) { + this.conf.flushOnExit = flushOnExit; + return this; + } + + public KantanjFileDatabaseConfiguration.Builder aesIterations(int aesIterations) { + if (aesIterations < 1) { + throw new IllegalArgumentException("must iterate at least once"); + } else { + Check.state(this.conf.encryptor != null, "encryptor already set (aesIterations must be set before password)"); + this.aesIterations = aesIterations; + return this; + } + } + + public KantanjFileDatabaseConfiguration.Builder password(char[] password) { + this.conf.encryptor = new AES256Encryptor(password, ENC_SALT, this.aesIterations); + return this; + } + + public KantanjFileDatabaseConfiguration.Builder encryptor(Encryptor encryptor) { + this.conf.encryptor = encryptor; + return this; + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/db/mongo/Cacheable.java b/src/main/java/me/darksidecode/kantanj/db/mongo/Cacheable.java new file mode 100644 index 0000000..bbe43bc --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/db/mongo/Cacheable.java @@ -0,0 +1,11 @@ +package me.darksidecode.kantanj.db.mongo; + +import org.bson.Document; + +public interface Cacheable { + void fetch(MongoManager manager, Object key); + + Document create(); + + Document push(); +} diff --git a/src/main/java/me/darksidecode/kantanj/db/mongo/MongoManager.java b/src/main/java/me/darksidecode/kantanj/db/mongo/MongoManager.java new file mode 100644 index 0000000..e008ca0 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/db/mongo/MongoManager.java @@ -0,0 +1,195 @@ +package me.darksidecode.kantanj.db.mongo; + +import com.mongodb.MongoClient; +import com.mongodb.MongoCredential; +import com.mongodb.ServerAddress; +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import java.util.Collections; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import me.darksidecode.kantanj.types.Check; +import org.bson.Document; + +public class MongoManager implements AutoCloseable { + private static final int DEFAULT_MONGO_PORT = 27017; + private MongoClient client; + private MongoDatabase selected; + + public MongoManager noLogs() { + Logger.getLogger("com.mongodb").setLevel(Level.OFF); + Logger.getLogger("org.mongodb").setLevel(Level.OFF); + return this; + } + + public MongoManager connectLocal() { + try { + this.client = new MongoClient(); + return this; + } catch (Exception ex) { + throw new RuntimeException("failed to connect to default local database", ex); + } + } + + public MongoManager connectLocal(String username, String database, char[] password) { + try { + return this.connect("localhost", 27017, username, database, password); + } catch (Exception e) { + throw new RuntimeException("failed to connect to default local database", e); + } + } + + public MongoManager connect(String host) { + if (host != null && !host.trim().isEmpty()) { + try { + this.client = new MongoClient(host); + return this; + } catch (Exception err) { + throw new RuntimeException("failed to connect to remote database \"" + host + "\" (default port)", err); + } + } else { + throw new IllegalArgumentException("invalid (null, empty or 'spaces-only') host"); + } + } + + public MongoManager connect(String host, int port) { + if (host == null || host.trim().isEmpty()) { + throw new IllegalArgumentException("invalid (null, empty or 'spaces-only') host"); + } else if (port >= 1 && port <= 65535) { + try { + this.client = new MongoClient(host, port); + return this; + } catch (Exception ignored) { + throw new RuntimeException(String.format("failed to connect to remote database \"%s\" at port %s", host, port)); + } + } else { + throw new IllegalArgumentException("invalid port " + port); + } + } + + public MongoManager connect(String host, int port, String username, String database, char[] password) { + if (host == null || host.trim().isEmpty()) { + throw new IllegalArgumentException("invalid (null, empty or 'spaces-only') host"); + } else if (username == null || username.trim().isEmpty()) { + throw new IllegalArgumentException("invalid (null, empty or 'spaces-only') username"); + } else if (database == null || database.trim().isEmpty()) { + throw new IllegalArgumentException("invalid (null, empty or 'spaces-only') database"); + } else if (password == null || password.length == 0) { + throw new IllegalArgumentException("invalid (null or empty) password"); + } else if (port >= 1 && port <= 65535) { + try { + MongoCredential cred = MongoCredential.createCredential(username, database, password); + + for (int i = 0; i < password.length; i++) { + password[i] = 0; + } + + this.client = new MongoClient(new ServerAddress(host, port), Collections.singletonList(cred)); + return this; + } catch (Exception ex) { + throw new RuntimeException("failed to connect to default local database (with user&pass)", ex); + } + } else { + throw new IllegalArgumentException("invalid port " + port); + } + } + + public MongoManager select(String database) { + this.ensureConnected(); + this.selected = this.client.getDatabase(Check.notNull(database, "database name cannot be null")); + return this; + } + + public MongoDatabase getSelectedDatabase() { + this.ensureSelected(); + return this.selected; + } + + public boolean isDatabaseSelected() { + this.ensureConnected(); + return this.selected != null; + } + + public boolean isConnected() { + return this.client != null; + } + + private void ensureSelected() { + this.ensureConnected(); + if (!this.isDatabaseSelected()) { + throw new IllegalStateException("no database selected"); + } + } + + private void ensureConnected() { + if (!this.isConnected()) { + throw new IllegalStateException("not connected"); + } + } + + @Override + public void close() { + if (this.isConnected()) { + try { + this.client.close(); + } catch (Exception ignored) { + } + } + } + + private T checkStateAndReturn(T object) { + this.ensureSelected(); + return object; + } + + public MongoCollection getCollection(String collection) { + return this.checkStateAndReturn(this.selected.getCollection(Check.notNull(collection, "collection name cannot be null"))); + } + + public FindIterable fetch(String collection, String key, Object val) { + return this.getCollection(collection).find(new Document(Check.notNull(key, "key cannot be null"), val)); + } + + public Document fetchFirst(String collection, String key, Object val) { + return (Document)this.fetch(collection, key, val).first(); + } + + public void insertOne(String collection, Document doc) { + this.getCollection(collection).insertOne(Check.notNull(doc, "doc cannot be null")); + } + + public void insertMany(String collection, List docs) { + if (Check.notNull(docs, "docs list cannot be null").isEmpty()) { + throw new IllegalArgumentException("nothing to insert"); + } else { + MongoCollection col = this.getCollection(collection); + if (docs.size() == 1) { + col.insertOne(docs.get(0)); + } else { + col.insertMany(docs); + } + } + } + + public Document updateOne(String collection, String idKey, Object idVal, Document updatedData) { + Check.notNull(idKey, "target entry ID key cannot be null"); + Check.notNull(updatedData, "updated data cannot be null"); + MongoCollection col = this.getCollection(collection); + Document targetEntry = (Document)col.find(new Document(idKey, idVal)).first(); + Check.notNull(targetEntry, "no entries with \"%s\"=\"%s\" found", idKey, idVal); + col.updateOne(targetEntry, new Document("$set", updatedData)); + return targetEntry; + } + + public long deleteOne(String collection, String idKey, Object idVal) { + Check.notNull(idKey, "target entry ID key cannot be null"); + MongoCollection col = this.getCollection(collection); + return col.deleteOne(new Document(idKey, idVal)).getDeletedCount(); + } + + public long count(String collection) { + return this.getCollection(collection).countDocuments(); + } +} diff --git a/src/main/java/me/darksidecode/kantanj/formatting/CommonJson.java b/src/main/java/me/darksidecode/kantanj/formatting/CommonJson.java new file mode 100644 index 0000000..fdee8e8 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/formatting/CommonJson.java @@ -0,0 +1,33 @@ +package me.darksidecode.kantanj.formatting; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import me.darksidecode.kantanj.types.Check; + +public final class CommonJson { + private static final Gson simpleGsonNoHtmlEsc = new GsonBuilder().disableHtmlEscaping().create(); + private static final Gson prettyGsonNoHtmlEsc = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + + private CommonJson() { + } + + public static T fromJson(String json, Class typeOfT) { + return (T)simpleGsonNoHtmlEsc.fromJson(Check.notNull(json, "json cannot be null"), Check.notNull(typeOfT, "typeOfT cannot be null")); + } + + public static String toJson(Object obj) { + return simpleGsonNoHtmlEsc.toJson(Check.notNull(obj, "obj cannot be null")); + } + + public static String toPrettyJson(Object obj) { + return prettyGsonNoHtmlEsc.toJson(Check.notNull(obj, "obj cannot be null")); + } + + public static Gson getSimpleGsonNoHtmlEsc() { + return simpleGsonNoHtmlEsc; + } + + public static Gson getPrettyGsonNoHtmlEsc() { + return prettyGsonNoHtmlEsc; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/formatting/Condition.java b/src/main/java/me/darksidecode/kantanj/formatting/Condition.java new file mode 100644 index 0000000..4728c32 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/formatting/Condition.java @@ -0,0 +1,254 @@ +package me.darksidecode.kantanj.formatting; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import jdk.nashorn.internal.runtime.regexp.joni.exception.SyntaxException; + +public class Condition { + final List branches = new ArrayList<>(); + Condition.Branch elseBranch; + String pre; + private boolean validated; + private int validatedHash = -1; + + void validate() { + int h = this.hashCode(); + if (!this.validated || h == 0 || h != this.validatedHash) { + this.validated = false; + if (this.pre == null) { + this.pre = ""; + } + + if (this.branches.isEmpty()) { + throw new SyntaxException("missing conditional branches"); + } else if (this.elseBranch == null) { + throw new SyntaxException("missing else branch"); + } else if (this.elseBranch.result == null) { + throw new SyntaxException("missing result at the else branch"); + } else { + for (int i = 0; i < this.branches.size(); i++) { + Condition.Branch branch = this.branches.get(i); + if (branch.obj == -1) { + throw new SyntaxException("missing target obj pointer at branch " + i); + } + + if (branch.op == null) { + throw new SyntaxException("missing comparison operator at branch " + i); + } + + if (branch.against == null) { + throw new SyntaxException("missing against obj at branch " + i); + } + + if (branch.result == null) { + throw new SyntaxException("missing result at branch " + i); + } + } + + this.validated = true; + this.validatedHash = this.hashCode(); + } + } + } + + private void ensureValidated() { + if (!this.validated) { + throw new IllegalStateException("condition is not validated"); + } + } + + public String apply(Object... args) { + if (args != null && args.length != 0) { + this.ensureValidated(); + StringBuilder s = new StringBuilder(this.pre); + String result = null; + + for (Condition.Branch branch : this.branches) { + if (branch.test(args)) { + result = branch.result; + break; + } + } + + if (result == null) { + result = this.elseBranch.result; + } + + s.append(result); + return s.toString(); + } else { + throw new IllegalArgumentException("args must not be empty or null"); + } + } + + @Override + public int hashCode() { + if (this.elseBranch != null && this.pre != null) { + int h = 31 * (1 + this.branches.size()); + h += this.pre.hashCode(); + h += 31 * this.elseBranch.result.hashCode(); + + for (int i = 0; i < this.branches.size(); i++) { + int hBranch = this.branches.get(i).hashCode(); + if (hBranch == 0) { + return 0; + } + + h += 31 * (i + 1) + 31 * hBranch; + } + + return Math.abs(h); + } else { + return 0; + } + } + + @Override + public String toString() { + this.ensureValidated(); + StringBuilder s = new StringBuilder("Condition: { branches: ("); + if (this.branches.isEmpty()) { + s.append("none"); + } else { + for (int i = 0; i < this.branches.size(); i++) { + s.append(this.branches.get(i).toString()); + if (i < this.branches.size() - 1) { + s.append(", "); + } + } + } + + s.append("); elseBranch: ").append(this.elseBranch.toString()); + s.append("; pre: \"").append(this.pre).append("\"}"); + return s.toString(); + } + + static class Branch { + private static final String RANGE_LIMITS_SPLIT = Pattern.quote(".."); + int obj = -1; + String op; + boolean negate; + String against; + String result; + + private boolean test(Object... args) { + if (this.obj >= args.length) { + throw new IllegalArgumentException("too few args: expected value at index " + this.obj); + } else { + Object target = args[this.obj]; + if (target == null) { + throw new NullPointerException("object at index " + this.obj + " must not be null"); + } else { + int idxOfOpening = this.against.indexOf(123); + int idxOfClosing = this.against.indexOf(125); + Object compareTo; + if (idxOfClosing > idxOfOpening) { + String pointerStr = this.against.replace("{", "").replace("}", ""); + + int pointer; + try { + pointer = Integer.parseInt(pointerStr); + } catch (NumberFormatException ignored) { + throw new SyntaxException("invalid pointer: " + this.against); + } + + if (pointer >= args.length) { + throw new IllegalArgumentException("too few args: expected value at index " + pointer); + } + + compareTo = args[pointer]; + if (compareTo == null) { + throw new NullPointerException("object at index " + this.obj + " must not be null"); + } + } else if (this.op.equals("~")) { + compareTo = null; + } else if (this.against.contains(".")) { + try { + compareTo = Double.parseDouble(this.against); + } catch (NumberFormatException ignoredEx) { + compareTo = this.against; + } + } else { + try { + compareTo = Integer.parseInt(this.against); + } catch (NumberFormatException ignoredErr) { + compareTo = this.against; + } + } + + Class targetClass = target.getClass(); + Class againstClass = compareTo == null ? null : compareTo.getClass(); + if (compareTo != null && targetClass != againstClass) { + throw new SyntaxException(String.format("types mismatch: cannot compare %s to %s", targetClass.getSimpleName(), againstClass.getSimpleName())); + } else { + boolean match; + if (this.op.equals("~")) { + if (!(target instanceof Number)) { + throw new SyntaxException("target object must be a number for range checks"); + } + + String[] limits = this.against.split(RANGE_LIMITS_SPLIT); + double low = Double.parseDouble(limits[0]); + double high = Double.parseDouble(limits[1]); + if (low >= high) { + throw new SyntaxException(String.format("low range limit must be less than high range limit; low: %s, high: %s", low, high)); + } + + double tNum = ((Number)target).doubleValue(); + match = tNum >= low && tNum <= high; + } else { + assert compareTo != null; + + if (target instanceof Number) { + double nTarget = ((Number)target).doubleValue(); + double nAgainst = ((Number)compareTo).doubleValue(); + match = this.compareNumbers(nTarget, nAgainst); + } else { + if (!this.op.equals("=")) { + throw new SyntaxException("operator " + this.op + " is not applicable for objects of type String"); + } + + match = target.equals(compareTo); + } + } + + return this.negate != match; + } + } + } + } + + private boolean compareNumbers(double nTarget, double nAgainst) { + switch (this.op) { + case "=": + return nTarget == nAgainst; + case "<": + return nTarget < nAgainst; + case "<=": + return nTarget <= nAgainst; + case ">": + return nTarget > nAgainst; + case ">=": + return nTarget >= nAgainst; + default: + throw new SyntaxException("operator " + this.op + " is not applicable for objects of type Number"); + } + } + + @Override + public int hashCode() { + if (this.obj != -1 && this.op != null && this.against != null && this.result != null) { + int h = 31 * this.obj + (this.negate ? 33 : 31) * this.op.hashCode() + this.against.hashCode() + this.result.hashCode(); + return Math.abs(h); + } else { + return 0; + } + } + + @Override + public String toString() { + return String.format("Branch[obj: %s, op: %s, negate: %s, against: %s, result: \"%s\"]", this.obj, this.op, this.negate, this.against, this.result); + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/formatting/ConditionalFormatter.java b/src/main/java/me/darksidecode/kantanj/formatting/ConditionalFormatter.java new file mode 100644 index 0000000..d2569ef --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/formatting/ConditionalFormatter.java @@ -0,0 +1,277 @@ +package me.darksidecode.kantanj.formatting; + +import java.util.ArrayList; +import java.util.List; +import jdk.nashorn.internal.runtime.regexp.joni.exception.SyntaxException; + +public class ConditionalFormatter { + private static final String OPS = "~<=>"; + private static final int EXPECTING_OBJ = 0; + private static final int EXPECTING_CONDITION = 1; + private static final int EXPECTING_RESULT = 2; + private static final int EXPECT_RANGE_START = 0; + private static final int EXPECT_ONE_DOT = 1; + private static final int EXPECT_RANGE_END = 2; + private final List conditions = new ArrayList<>(); + private String plainTail = ""; + private boolean openingQuote; + private int lastQuotePos; + private int state = 0; + private int rangeSpecState = 0; + private StringBuilder curNum = new StringBuilder(); + private StringBuilder op = new StringBuilder(); + private StringBuilder against = new StringBuilder(); + private StringBuilder result = new StringBuilder(); + private Condition.Branch curBranch = new Condition.Branch(); + private Condition curCond; + private boolean appendCurNum; + private boolean elseBranch; + private boolean rangeSpec; + + public ConditionalFormatter(String s) { + if (s != null && !s.trim().isEmpty()) { + char[] chars = s.toCharArray(); + StringBuilder pre = new StringBuilder(); + + for (int i = 0; i < chars.length; i++) { + char c = chars[i]; + if (c == '\'') { + this.openingQuote = !this.openingQuote; + this.lastQuotePos = i; + if (this.openingQuote) { + if (i == chars.length - 1) { + throw new SyntaxException("unclosed quote at char " + (i + 1)); + } + + i = this.parseCondition(chars, i, pre.toString()); + pre = new StringBuilder(); + } + } else { + pre.append(c); + } + } + + if (this.openingQuote) { + throw new SyntaxException("unclosed quote at char " + (this.lastQuotePos + 1)); + } else { + if (pre.length() > 0) { + this.plainTail = pre.toString(); + } + + this.conditions.forEach(Condition::validate); + } + } else { + throw new IllegalArgumentException("input string cannot be empty"); + } + } + + private int parseCondition(char[] chars, int start, String pre) { + char[] innerChars = this.getInner(chars, start); + this.curCond = new Condition(); + this.curCond.pre = pre; + + for (int pos = 0; pos < innerChars.length; pos++) { + char ic = innerChars[pos]; + boolean skipSpace = ic == ' ' && this.state != 2; + boolean skipColon = ic == ':' && this.elseBranch; + if (!skipSpace && !skipColon) { + switch (this.state) { + case 0: + this.parseExpectingObj(ic, start, pos); + break; + case 1: + this.parseExpectingCondition(ic, start, pos); + break; + case 2: + int skip = this.parseExpectingResult(ic, start, pos); + if (skip != -1) { + return skip; + } + break; + default: + throw new IllegalStateException(Integer.toString(this.state)); + } + } + } + + throw new SyntaxException("unterminated condition at char " + (start + 1)); + } + + private void parseExpectingObj(char ic, int start, int pos) { + if (ic == '*') { + this.elseBranch = true; + this.state = 2; + } else if (ic == '{') { + this.appendCurNum = true; + } else if (this.appendCurNum) { + if (ic == '}') { + if (this.curNum.length() == 0) { + throw new SyntaxException("empty pointer at char " + (start + 1 + pos + 1)); + } + + this.curBranch.obj = Integer.parseInt(this.curNum.toString()); + this.curNum = new StringBuilder(); + this.appendCurNum = false; + this.state = 1; + } else { + if (!Character.isDigit(ic)) { + throw new SyntaxException("invalid non-int pointer at char " + (start + 1 + pos + 1)); + } + + this.curNum.append(ic); + } + } + } + + private void parseExpectingCondition(char ic, int start, int pos) { + boolean operatorChar = "~<=>".indexOf(ic) != -1; + if (!this.rangeSpec) { + this.rangeSpec = this.op.length() == 1 && this.op.charAt(0) == '~'; + } + + if (ic == '!') { + this.curBranch.negate = true; + } else if (!operatorChar && !this.rangeSpec) { + if (this.curBranch.op == null) { + if (this.op.length() == 0) { + throw new SyntaxException("empty comparison operator at char " + (start + 1 + pos + 1)); + } + + this.curBranch.op = this.op.toString(); + this.op = new StringBuilder(); + } + + if (ic == ':') { + if (this.against.length() == 0) { + throw new SyntaxException("nothing to compare to at char " + (start + 1 + pos + 1)); + } + + this.curBranch.against = this.against.toString(); + this.against = new StringBuilder(); + this.state = 2; + } else { + this.against.append(ic); + } + } else { + boolean prevCharDigit = this.op.length() > 1 && Character.isDigit(this.op.charAt(this.op.length() - 1)); + this.op.append(ic); + if (this.rangeSpec) { + boolean validChar = ic == '.' || ic == ':' || Character.isDigit(ic); + if (!validChar) { + throw new SyntaxException(String.format("illegal symbol %s in range spec at char %s", ic, start + 1 + pos + 1)); + } + + if (this.rangeSpecState == 0 && ic == '.') { + if (!prevCharDigit) { + throw new SyntaxException("expected range start number at char " + (start + 1 + pos + 1)); + } + + this.rangeSpecState = 1; + } else if (this.rangeSpecState == 1) { + if (ic != '.') { + throw new SyntaxException("expected range start/end separator \"..\" at char " + (start + 1 + pos + 1)); + } + + this.rangeSpecState = 2; + } else if (this.rangeSpecState == 2) { + if (ic == '.') { + throw new SyntaxException("expected colon \":\" at the end of range spec at char " + (start + 1 + pos + 1)); + } + + if (ic == ':') { + if (!prevCharDigit) { + throw new SyntaxException("expected range end number at char " + (start + 1 + pos + 1)); + } + + this.curBranch.op = "~"; + this.curBranch.against = this.op.substring(1, this.op.length() - 1); + this.rangeSpecState = 0; + this.rangeSpec = false; + this.op = new StringBuilder(); + this.against = new StringBuilder(); + this.state = 2; + } + } + } + } + } + + private int parseExpectingResult(char ic, int start, int pos) { + if (ic == '|') { + if (this.elseBranch) { + throw new SyntaxException("else branch must be the last branch of a condition: unexpected OR operator at char " + (start + 1 + pos + 1)); + } + + String r = this.result.toString().trim(); + if (r.isEmpty()) { + throw new SyntaxException("expected result at char " + (start + 1 + pos + 1)); + } + + this.curBranch.result = r; + this.curCond.branches.add(this.curBranch); + this.result = new StringBuilder(); + this.curBranch = new Condition.Branch(); + this.state = 0; + } else { + if (ic == '\'') { + if (!this.elseBranch) { + throw new SyntaxException("illegal condition end: missing else branch at char " + (start + 1 + pos + 1)); + } + + String r = this.result.toString().trim(); + if (r.isEmpty()) { + throw new SyntaxException("expected result at char " + (start + 1 + pos + 1)); + } + + this.openingQuote = !this.openingQuote; + this.lastQuotePos = start; + this.curBranch.result = r; + this.curCond.elseBranch = this.curBranch; + this.conditions.add(this.curCond); + return start + pos + 1; + } + + this.result.append(ic); + } + + return -1; + } + + private char[] getInner(char[] chars, int start) { + StringBuilder inner = new StringBuilder(); + + for (int j = start + 1; j < chars.length; j++) { + char next = chars[j]; + inner.append(next); + if (next == '\'') { + if (j == start + 1) { + throw new SyntaxException("empty condition at char " + (start + 1)); + } + break; + } + } + + return inner.toString().toCharArray(); + } + + public String format(Object... args) { + if (args == null) { + throw new NullPointerException("args cannot be null"); + } else { + StringBuilder formatted = new StringBuilder(); + this.conditions.forEach(cond -> formatted.append(cond.apply(args))); + String f = formatted.toString() + this.plainTail; + + for (int i = 0; i < args.length; i++) { + Object o = args[i]; + if (o == null) { + throw new NullPointerException("object at index " + i + " must not be null"); + } + + f = f.replace("{" + i + "}", o.toString()); + } + + return f; + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/formatting/Formatting.java b/src/main/java/me/darksidecode/kantanj/formatting/Formatting.java new file mode 100644 index 0000000..181b47e --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/formatting/Formatting.java @@ -0,0 +1,22 @@ +package me.darksidecode.kantanj.formatting; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import me.darksidecode.kantanj.types.Check; + +public final class Formatting { + private Formatting() { + } + + public static String urlEncodeUtf8(String s) { + try { + return URLEncoder.encode(Check.notNull(s, "cannot encode null string"), "UTF-8"); + } catch (UnsupportedEncodingException ignored) { + throw new RuntimeException("error in utf8 url encoding for string: " + s); + } + } + + public static String unixLines(String s) { + return s.replace("\r\n", "\n").replace("\r", "\n"); + } +} diff --git a/src/main/java/me/darksidecode/kantanj/formatting/Hash.java b/src/main/java/me/darksidecode/kantanj/formatting/Hash.java new file mode 100644 index 0000000..2313569 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/formatting/Hash.java @@ -0,0 +1,67 @@ +package me.darksidecode.kantanj.formatting; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.security.MessageDigest; +import javax.xml.bind.DatatypeConverter; + +public enum Hash { + MD5("MD5"), + SHA1("SHA1"), + SHA256("SHA-256"), + SHA512("SHA-512"); + + private String name; + + private Hash(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public byte[] checksum(File input) { + try (InputStream in = new FileInputStream(input)) { + MessageDigest digest = MessageDigest.getInstance(this.name); + byte[] block = new byte[4096]; + + int length; + while ((length = in.read(block)) > 0) { + digest.update(block, 0, length); + } + + return digest.digest(); + } catch (Exception ex) { + throw new RuntimeException("failed to get checksum of " + input.getAbsolutePath(), ex); + } + } + + public String checksumString(File input) { + return DatatypeConverter.printHexBinary(this.checksum(input)); + } + + public byte[] checksum(byte[] input) { + try { + MessageDigest digest = MessageDigest.getInstance(this.name); + digest.update(input); + return digest.digest(); + } catch (Exception e) { + throw new RuntimeException("failed to get checksum of " + input.length + " bytes", e); + } + } + + public String checksumString(byte[] input) { + return DatatypeConverter.printHexBinary(this.checksum(input)); + } + + public byte[] checksum(String input, Charset encoding) { + return this.checksum(input.getBytes(encoding)); + } + + public String checksumString(String input, Charset encoding) { + return DatatypeConverter.printHexBinary(this.checksum(input, encoding)); + } +} diff --git a/src/main/java/me/darksidecode/kantanj/ipapi/IPAPI.java b/src/main/java/me/darksidecode/kantanj/ipapi/IPAPI.java new file mode 100644 index 0000000..a909093 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/ipapi/IPAPI.java @@ -0,0 +1,127 @@ +package me.darksidecode.kantanj.ipapi; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import java.net.InetAddress; +import java.util.concurrent.TimeUnit; +import me.darksidecode.kantanj.formatting.CommonJson; +import me.darksidecode.kantanj.networking.GetHttpRequest; +import me.darksidecode.kantanj.networking.Networking; +import me.darksidecode.kantanj.system.Threads; +import me.darksidecode.kantanj.time.ExpiringList; +import me.darksidecode.kantanj.types.Check; +import org.apache.http.entity.ContentType; + +public class IPAPI { + public static final String BASE_URL = "http://ip-api.com"; + private static final int MAX_REQUESTS_PER_MIN = 145; + private static final long MIN_BLOCK_MILLIS = 1000L; + private static boolean enableCaching = true; + private static boolean blockOnLimitExcess = true; + private static long threadBlockMillis = TimeUnit.SECONDS.toMillis(30L); + private static final ExpiringList requestCounter = new ExpiringList(1L, TimeUnit.MINUTES); + private static final Cache cache = CacheBuilder.newBuilder().expireAfterWrite(1L, TimeUnit.DAYS).build(); + private static final Object cacheLock = new Object(); + private static final Object requestLock = new Object(); + + public static void setThreadBlockTime(long blockTime, TimeUnit timeUnit) { + if (blockTime < 1L) { + throw new IllegalArgumentException("blockTime cannot be negative or zero"); + } else { + long millis = Check.notNull(timeUnit, "timeUnit cannot be null").toMillis(blockTime); + if (millis < 1000L) { + throw new IllegalArgumentException("cannot block for less than 1 second"); + } else { + threadBlockMillis = millis; + } + } + } + + public static IPAddress info(InetAddress address) { + return info(address.getHostAddress()); + } + + public static IPAddress info(InetAddress address, IPAPILanguage lang) { + return info(address.getHostAddress(), lang); + } + + public static IPAddress info(String ip) { + return info(ip, IPAPILanguage.ENGLISH); + } + + public static IPAddress info(String ip, IPAPILanguage lang) { + if (enableCaching) { + IPAPI.IPAPIRequest ipapiRequest = new IPAPI.IPAPIRequest(ip, lang); + int hash = ipapiRequest.hashCode(); + synchronized (cacheLock) { + IPAddress cached = (IPAddress)cache.getIfPresent(hash); + if (cached != null) { + return cached; + } else { + IPAddress ipAddr = info0(ip, lang); + cache.put(hash, ipAddr); + return ipAddr; + } + } + } else { + return info0(ip, lang); + } + } + + private static IPAddress info0(String ip, IPAPILanguage lang) { + synchronized (requestLock) { + int requestsLastMin = requestCounter.updateAndCount(); + if (requestsLastMin > 145 && blockOnLimitExcess) { + Threads.sleepQuietly(threadBlockMillis); + } + + GetHttpRequest request = (GetHttpRequest)new GetHttpRequest() + .baseUrl("http://ip-api.com") + .path("json/" + ip) + .queryParam("lang", lang.getIso639Name()) + .requestProperty("Content-Type", ContentType.APPLICATION_JSON.toString()) + .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101"); + String response = Networking.Http.get(request); + return CommonJson.fromJson(response, IPAddress.class); + } + } + + public static boolean isEnableCaching() { + return enableCaching; + } + + public static void setEnableCaching(boolean enableCaching) { + IPAPI.enableCaching = enableCaching; + } + + public static boolean isBlockOnLimitExcess() { + return blockOnLimitExcess; + } + + public static void setBlockOnLimitExcess(boolean blockOnLimitExcess) { + IPAPI.blockOnLimitExcess = blockOnLimitExcess; + } + + private static class IPAPIRequest { + private final String ip; + private final IPAPILanguage lang; + + @Override + public int hashCode() { + return this.ip.hashCode() + this.lang.name().hashCode(); + } + + public String getIp() { + return this.ip; + } + + public IPAPILanguage getLang() { + return this.lang; + } + + public IPAPIRequest(String ip, IPAPILanguage lang) { + this.ip = ip; + this.lang = lang; + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/ipapi/IPAPILanguage.java b/src/main/java/me/darksidecode/kantanj/ipapi/IPAPILanguage.java new file mode 100644 index 0000000..048a152 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/ipapi/IPAPILanguage.java @@ -0,0 +1,28 @@ +package me.darksidecode.kantanj.ipapi; + +public enum IPAPILanguage { + ENGLISH("en", "English (default)"), + GERMAN("de", "Deutsch (German)"), + SPANISH("es", "Español (Spanish)"), + PORTUGUESE("pt-BR", "Español - Argentina (Spanish)"), + FRENCH("fr", "Français (French)"), + JAPANESE("ja", "日本語 (Japanese)"), + CHINESE("zh-CN", "中国 (Chinese)"), + RUSSIAN("ru", "Русский (Russian)"); + + private final String iso639Name; + private final String description; + + private IPAPILanguage(String iso639Name, String description) { + this.iso639Name = iso639Name; + this.description = description; + } + + public String getIso639Name() { + return this.iso639Name; + } + + public String getDescription() { + return this.description; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/ipapi/IPAddress.java b/src/main/java/me/darksidecode/kantanj/ipapi/IPAddress.java new file mode 100644 index 0000000..eca8e36 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/ipapi/IPAddress.java @@ -0,0 +1,113 @@ +package me.darksidecode.kantanj.ipapi; + +import com.google.gson.Gson; +import java.io.Serializable; +import me.darksidecode.kantanj.formatting.CommonJson; + +public class IPAddress implements Serializable { + private static final long serialVersionUID = 1423606597409892108L; + private String status; + private String message; + private String country; + private String countryCode; + private String region; + private String regionName; + private String city; + private String district; + private String zip; + private float lat; + private float lon; + private String timezone; + private String isp; + private String org; + private String as; + private String reverse; + private boolean cellular; + private boolean proxy; + private String query; + + @Override + public String toString() { + return this.toString(CommonJson.getPrettyGsonNoHtmlEsc()); + } + + public String toString(Gson gson) { + return gson.toJson(this); + } + + public String getStatus() { + return this.status; + } + + public String getMessage() { + return this.message; + } + + public String getCountry() { + return this.country; + } + + public String getCountryCode() { + return this.countryCode; + } + + public String getRegion() { + return this.region; + } + + public String getRegionName() { + return this.regionName; + } + + public String getCity() { + return this.city; + } + + public String getDistrict() { + return this.district; + } + + public String getZip() { + return this.zip; + } + + public float getLat() { + return this.lat; + } + + public float getLon() { + return this.lon; + } + + public String getTimezone() { + return this.timezone; + } + + public String getIsp() { + return this.isp; + } + + public String getOrg() { + return this.org; + } + + public String getAs() { + return this.as; + } + + public String getReverse() { + return this.reverse; + } + + public boolean isCellular() { + return this.cellular; + } + + public boolean isProxy() { + return this.proxy; + } + + public String getQuery() { + return this.query; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/logging/BasicLogger.java b/src/main/java/me/darksidecode/kantanj/logging/BasicLogger.java new file mode 100644 index 0000000..c2f5688 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/logging/BasicLogger.java @@ -0,0 +1,36 @@ +package me.darksidecode.kantanj.logging; + +import java.io.PrintStream; + +public interface BasicLogger { + default boolean isEnableDebug() { + return false; + } + + default void setEnableDebug() { + throw new UnsupportedOperationException("setEnableDebug is not implemented in " + this.getClass().getName()); + } + + default void debug(String message, Object... format) { + if (this.isEnableDebug()) { + this.print(System.out, message, format); + } + } + + default void info(String message, Object... format) { + this.print(System.out, message, format); + } + + default void warning(String message, Object... format) { + this.print(System.err, message, format); + } + + default void error(String message, Object... format) { + this.print(System.err, message, format); + } + + default void print(PrintStream printStream, String message, Object... format) { + message = format != null && format.length > 0 ? String.format(message, format) : message; + printStream.println(message); + } +} diff --git a/src/main/java/me/darksidecode/kantanj/networking/GetHttpRequest.java b/src/main/java/me/darksidecode/kantanj/networking/GetHttpRequest.java new file mode 100644 index 0000000..8e2ce50 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/networking/GetHttpRequest.java @@ -0,0 +1,37 @@ +package me.darksidecode.kantanj.networking; + +public class GetHttpRequest extends SimpleHttpRequest { + public GetHttpRequest done() { + return this; + } + + @Override + public SimpleHttpRequest requestMethod(RequestMethod requestMethod) { + throw new IllegalStateException("cannot change request method for " + this.getClass().getName()); + } + + @Override + public RequestMethod getRequestMethod() { + return RequestMethod.GET; + } + + @Override + public SimpleHttpRequest doInput(boolean doInput) { + throw new IllegalStateException("cannot change doInput for " + this.getClass().getName()); + } + + @Override + public boolean shouldDoInput() { + return true; + } + + @Override + public SimpleHttpRequest doOutput(boolean doOutput) { + throw new IllegalStateException("cannot change doOutput for " + this.getClass().getName()); + } + + @Override + public boolean shouldDoOutput() { + return false; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/networking/HttpRequest.java b/src/main/java/me/darksidecode/kantanj/networking/HttpRequest.java new file mode 100644 index 0000000..d3ec4a8 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/networking/HttpRequest.java @@ -0,0 +1,25 @@ +package me.darksidecode.kantanj.networking; + +import java.util.Map; + +public interface HttpRequest { + String getUserAgent() throws IllegalStateException; + + RequestMethod getRequestMethod() throws IllegalStateException; + + boolean isSecured() throws IllegalStateException; + + Map getRequestProperties(); + + int getConnectTimeout(); + + int getReadTimeout(); + + boolean shouldFollowRedirects(); + + boolean shouldDoInput(); + + boolean shouldDoOutput(); + + String getURL() throws IllegalStateException; +} diff --git a/src/main/java/me/darksidecode/kantanj/networking/Networking.java b/src/main/java/me/darksidecode/kantanj/networking/Networking.java new file mode 100644 index 0000000..8e4c5d9 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/networking/Networking.java @@ -0,0 +1,122 @@ +package me.darksidecode.kantanj.networking; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.URL; +import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import me.darksidecode.kantanj.types.Check; +import org.apache.commons.io.IOUtils; +import org.apache.http.entity.ContentType; + +public final class Networking { + private Networking() { + } + + public static void removeJavaUserAgentSuffixGlobally() { + System.setProperty("http.agent", ""); + } + + public static String resolveIPv4(String host) { + try { + Check.notNull(host, "host cannot be null"); + + for (InetAddress inetAddress : InetAddress.getAllByName(host)) { + if (inetAddress instanceof Inet4Address) { + return inetAddress.getHostAddress(); + } + } + + throw new UnknownHostException("unknown host " + host); + } catch (Exception ex) { + throw new RuntimeException("failed to resolve IPv4 of " + host, ex); + } + } + + public static final class Http { + private Http() { + } + + public static String post(PostHttpRequest request) { + try { + HttpURLConnection con = openConnection(request); + StringBuilder response = new StringBuilder(); + OutputStream outputStream = con.getOutputStream(); + outputStream.write(request.getPostData()); + outputStream.close(); + if (request.shouldDoInput()) { + return readResponseAndDisconnect(con, response); + } else { + con.disconnect(); + return null; + } + } catch (Exception e) { + throw new RuntimeException("http POST request failed", e); + } + } + + public static String get(GetHttpRequest request) { + try { + HttpURLConnection con = openConnection(request); + StringBuilder response = new StringBuilder(); + return readResponseAndDisconnect(con, response); + } catch (Exception err) { + throw new RuntimeException("http GET request failed", err); + } + } + + public static HttpURLConnection openConnection(HttpRequest request) { + Check.notNull(request, "request cannot be null"); + + try { + URL url = new URL(request.getURL()); + HttpURLConnection con = (HttpURLConnection)url.openConnection(); + con.setRequestMethod(request.getRequestMethod().name()); + Map requestProps = request.getRequestProperties(); + + for (String prop : requestProps.keySet()) { + con.setRequestProperty(prop, requestProps.get(prop)); + } + + if (request instanceof PostHttpRequest) { + if (!requestProps.containsKey("Content-Type")) { + con.setRequestProperty("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString()); + } + + con.setRequestProperty("Content-Length", String.valueOf(((PostHttpRequest)request).getPostData().length)); + } + + con.setRequestProperty("User-Agent", request.getUserAgent()); + con.setInstanceFollowRedirects(request.shouldFollowRedirects()); + con.setConnectTimeout(request.getConnectTimeout()); + con.setReadTimeout(request.getReadTimeout()); + con.setDoInput(request.shouldDoInput()); + con.setDoOutput(request.shouldDoOutput()); + return con; + } catch (Exception cause) { + throw new RuntimeException("failed to establish a new connection", cause); + } + } + + private static String readResponseAndDisconnect(HttpURLConnection con, StringBuilder response) throws IOException { + InputStream inputStream = con.getInputStream(); + + for (String line : IOUtils.readLines(inputStream, StandardCharsets.UTF_8)) { + response.append(line).append('\n'); + } + + inputStream.close(); + con.disconnect(); + if (response.length() > 0 && response.charAt(response.length() - 1) == '\n') { + response.deleteCharAt(response.length() - 1); + } + + return response.toString(); + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/networking/PostHttpRequest.java b/src/main/java/me/darksidecode/kantanj/networking/PostHttpRequest.java new file mode 100644 index 0000000..e9b9c4d --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/networking/PostHttpRequest.java @@ -0,0 +1,58 @@ +package me.darksidecode.kantanj.networking; + +import java.io.Serializable; +import java.nio.charset.StandardCharsets; +import me.darksidecode.kantanj.formatting.CommonJson; +import me.darksidecode.kantanj.types.Check; +import org.apache.http.entity.ContentType; + +public class PostHttpRequest extends SimpleHttpRequest { + private byte[] postData; + + public PostHttpRequest done() { + return this; + } + + @Override + public SimpleHttpRequest requestMethod(RequestMethod requestMethod) { + throw new IllegalStateException("cannot change request method for " + this.getClass().getName()); + } + + @Override + public RequestMethod getRequestMethod() { + return RequestMethod.POST; + } + + @Override + public SimpleHttpRequest doOutput(boolean doOutput) { + throw new IllegalStateException("cannot change doOutput for " + this.getClass().getName()); + } + + @Override + public boolean shouldDoOutput() { + return true; + } + + public PostHttpRequest postData(byte[] postData) { + this.postData = Check.notNull(postData, "post data cannot be null"); + return this; + } + + public PostHttpRequest postUtf8Data(String postDataUtf8) { + this.postData = Check.notNull(postDataUtf8, "post data cannot be null").getBytes(StandardCharsets.UTF_8); + return this; + } + + public PostHttpRequest postJsonData(T object) { + this.requestProperty("Content-Type", ContentType.APPLICATION_JSON.toString()); + return this.postUtf8Data(CommonJson.toJson(object)); + } + + public byte[] getPostData() { + if (this.postData == null) { + throw new IllegalArgumentException("post data is not set"); + } else { + return this.postData; + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/networking/RequestMethod.java b/src/main/java/me/darksidecode/kantanj/networking/RequestMethod.java new file mode 100644 index 0000000..adedef2 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/networking/RequestMethod.java @@ -0,0 +1,12 @@ +package me.darksidecode.kantanj.networking; + +public enum RequestMethod { + GET, + HEAD, + POST, + PUT, + DELETE, + CONNECT, + OPTIONS, + TRACE; +} diff --git a/src/main/java/me/darksidecode/kantanj/networking/SampleUserAgents.java b/src/main/java/me/darksidecode/kantanj/networking/SampleUserAgents.java new file mode 100644 index 0000000..857fec4 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/networking/SampleUserAgents.java @@ -0,0 +1,8 @@ +package me.darksidecode.kantanj.networking; + +public final class SampleUserAgents { + public static final String MOZILLA_WIN_NT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101"; + + private SampleUserAgents() { + } +} diff --git a/src/main/java/me/darksidecode/kantanj/networking/SimpleHttpRequest.java b/src/main/java/me/darksidecode/kantanj/networking/SimpleHttpRequest.java new file mode 100644 index 0000000..3f5caac --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/networking/SimpleHttpRequest.java @@ -0,0 +1,236 @@ +package me.darksidecode.kantanj.networking; + +import java.util.HashMap; +import java.util.Map; +import me.darksidecode.kantanj.formatting.Formatting; +import me.darksidecode.kantanj.types.Check; + +public class SimpleHttpRequest implements HttpRequest { + public static final int DEFAULT_CONNECT_TIMEOUT = 5000; + public static final int DEFAULT_READ_TIMEOUT = 5000; + private String userAgent; + private RequestMethod requestMethod; + private String baseUrl; + private String path; + private final Map queryParams = new HashMap<>(); + private final Map requestProperties = new HashMap<>(); + private int connectTimeout = 5000; + private int readTimeout = 5000; + private boolean followRedirects; + private boolean doInput = true; + private boolean doOutput; + + public SimpleHttpRequest done() { + return this; + } + + public SimpleHttpRequest userAgent(String userAgent) { + return this.userAgent(userAgent, false); + } + + public SimpleHttpRequest userAgent(String userAgent, boolean removeJavaSuffix) { + this.userAgent = Check.notNull(userAgent, "userAgent cannot be null"); + if (removeJavaSuffix) { + Networking.removeJavaUserAgentSuffixGlobally(); + } + + return this; + } + + public SimpleHttpRequest requestMethod(RequestMethod requestMethod) { + Check.state(this.requestMethod != null, "requestMethod already set"); + this.requestMethod = Check.notNull(requestMethod, "requestMethod cannot be null"); + return this; + } + + public SimpleHttpRequest baseUrl(String baseUrl) { + Check.state(this.baseUrl != null, "baseUrl already set"); + Check.notNull(baseUrl, "baseUrl cannot be null"); + if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) { + throw new IllegalArgumentException("non-http protocol in baseUrl: " + baseUrl); + } else { + this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; + return this; + } + } + + public SimpleHttpRequest path(String path) { + Check.state(this.path != null, "path already set"); + Check.notNull(path, "path cannot be null"); + if (path.isEmpty()) { + throw new IllegalArgumentException("path cannot be empty"); + } else { + if (path.charAt(0) == '/') { + if (path.length() == 1) { + throw new IllegalArgumentException("path cannot consist of a single slash"); + } + + path = path.substring(1); + } + + this.path = path; + return this; + } + } + + public SimpleHttpRequest queryParam(String queryParam, Object value) { + if (this.queryParams.containsKey(Check.notNull(queryParam, "queryParam key cannot be null"))) { + throw new IllegalStateException("duplicate query param \"" + queryParam + "\""); + } else { + this.queryParams.put(queryParam, Check.notNull(value, "queryParam value cannot be null").toString()); + return this; + } + } + + public SimpleHttpRequest encodedQueryParam(String queryParam, String valueToEncode) { + return this.queryParam(queryParam, Formatting.urlEncodeUtf8(valueToEncode)); + } + + public SimpleHttpRequest queryParams(Object... queryParams) { + if (Check.notEmpty(queryParams, "queryParams cannot be empty").length % 2 != 0) { + throw new IllegalArgumentException( + "queryParams length must be a multple of two, with query params keys (String) at even indexes and their values (Object) at the adjacent odd ones" + ); + } else { + for (int i = 0; i < queryParams.length - 1; i += 2) { + Object objAtEven = Check.notNull(queryParams[i], "query param key cannot be null (index %s)", i); + String qpKey = Check.instanceOf( + objAtEven, + String.class, + "even indexes must contain query params keys; expected String at index %s, but got %s", + i, + objAtEven.getClass().getName() + ); + this.queryParam(qpKey, queryParams[i + 1]); + } + + return this; + } + } + + public SimpleHttpRequest requestProperty(String propertyName, String value) { + if (Check.notNull(propertyName, "propertyName cannot be null").equals("User-Agent")) { + throw new IllegalArgumentException("User-Agent must be set using method userAgent(...)"); + } else { + this.requestProperties.put(propertyName, Check.notNull(value, "value cannot be null")); + return this; + } + } + + public SimpleHttpRequest connectTimeout(int timeoutMillis) { + if (timeoutMillis < 0) { + throw new IllegalArgumentException("timeoutMillis must be a positive integer"); + } else { + this.connectTimeout = timeoutMillis; + return this; + } + } + + public SimpleHttpRequest readTimeout(int timeoutMillis) { + if (timeoutMillis < 0) { + throw new IllegalArgumentException("timeoutMillis must be a positive integer"); + } else { + this.readTimeout = timeoutMillis; + return this; + } + } + + public SimpleHttpRequest followRedirects(boolean follow) { + this.followRedirects = follow; + return this; + } + + public SimpleHttpRequest doInput(boolean doInput) { + this.doInput = doInput; + return this; + } + + public SimpleHttpRequest doOutput(boolean doOutput) { + this.doOutput = doOutput; + return this; + } + + @Override + public String getUserAgent() { + Check.state(this.userAgent == null, "userAgent not set"); + return this.userAgent; + } + + @Override + public RequestMethod getRequestMethod() { + Check.state(this.requestMethod == null, "requestMethod not set"); + return this.requestMethod; + } + + @Override + public boolean isSecured() { + Check.state(this.baseUrl == null, "baseUrl not set"); + return this.baseUrl.startsWith("https://"); + } + + @Override + public Map getRequestProperties() { + return this.requestProperties; + } + + @Override + public int getConnectTimeout() { + return this.connectTimeout; + } + + @Override + public int getReadTimeout() { + return this.readTimeout; + } + + @Override + public boolean shouldFollowRedirects() { + return this.followRedirects; + } + + @Override + public boolean shouldDoInput() { + return this.doInput; + } + + @Override + public boolean shouldDoOutput() { + return this.doOutput; + } + + @Override + public String getURL() throws IllegalStateException { + Check.state(this.baseUrl == null, "baseUrl not set"); + Check.state(this.path == null, "path not set"); + StringBuilder url = new StringBuilder(this.baseUrl + '/' + this.path); + boolean firstQParam = true; + + for (String queryParam : this.queryParams.keySet()) { + char appendChar = '&'; + if (firstQParam) { + appendChar = '?'; + firstQParam = false; + } + + url.append(appendChar).append(queryParam).append('=').append(this.queryParams.get(queryParam)); + } + + return url.toString(); + } + + public GetHttpRequest asGetRequest() { + if (this instanceof GetHttpRequest) { + return (GetHttpRequest)this; + } else { + throw new ClassCastException("not a GET request: " + this.getClass().getName()); + } + } + + public PostHttpRequest asPostRequest() { + if (this instanceof PostHttpRequest) { + return (PostHttpRequest)this; + } else { + throw new ClassCastException("not a POST request: " + this.getClass().getName()); + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/system/Env.java b/src/main/java/me/darksidecode/kantanj/system/Env.java new file mode 100644 index 0000000..e542f5a --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/system/Env.java @@ -0,0 +1,126 @@ +package me.darksidecode.kantanj.system; + +import java.util.NoSuchElementException; +import java.util.Optional; + +public final class Env { + private Env() { + } + + public static Optional getVarInteger(String key) { + Optional o = getVarString(key); + if (o.isPresent()) { + try { + return Optional.of(Integer.parseInt(o.get())); + } catch (NumberFormatException ignored) { + throw new NumberFormatException("env \"" + key + "\" is not of type Integer"); + } + } else { + return Optional.empty(); + } + } + + public static Integer requireVarInteger(String key) { + return getVarInteger(key).orElseThrow(() -> new NoSuchElementException("no such Integer env specified: " + key)); + } + + public static Optional getVarShort(String key) { + Optional o = getVarString(key); + if (o.isPresent()) { + try { + return Optional.of(Short.parseShort(o.get())); + } catch (NumberFormatException ignored) { + throw new NumberFormatException("env \"" + key + "\" is not of type Short"); + } + } else { + return Optional.empty(); + } + } + + public static Short requireVarShort(String key) { + return getVarShort(key).orElseThrow(() -> new NoSuchElementException("no such Short env specified: " + key)); + } + + public static Optional getVarLong(String key) { + Optional o = getVarString(key); + if (o.isPresent()) { + try { + return Optional.of(Long.parseLong(o.get())); + } catch (NumberFormatException ignored) { + throw new NumberFormatException("env \"" + key + "\" is not of type Long"); + } + } else { + return Optional.empty(); + } + } + + public static Long requireVarLong(String key) { + return getVarLong(key).orElseThrow(() -> new NoSuchElementException("no such Long env specified: " + key)); + } + + public static Optional getVarDouble(String key) { + Optional o = getVarString(key); + if (o.isPresent()) { + try { + return Optional.of(Double.parseDouble(o.get())); + } catch (NumberFormatException ignored) { + throw new NumberFormatException("env \"" + key + "\" is not of type Double"); + } + } else { + return Optional.empty(); + } + } + + public static Double requireVarDouble(String key) { + return getVarDouble(key).orElseThrow(() -> new NoSuchElementException("no such Double env specified: " + key)); + } + + public static Optional getVarFloat(String key) { + Optional o = getVarString(key); + if (o.isPresent()) { + try { + return Optional.of(Float.parseFloat(o.get())); + } catch (NumberFormatException ignored) { + throw new NumberFormatException("env \"" + key + "\" is not of type Float"); + } + } else { + return Optional.empty(); + } + } + + public static Float requireVarFloat(String key) { + return getVarFloat(key).orElseThrow(() -> new NoSuchElementException("no such Float env specified: " + key)); + } + + public static Optional getVarBoolean(String key) { + Optional o = getVarString(key); + if (o.isPresent()) { + switch (o.get().toLowerCase()) { + case "1": + case "yes": + case "true": + return Optional.of(true); + case "0": + case "no": + case "false": + return Optional.of(false); + default: + throw new NumberFormatException("env \"" + key + "\" is not of type Boolean"); + } + } else { + return Optional.empty(); + } + } + + public static Boolean requireVarBoolean(String key) { + return getVarBoolean(key).orElseThrow(() -> new NoSuchElementException("no such Boolean env specified: " + key)); + } + + public static Optional getVarString(String key) { + return Optional.ofNullable(System.getenv(key)); + } + + public static String requireVarString(String key) { + return getVarString(key).orElseThrow(() -> new NoSuchElementException("no such String env specified: " + key)); + } +} diff --git a/src/main/java/me/darksidecode/kantanj/system/FileUtils.java b/src/main/java/me/darksidecode/kantanj/system/FileUtils.java new file mode 100644 index 0000000..c283594 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/system/FileUtils.java @@ -0,0 +1,123 @@ +package me.darksidecode.kantanj.system; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; +import me.darksidecode.kantanj.crypto.Encryptor; +import me.darksidecode.kantanj.types.Check; +import org.apache.commons.io.IOUtils; + +public final class FileUtils { + private FileUtils() { + } + + public static byte[] readGZIP(File gzipFile) { + Check.fileExists(gzipFile, "no such file %s", gzipFile.getAbsolutePath()); + + try ( + FileInputStream fin = new FileInputStream(gzipFile); + GZIPInputStream gzipIn = new GZIPInputStream(fin); + ) { + return IOUtils.toByteArray(gzipIn); + } catch (Exception ex) { + throw new RuntimeException("failed to read gzip file " + gzipFile.getAbsolutePath(), ex); + } + } + + public static byte[] readEncryptedGZIP(File gzipFile, Encryptor encryptor) { + Check.fileExists(gzipFile, "no such file %s", gzipFile.getAbsolutePath()); + Check.notNull(encryptor, "encryptor cannot be null"); + File decrypted = new File(gzipFile.getAbsolutePath() + ".decr" + System.nanoTime()); + decrypted.deleteOnExit(); + + try { + byte[] origData = Files.readAllBytes(gzipFile.toPath()); + byte[] decryptedData = encryptor.decrypt(origData); + Files.write(decrypted.toPath(), decryptedData); + return readGZIP(decrypted); + } catch (Exception e) { + throw new RuntimeException("failed to read encrypted gzip file " + gzipFile.getAbsolutePath(), e); + } finally { + decrypted.delete(); + } + } + + public static void writeGZIP(File file, byte[] data, FileUtils.OverwriteMode overwriteMode) { + Check.notNull(file, "file cannot be null"); + Check.notNull(data, "data cannot be null"); + Check.notNull(overwriteMode, "overwriteMode cannot be null"); + if (file.exists()) { + if (file.isDirectory()) { + throw new IllegalArgumentException("expected file, got directory: " + file.getAbsolutePath()); + } + + switch (overwriteMode) { + case THROW_STATE_EXCEPTION: + throw new IllegalStateException("file already exists: " + file.getAbsolutePath()); + case DO_NOT_WRITE: + return; + case OVERWRITE: + file.delete(); + break; + case BACKUP: + String origPath = file.getAbsolutePath(); + if (origPath.endsWith("/")) { + origPath = origPath.substring(0, origPath.length() - 1); + } + + try { + byte[] originalData = Files.readAllBytes(file.toPath()); + Files.write(new File(origPath + "." + System.currentTimeMillis() + "~").toPath(), originalData); + file.delete(); + break; + } catch (IOException e) { + throw new RuntimeException("failed to backup file " + origPath, e); + } + default: + throw new UnsupportedOperationException("unsupported overwrite mode: " + overwriteMode.name()); + } + } + + try ( + FileOutputStream fos = new FileOutputStream(file); + GZIPOutputStream gzipOut = new GZIPOutputStream(fos); + ) { + gzipOut.write(data); + } catch (Exception e) { + throw new RuntimeException("failed to write gzip file (overwrite mode: " + overwriteMode + ") " + file.getAbsolutePath(), e); + } + } + + public static void writeEncryptedGZIP(File gzipFile, byte[] data, Encryptor encryptor, FileUtils.OverwriteMode overwriteMode) { + Check.notNull(encryptor, "encryptor cannot be null"); + writeGZIP(gzipFile, data, overwriteMode); + File encrypted = new File(gzipFile.getAbsolutePath() + ".encr" + System.nanoTime()); + encrypted.deleteOnExit(); + + try { + Path origPath = gzipFile.toPath(); + Path encryptedPath = encrypted.toPath(); + byte[] origData = Files.readAllBytes(origPath); + byte[] encryptedData = encryptor.encrypt(origData); + Files.write(encryptedPath, encryptedData); + Files.move(encryptedPath, origPath, StandardCopyOption.REPLACE_EXISTING); + } catch (Exception ex) { + throw new RuntimeException("failed to write encrypted gzip file (overwrite mode: " + overwriteMode + ") " + gzipFile.getAbsolutePath(), ex); + } finally { + encrypted.delete(); + } + } + + public static enum OverwriteMode { + THROW_STATE_EXCEPTION, + DO_NOT_WRITE, + OVERWRITE, + BACKUP; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/system/Shell.java b/src/main/java/me/darksidecode/kantanj/system/Shell.java new file mode 100644 index 0000000..7dc1236 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/system/Shell.java @@ -0,0 +1,38 @@ +package me.darksidecode.kantanj.system; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import me.darksidecode.kantanj.logging.BasicLogger; + +public final class Shell { + private Shell() { + } + + public static Process execute(String executor, File directory, String cmd, BasicLogger outLogger) { + try { + ProcessBuilder pb = new ProcessBuilder(cmd.split(" ")); + pb.directory(directory); + Process p = pb.start(); + optout(executor + "/INFO", p.getInputStream(), outLogger); + optout(executor + "/WARNING", p.getErrorStream(), outLogger); + return p; + } catch (Exception ex) { + throw new RuntimeException("bash command execution failure", ex); + } + } + + private static void optout(String name, InputStream stream, BasicLogger outLogger) throws Exception { + BufferedReader in = new BufferedReader(new InputStreamReader(stream)); + + String line; + while ((line = in.readLine()) != null) { + if (name.contains("ERROR")) { + outLogger.warning("(Bash) (%s) %s", name, line); + } else { + outLogger.info("(Bash) (%s) %s", name, line); + } + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/system/Threads.java b/src/main/java/me/darksidecode/kantanj/system/Threads.java new file mode 100644 index 0000000..e367490 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/system/Threads.java @@ -0,0 +1,16 @@ +package me.darksidecode.kantanj.system; + +import java.util.concurrent.TimeUnit; + +public class Threads { + public static void sleepQuietly(long duration, TimeUnit durationUnit) { + sleepQuietly(durationUnit.toMillis(duration)); + } + + public static void sleepQuietly(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException ignored) { + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/time/ExpiringList.java b/src/main/java/me/darksidecode/kantanj/time/ExpiringList.java new file mode 100644 index 0000000..caa75bf --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/time/ExpiringList.java @@ -0,0 +1,38 @@ +package me.darksidecode.kantanj.time; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import me.darksidecode.kantanj.types.Check; + +public class ExpiringList { + private final long entryLifespanMillis; + private final List entries; + private final Object lock = new Object(); + + public ExpiringList(long singleEntryLifespan, TimeUnit lifespanUnit) { + if (singleEntryLifespan < 1L) { + throw new IllegalArgumentException("invalid singleEntryLifespan: " + singleEntryLifespan); + } else { + this.entryLifespanMillis = Check.notNull(lifespanUnit, "lifespanUnit cannot be null").toMillis(singleEntryLifespan); + this.entries = new ArrayList<>(); + } + } + + public int updateAndCount() { + synchronized (this.lock) { + List expired = new ArrayList<>(); + this.entries.stream().filter(e -> System.currentTimeMillis() > e + this.entryLifespanMillis).forEach(expired::add); + expired.forEach(this.entries::remove); + this.entries.add(System.currentTimeMillis()); + return this.entries.size(); + } + } + + @Deprecated + public int count() { + synchronized (this.lock) { + return this.entries.size(); + } + } +} diff --git a/src/main/java/me/darksidecode/kantanj/types/Check.java b/src/main/java/me/darksidecode/kantanj/types/Check.java new file mode 100644 index 0000000..d8ed8c7 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/types/Check.java @@ -0,0 +1,67 @@ +package me.darksidecode.kantanj.types; + +import java.io.File; +import java.util.NoSuchElementException; + +public final class Check { + private static final String USERNAME_CHARSET = "qwertyuiopasdfghjklzxcvbnm1234567890_"; + + private Check() { + } + + public static T notNull(T obj, String message, Object... format) { + if (obj == null) { + throw new NullPointerException(makeMessage(message, format)); + } else { + return obj; + } + } + + public static T[] notEmpty(T[] array, String message, Object... format) { + if (((Object[])notNull((T)array, "array cannot be null")).length == 0) { + throw new IllegalArgumentException(makeMessage(message, format)); + } else { + return array; + } + } + + public static T instanceOf(Object obj, Class type, String message, Object... format) { + notNull(obj, "object cannot be null"); + notNull(type, "type cannot be null"); + if (!type.isInstance(notNull(obj, message))) { + throw new ClassCastException(makeMessage(message, format)); + } else { + return (T)obj; + } + } + + public static String username(String username) { + notNull(username, "username cannot be null"); + + for (char c : username.toCharArray()) { + if ("qwertyuiopasdfghjklzxcvbnm1234567890_".indexOf(c) == -1) { + throw new IllegalArgumentException("illegal character in username: " + c); + } + } + + return username; + } + + public static void state(boolean b, String message, Object... format) { + if (b) { + throw new IllegalStateException(makeMessage(message, format)); + } + } + + public static File fileExists(File file, String message, Object... format) { + if (!notNull(file, "file cannot be null").exists()) { + throw new NoSuchElementException(makeMessage(message, format)); + } else { + return file; + } + } + + private static String makeMessage(String message, Object... format) { + return format != null && format.length > 0 ? String.format(message, format) : message; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/types/Convert.java b/src/main/java/me/darksidecode/kantanj/types/Convert.java new file mode 100644 index 0000000..6318332 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/types/Convert.java @@ -0,0 +1,13 @@ +package me.darksidecode.kantanj.types; + +import com.google.gson.internal.LinkedTreeMap; +import org.bson.Document; + +public final class Convert { + private Convert() { + } + + public static Document treeMapToBsonDoc(LinkedTreeMap map) { + return new Document(map); + } +} diff --git a/src/main/java/me/darksidecode/kantanj/types/Maps.java b/src/main/java/me/darksidecode/kantanj/types/Maps.java new file mode 100644 index 0000000..0a45280 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/types/Maps.java @@ -0,0 +1,29 @@ +package me.darksidecode.kantanj.types; + +import java.util.Map; + +public final class Maps { + private Maps() { + } + + public static void copy(Map src, Map dest) { + Check.notNull(src, "source map cannot be null"); + Check.notNull(dest, "destination map cannot be null"); + src.forEach(dest::put); + } + + public static Map copy(Map src, Class typeOfDestMap) { + Check.notNull(src, "source map cannot be null"); + Check.notNull(typeOfDestMap, "type of destination map cannot be null"); + + Map dest; + try { + dest = (Map)typeOfDestMap.newInstance(); + } catch (IllegalAccessException | InstantiationException ex) { + throw new RuntimeException("failed to instantiatea new Map of type " + typeOfDestMap.getName(), ex); + } + + src.forEach(dest::put); + return dest; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/wrapper/ConcurrentObject.java b/src/main/java/me/darksidecode/kantanj/wrapper/ConcurrentObject.java new file mode 100644 index 0000000..34a5784 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/wrapper/ConcurrentObject.java @@ -0,0 +1,45 @@ +package me.darksidecode.kantanj.wrapper; + +import me.darksidecode.kantanj.types.Check; + +public class ConcurrentObject { + private final Object lock; + private T value; + + public ConcurrentObject() { + this(new Object(), null); + } + + public ConcurrentObject(T initialValue) { + this(new Object(), initialValue); + } + + public ConcurrentObject(Object lock, T initialValue) { + this.lock = Check.notNull(lock, "lock cannot be null"); + this.value = initialValue; + } + + public void set(T newValue) { + synchronized (this.lock) { + this.value = newValue; + } + } + + public T get() { + synchronized (this.lock) { + return this.value; + } + } + + public T getAndSwap(T newValue) { + synchronized (this.lock) { + T oldValue = this.value; + this.value = newValue; + return oldValue; + } + } + + public Object getLock() { + return this.lock; + } +} diff --git a/src/main/java/me/darksidecode/kantanj/wrapper/ExpiringObject.java b/src/main/java/me/darksidecode/kantanj/wrapper/ExpiringObject.java new file mode 100644 index 0000000..e229625 --- /dev/null +++ b/src/main/java/me/darksidecode/kantanj/wrapper/ExpiringObject.java @@ -0,0 +1,50 @@ +package me.darksidecode.kantanj.wrapper; + +import java.util.concurrent.TimeUnit; + +public abstract class ExpiringObject { + protected T value; + private final long lifespanMillis; + private long lastUpdateTime; + + public ExpiringObject(long lifespan, TimeUnit lifespanUnit) { + if ((this.lifespanMillis = lifespanUnit.toMillis(lifespan)) < 1L) { + throw new IllegalArgumentException("lifespan cannot be less than 1 millisecond"); + } else { + this.update(); + } + } + + public ExpiringObject(T initialValue, long lifespan, TimeUnit lifespanUnit) { + this.value = initialValue; + if ((this.lifespanMillis = lifespanUnit.toMillis(lifespan)) < 1L) { + throw new IllegalArgumentException("lifespan cannot be less than 1 millisecond"); + } else { + this.lastUpdateTime = System.currentTimeMillis(); + } + } + + public boolean hasExpired() { + return System.currentTimeMillis() > this.lastUpdateTime + this.lifespanMillis; + } + + public T get() { + if (this.hasExpired()) { + this.update(); + } + + return this.value; + } + + public final void update() { + try { + this.update0(); + } catch (Exception ex) { + throw new RuntimeException("failed to update " + this.getClass().getName(), ex); + } finally { + this.lastUpdateTime = System.currentTimeMillis(); + } + } + + protected abstract void update0() throws Exception; +} diff --git a/src/main/java/me/flo/flogger/Flogger4J.java b/src/main/java/me/flo/flogger/Flogger4J.java new file mode 100644 index 0000000..63ced80 --- /dev/null +++ b/src/main/java/me/flo/flogger/Flogger4J.java @@ -0,0 +1,91 @@ +package me.flo.flogger; + +import java.beans.ConstructorProperties; +import java.util.ArrayList; +import java.util.List; +import me.flo.flogger.types.FlogFormatter; +import me.flo.flogger.types.FlogLevel; +import me.flo.flogger.types.FlogPublisher; +import me.flo.flogger.types.FlogRecord; + +public class Flogger4J { + private static Flogger4J global; + private final String name; + private FlogLevel level = FlogLevel.INFO; + private FlogFormatter formatter = FlogFormatter.DEFAULT; + private final List publishers = new ArrayList<>(); + + public void log(FlogLevel level, String message) { + if (level == FlogLevel.OFF) { + throw new IllegalArgumentException("Level can't be OFF"); + } else { + FlogRecord record = new FlogRecord(this, level, message, System.currentTimeMillis()); + this.publishers.forEach(fp -> fp.handleIntern(record)); + } + } + + public void error(String message) { + this.log(FlogLevel.ERROR, message); + } + + public void warning(String message) { + this.log(FlogLevel.WARN, message); + } + + public void info(String message) { + this.log(FlogLevel.INFO, message); + } + + public void debug(String message) { + this.log(FlogLevel.DEBUG, message); + } + + public void trace(String message) { + this.log(FlogLevel.TRACE, message); + } + + public void addPublisher(FlogPublisher publisher) { + if (publisher.getLevel() == null) { + publisher.level(this.level); + } + + if (publisher.getFormatter() == null) { + publisher.formatter(this.formatter); + } + + this.publishers.add(publisher); + } + + public static Flogger4J initializeGlobal(String name) { + return global = new Flogger4J(name); + } + + public static Flogger4J global() { + return global; + } + + @ConstructorProperties({"name"}) + public Flogger4J(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public void setLevel(FlogLevel level) { + this.level = level; + } + + public FlogLevel getLevel() { + return this.level; + } + + public void setFormatter(FlogFormatter formatter) { + this.formatter = formatter; + } + + public FlogFormatter getFormatter() { + return this.formatter; + } +} diff --git a/src/main/java/me/flo/flogger/impl/AsyncLogWriterPublisher.java b/src/main/java/me/flo/flogger/impl/AsyncLogWriterPublisher.java new file mode 100644 index 0000000..878b323 --- /dev/null +++ b/src/main/java/me/flo/flogger/impl/AsyncLogWriterPublisher.java @@ -0,0 +1,40 @@ +package me.flo.flogger.impl; + +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import me.flo.flogger.types.FlogFormatter; +import me.flo.flogger.types.FlogPublisher; +import me.flo.flogger.types.FlogRecord; + +public abstract class AsyncLogWriterPublisher extends FlogPublisher implements Runnable { + private final LogWriterPublisher publisher; + private final BlockingQueue queue; + + public AsyncLogWriterPublisher(LogWriterPublisher publisher, int queueSize) { + this.publisher = publisher; + this.queue = queueSize == -1 ? new LinkedBlockingQueue<>() : new ArrayBlockingQueue<>(queueSize); + this.startAsync(this); + } + + @Override + public void run() { + while (this.publisher != null) { + try { + Object[] array = this.queue.take(); + this.publisher.handle((FlogRecord)array[0], (FlogFormatter)array[1]); + } catch (InterruptedException ex) { + new RuntimeException("FLOGGER CRASH", ex).printStackTrace(); + } + } + } + + @Override + public void handle(FlogRecord record, FlogFormatter formatter) { + if (!this.queue.offer(new Object[]{record, formatter})) { + throw new RuntimeException("No space left in logging queue."); + } + } + + protected abstract void startAsync(Runnable task); +} diff --git a/src/main/java/me/flo/flogger/impl/DailyLogFilePublisher.java b/src/main/java/me/flo/flogger/impl/DailyLogFilePublisher.java new file mode 100644 index 0000000..ee07179 --- /dev/null +++ b/src/main/java/me/flo/flogger/impl/DailyLogFilePublisher.java @@ -0,0 +1,58 @@ +package me.flo.flogger.impl; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Date; +import me.flo.flogger.types.FlogFormatter; +import me.flo.flogger.types.FlogRecord; + +public class DailyLogFilePublisher extends LogWriterPublisher { + private static final SimpleDateFormat format = new SimpleDateFormat("dd-MM-YYYY"); + private final File dir; + private File currentFile; + private int lastDayOfMonth = -1; + + public DailyLogFilePublisher(File directory) throws IOException { + super(new FileWriter(newFile(directory), true)); + this.currentFile = newFile(directory); + this.dir = directory; + } + + private static File newFile(File dir) throws IOException { + File f = new File(dir, format.format(new Date(System.currentTimeMillis())) + ".log"); + if (!f.exists()) { + f.createNewFile(); + } + + return f; + } + + @Override + public void handle(FlogRecord record, FlogFormatter formatter) { + LocalDate date = LocalDate.now(); + if (this.lastDayOfMonth != -1 && this.lastDayOfMonth != date.getDayOfMonth()) { + try { + this.writer.close(); + File nf = newFile(this.dir); + this.writer = new FileWriter(nf, true); + this.writerSwitched((FileWriter)this.writer, this.currentFile); + this.currentFile = nf; + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + this.lastDayOfMonth = date.getDayOfMonth(); + super.handle(record, formatter); + } + + protected void writerSwitched(FileWriter newWriter, File oldFile) { + } + + public File getCurrentFile() { + return this.currentFile; + } +} diff --git a/src/main/java/me/flo/flogger/impl/LogConsolePublisher.java b/src/main/java/me/flo/flogger/impl/LogConsolePublisher.java new file mode 100644 index 0000000..fb1b949 --- /dev/null +++ b/src/main/java/me/flo/flogger/impl/LogConsolePublisher.java @@ -0,0 +1,13 @@ +package me.flo.flogger.impl; + +import me.flo.flogger.types.FlogFormatter; +import me.flo.flogger.types.FlogLevel; +import me.flo.flogger.types.FlogPublisher; +import me.flo.flogger.types.FlogRecord; + +public final class LogConsolePublisher extends FlogPublisher { + @Override + public void handle(FlogRecord record, FlogFormatter formatter) { + (record.getLevel() == FlogLevel.ERROR ? System.err : System.out).println(formatter.format(record)); + } +} diff --git a/src/main/java/me/flo/flogger/impl/LogWriterPublisher.java b/src/main/java/me/flo/flogger/impl/LogWriterPublisher.java new file mode 100644 index 0000000..1cdcd57 --- /dev/null +++ b/src/main/java/me/flo/flogger/impl/LogWriterPublisher.java @@ -0,0 +1,28 @@ +package me.flo.flogger.impl; + +import java.beans.ConstructorProperties; +import java.io.IOException; +import java.io.Writer; +import me.flo.flogger.types.FlogException; +import me.flo.flogger.types.FlogFormatter; +import me.flo.flogger.types.FlogPublisher; +import me.flo.flogger.types.FlogRecord; + +public class LogWriterPublisher extends FlogPublisher { + protected Writer writer; + + @Override + public void handle(FlogRecord record, FlogFormatter formatter) { + try { + this.writer.write(formatter.format(record) + '\n'); + this.writer.flush(); + } catch (IOException ex) { + throw new FlogException("Failed to write to writer", ex); + } + } + + @ConstructorProperties({"writer"}) + public LogWriterPublisher(Writer writer) { + this.writer = writer; + } +} diff --git a/src/main/java/me/flo/flogger/types/FlogException.java b/src/main/java/me/flo/flogger/types/FlogException.java new file mode 100644 index 0000000..78188b1 --- /dev/null +++ b/src/main/java/me/flo/flogger/types/FlogException.java @@ -0,0 +1,7 @@ +package me.flo.flogger.types; + +public class FlogException extends RuntimeException { + public FlogException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/me/flo/flogger/types/FlogFormatter.java b/src/main/java/me/flo/flogger/types/FlogFormatter.java new file mode 100644 index 0000000..0615860 --- /dev/null +++ b/src/main/java/me/flo/flogger/types/FlogFormatter.java @@ -0,0 +1,36 @@ +package me.flo.flogger.types; + +import java.text.SimpleDateFormat; +import java.util.Collections; + +public interface FlogFormatter { + FlogFormatter DEFAULT = new FlogFormatter.Default(); + + String format(FlogRecord record); + + public static final class Default implements FlogFormatter { + private final SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss"); + private FlogRecord cacheRecord; + private String cacheFormatted; + + @Override + public String format(FlogRecord record) { + if (this.cacheRecord != null && this.cacheRecord.equals(record)) { + return this.cacheFormatted; + } else { + this.cacheRecord = record; + int i = 5 - record.getLevel().name().length(); + return this.cacheFormatted = '[' + + this.format.format(Long.valueOf(record.getTimestamp())) + + " -> " + + record.getLevel().name() + + String.join("", Collections.nCopies(i, " ")) + + "]: " + + record.getMessage(); + } + } + + private Default() { + } + } +} diff --git a/src/main/java/me/flo/flogger/types/FlogLevel.java b/src/main/java/me/flo/flogger/types/FlogLevel.java new file mode 100644 index 0000000..a5c829d --- /dev/null +++ b/src/main/java/me/flo/flogger/types/FlogLevel.java @@ -0,0 +1,14 @@ +package me.flo.flogger.types; + +public enum FlogLevel { + OFF, + ERROR, + WARN, + INFO, + DEBUG, + TRACE; + + public boolean isLoggable(FlogLevel logLevel) { + return this.ordinal() <= logLevel.ordinal(); + } +} diff --git a/src/main/java/me/flo/flogger/types/FlogPublisher.java b/src/main/java/me/flo/flogger/types/FlogPublisher.java new file mode 100644 index 0000000..485b7a8 --- /dev/null +++ b/src/main/java/me/flo/flogger/types/FlogPublisher.java @@ -0,0 +1,32 @@ +package me.flo.flogger.types; + +public abstract class FlogPublisher { + private FlogLevel level; + private FlogFormatter formatter; + + public void handleIntern(FlogRecord record) { + if (record.getLevel().isLoggable(this.level)) { + this.handle(record, this.formatter); + } + } + + protected abstract void handle(FlogRecord record, FlogFormatter formatter); + + public FlogPublisher level(FlogLevel level) { + this.level = level; + return this; + } + + public FlogPublisher formatter(FlogFormatter formatter) { + this.formatter = formatter; + return this; + } + + public FlogLevel getLevel() { + return this.level; + } + + public FlogFormatter getFormatter() { + return this.formatter; + } +} diff --git a/src/main/java/me/flo/flogger/types/FlogRecord.java b/src/main/java/me/flo/flogger/types/FlogRecord.java new file mode 100644 index 0000000..ddb408d --- /dev/null +++ b/src/main/java/me/flo/flogger/types/FlogRecord.java @@ -0,0 +1,93 @@ +package me.flo.flogger.types; + +import java.beans.ConstructorProperties; +import me.flo.flogger.Flogger4J; + +public class FlogRecord { + private final Flogger4J flogger; + private FlogLevel level; + private String message; + private final long timestamp; + + @ConstructorProperties({"flogger", "level", "message", "timestamp"}) + public FlogRecord(Flogger4J flogger, FlogLevel level, String message, long timestamp) { + this.flogger = flogger; + this.level = level; + this.message = message; + this.timestamp = timestamp; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (!(o instanceof FlogRecord)) { + return false; + } else { + FlogRecord other = (FlogRecord)o; + if (!other.canEqual(this)) { + return false; + } else { + Object this$flogger = this.getFlogger(); + Object other$flogger = other.getFlogger(); + if (this$flogger == null ? other$flogger == null : this$flogger.equals(other$flogger)) { + Object this$level = this.getLevel(); + Object other$level = other.getLevel(); + if (this$level == null ? other$level == null : this$level.equals(other$level)) { + Object this$message = this.getMessage(); + Object other$message = other.getMessage(); + return (this$message == null ? other$message == null : this$message.equals(other$message)) + ? this.getTimestamp() == other.getTimestamp() + : false; + } else { + return false; + } + } else { + return false; + } + } + } + } + + protected boolean canEqual(Object other) { + return other instanceof FlogRecord; + } + + @Override + public int hashCode() { + int PRIME = 59; + int result = 1; + Object $flogger = this.getFlogger(); + result = result * 59 + ($flogger == null ? 43 : $flogger.hashCode()); + Object $level = this.getLevel(); + result = result * 59 + ($level == null ? 43 : $level.hashCode()); + Object $message = this.getMessage(); + result = result * 59 + ($message == null ? 43 : $message.hashCode()); + long $timestamp = this.getTimestamp(); + return result * 59 + (int)($timestamp >>> 32 ^ $timestamp); + } + + public Flogger4J getFlogger() { + return this.flogger; + } + + public void setLevel(FlogLevel level) { + this.level = level; + } + + public FlogLevel getLevel() { + return this.level; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getMessage() { + return this.message; + } + + public long getTimestamp() { + return this.timestamp; + } +} diff --git a/src/main/java/org/bstats/Country.java b/src/main/java/org/bstats/Country.java new file mode 100644 index 0000000..df064cb --- /dev/null +++ b/src/main/java/org/bstats/Country.java @@ -0,0 +1,282 @@ +package org.bstats; + +import java.util.Arrays; +import java.util.Locale; + +public enum Country { + AUTO_DETECT("AUTO", "Auto Detected"), + ANDORRA("AD", "Andorra"), + UNITED_ARAB_EMIRATES("AE", "United Arab Emirates"), + AFGHANISTAN("AF", "Afghanistan"), + ANTIGUA_AND_BARBUDA("AG", "Antigua and Barbuda"), + ANGUILLA("AI", "Anguilla"), + ALBANIA("AL", "Albania"), + ARMENIA("AM", "Armenia"), + NETHERLANDS_ANTILLES("AN", "Netherlands Antilles"), + ANGOLA("AO", "Angola"), + ANTARCTICA("AQ", "Antarctica"), + ARGENTINA("AR", "Argentina"), + AMERICAN_SAMOA("AS", "American Samoa"), + AUSTRIA("AT", "Austria"), + AUSTRALIA("AU", "Australia"), + ARUBA("AW", "Aruba"), + ALAND_ISLANDS("AX", "Åland Islands"), + AZERBAIJAN("AZ", "Azerbaijan"), + BOSNIA_AND_HERZEGOVINA("BA", "Bosnia and Herzegovina"), + BARBADOS("BB", "Barbados"), + BANGLADESH("BD", "Bangladesh"), + BELGIUM("BE", "Belgium"), + BURKINA_FASO("BF", "Burkina Faso"), + BULGARIA("BG", "Bulgaria"), + BAHRAIN("BH", "Bahrain"), + BURUNDI("BI", "Burundi"), + BENIN("BJ", "Benin"), + SAINT_BARTHELEMY("BL", "Saint Barthélemy"), + BERMUDA("BM", "Bermuda"), + BRUNEI("BN", "Brunei"), + BOLIVIA("BO", "Bolivia"), + BONAIRE_SINT_EUSTATIUS_AND_SABA("BQ", "Bonaire, Sint Eustatius and Saba"), + BRAZIL("BR", "Brazil"), + BAHAMAS("BS", "Bahamas"), + BHUTAN("BT", "Bhutan"), + BOUVET_ISLAND("BV", "Bouvet Island"), + BOTSWANA("BW", "Botswana"), + BELARUS("BY", "Belarus"), + BELIZE("BZ", "Belize"), + CANADA("CA", "Canada"), + COCOS_ISLANDS("CC", "Cocos Islands"), + THE_DEMOCRATIC_REPUBLIC_OF_CONGO("CD", "The Democratic Republic Of Congo"), + CENTRAL_AFRICAN_REPUBLIC("CF", "Central African Republic"), + CONGO("CG", "Congo"), + SWITZERLAND("CH", "Switzerland"), + COTE_D_IVOIRE("CI", "Côte d'Ivoire"), + COOK_ISLANDS("CK", "Cook Islands"), + CHILE("CL", "Chile"), + CAMEROON("CM", "Cameroon"), + CHINA("CN", "China"), + COLOMBIA("CO", "Colombia"), + COSTA_RICA("CR", "Costa Rica"), + CUBA("CU", "Cuba"), + CAPE_VERDE("CV", "Cape Verde"), + CURACAO("CW", "Curaçao"), + CHRISTMAS_ISLAND("CX", "Christmas Island"), + CYPRUS("CY", "Cyprus"), + CZECH_REPUBLIC("CZ", "Czech Republic"), + GERMANY("DE", "Germany"), + DJIBOUTI("DJ", "Djibouti"), + DENMARK("DK", "Denmark"), + DOMINICA("DM", "Dominica"), + DOMINICAN_REPUBLIC("DO", "Dominican Republic"), + ALGERIA("DZ", "Algeria"), + ECUADOR("EC", "Ecuador"), + ESTONIA("EE", "Estonia"), + EGYPT("EG", "Egypt"), + WESTERN_SAHARA("EH", "Western Sahara"), + ERITREA("ER", "Eritrea"), + SPAIN("ES", "Spain"), + ETHIOPIA("ET", "Ethiopia"), + FINLAND("FI", "Finland"), + FIJI("FJ", "Fiji"), + FALKLAND_ISLANDS("FK", "Falkland Islands"), + MICRONESIA("FM", "Micronesia"), + FAROE_ISLANDS("FO", "Faroe Islands"), + FRANCE("FR", "France"), + GABON("GA", "Gabon"), + UNITED_KINGDOM("GB", "United Kingdom"), + GRENADA("GD", "Grenada"), + GEORGIA("GE", "Georgia"), + FRENCH_GUIANA("GF", "French Guiana"), + GUERNSEY("GG", "Guernsey"), + GHANA("GH", "Ghana"), + GIBRALTAR("GI", "Gibraltar"), + GREENLAND("GL", "Greenland"), + GAMBIA("GM", "Gambia"), + GUINEA("GN", "Guinea"), + GUADELOUPE("GP", "Guadeloupe"), + EQUATORIAL_GUINEA("GQ", "Equatorial Guinea"), + GREECE("GR", "Greece"), + SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS("GS", "South Georgia And The South Sandwich Islands"), + GUATEMALA("GT", "Guatemala"), + GUAM("GU", "Guam"), + GUINEA_BISSAU("GW", "Guinea-Bissau"), + GUYANA("GY", "Guyana"), + HONG_KONG("HK", "Hong Kong"), + HEARD_ISLAND_AND_MCDONALD_ISLANDS("HM", "Heard Island And McDonald Islands"), + HONDURAS("HN", "Honduras"), + CROATIA("HR", "Croatia"), + HAITI("HT", "Haiti"), + HUNGARY("HU", "Hungary"), + INDONESIA("ID", "Indonesia"), + IRELAND("IE", "Ireland"), + ISRAEL("IL", "Israel"), + ISLE_OF_MAN("IM", "Isle Of Man"), + INDIA("IN", "India"), + BRITISH_INDIAN_OCEAN_TERRITORY("IO", "British Indian Ocean Territory"), + IRAQ("IQ", "Iraq"), + IRAN("IR", "Iran"), + ICELAND("IS", "Iceland"), + ITALY("IT", "Italy"), + JERSEY("JE", "Jersey"), + JAMAICA("JM", "Jamaica"), + JORDAN("JO", "Jordan"), + JAPAN("JP", "Japan"), + KENYA("KE", "Kenya"), + KYRGYZSTAN("KG", "Kyrgyzstan"), + CAMBODIA("KH", "Cambodia"), + KIRIBATI("KI", "Kiribati"), + COMOROS("KM", "Comoros"), + SAINT_KITTS_AND_NEVIS("KN", "Saint Kitts And Nevis"), + NORTH_KOREA("KP", "North Korea"), + SOUTH_KOREA("KR", "South Korea"), + KUWAIT("KW", "Kuwait"), + CAYMAN_ISLANDS("KY", "Cayman Islands"), + KAZAKHSTAN("KZ", "Kazakhstan"), + LAOS("LA", "Laos"), + LEBANON("LB", "Lebanon"), + SAINT_LUCIA("LC", "Saint Lucia"), + LIECHTENSTEIN("LI", "Liechtenstein"), + SRI_LANKA("LK", "Sri Lanka"), + LIBERIA("LR", "Liberia"), + LESOTHO("LS", "Lesotho"), + LITHUANIA("LT", "Lithuania"), + LUXEMBOURG("LU", "Luxembourg"), + LATVIA("LV", "Latvia"), + LIBYA("LY", "Libya"), + MOROCCO("MA", "Morocco"), + MONACO("MC", "Monaco"), + MOLDOVA("MD", "Moldova"), + MONTENEGRO("ME", "Montenegro"), + SAINT_MARTIN("MF", "Saint Martin"), + MADAGASCAR("MG", "Madagascar"), + MARSHALL_ISLANDS("MH", "Marshall Islands"), + MACEDONIA("MK", "Macedonia"), + MALI("ML", "Mali"), + MYANMAR("MM", "Myanmar"), + MONGOLIA("MN", "Mongolia"), + MACAO("MO", "Macao"), + NORTHERN_MARIANA_ISLANDS("MP", "Northern Mariana Islands"), + MARTINIQUE("MQ", "Martinique"), + MAURITANIA("MR", "Mauritania"), + MONTSERRAT("MS", "Montserrat"), + MALTA("MT", "Malta"), + MAURITIUS("MU", "Mauritius"), + MALDIVES("MV", "Maldives"), + MALAWI("MW", "Malawi"), + MEXICO("MX", "Mexico"), + MALAYSIA("MY", "Malaysia"), + MOZAMBIQUE("MZ", "Mozambique"), + NAMIBIA("NA", "Namibia"), + NEW_CALEDONIA("NC", "New Caledonia"), + NIGER("NE", "Niger"), + NORFOLK_ISLAND("NF", "Norfolk Island"), + NIGERIA("NG", "Nigeria"), + NICARAGUA("NI", "Nicaragua"), + NETHERLANDS("NL", "Netherlands"), + NORWAY("NO", "Norway"), + NEPAL("NP", "Nepal"), + NAURU("NR", "Nauru"), + NIUE("NU", "Niue"), + NEW_ZEALAND("NZ", "New Zealand"), + OMAN("OM", "Oman"), + PANAMA("PA", "Panama"), + PERU("PE", "Peru"), + FRENCH_POLYNESIA("PF", "French Polynesia"), + PAPUA_NEW_GUINEA("PG", "Papua New Guinea"), + PHILIPPINES("PH", "Philippines"), + PAKISTAN("PK", "Pakistan"), + POLAND("PL", "Poland"), + SAINT_PIERRE_AND_MIQUELON("PM", "Saint Pierre And Miquelon"), + PITCAIRN("PN", "Pitcairn"), + PUERTO_RICO("PR", "Puerto Rico"), + PALESTINE("PS", "Palestine"), + PORTUGAL("PT", "Portugal"), + PALAU("PW", "Palau"), + PARAGUAY("PY", "Paraguay"), + QATAR("QA", "Qatar"), + REUNION("RE", "Reunion"), + ROMANIA("RO", "Romania"), + SERBIA("RS", "Serbia"), + RUSSIA("RU", "Russia"), + RWANDA("RW", "Rwanda"), + SAUDI_ARABIA("SA", "Saudi Arabia"), + SOLOMON_ISLANDS("SB", "Solomon Islands"), + SEYCHELLES("SC", "Seychelles"), + SUDAN("SD", "Sudan"), + SWEDEN("SE", "Sweden"), + SINGAPORE("SG", "Singapore"), + SAINT_HELENA("SH", "Saint Helena"), + SLOVENIA("SI", "Slovenia"), + SVALBARD_AND_JAN_MAYEN("SJ", "Svalbard And Jan Mayen"), + SLOVAKIA("SK", "Slovakia"), + SIERRA_LEONE("SL", "Sierra Leone"), + SAN_MARINO("SM", "San Marino"), + SENEGAL("SN", "Senegal"), + SOMALIA("SO", "Somalia"), + SURINAME("SR", "Suriname"), + SOUTH_SUDAN("SS", "South Sudan"), + SAO_TOME_AND_PRINCIPE("ST", "Sao Tome And Principe"), + EL_SALVADOR("SV", "El Salvador"), + SINT_MAARTEN_DUTCH_PART("SX", "Sint Maarten (Dutch part)"), + SYRIA("SY", "Syria"), + SWAZILAND("SZ", "Swaziland"), + TURKS_AND_CAICOS_ISLANDS("TC", "Turks And Caicos Islands"), + CHAD("TD", "Chad"), + FRENCH_SOUTHERN_TERRITORIES("TF", "French Southern Territories"), + TOGO("TG", "Togo"), + THAILAND("TH", "Thailand"), + TAJIKISTAN("TJ", "Tajikistan"), + TOKELAU("TK", "Tokelau"), + TIMOR_LESTE("TL", "Timor-Leste"), + TURKMENISTAN("TM", "Turkmenistan"), + TUNISIA("TN", "Tunisia"), + TONGA("TO", "Tonga"), + TURKEY("TR", "Turkey"), + TRINIDAD_AND_TOBAGO("TT", "Trinidad and Tobago"), + TUVALU("TV", "Tuvalu"), + TAIWAN("TW", "Taiwan"), + TANZANIA("TZ", "Tanzania"), + UKRAINE("UA", "Ukraine"), + UGANDA("UG", "Uganda"), + UNITED_STATES_MINOR_OUTLYING_ISLANDS("UM", "United States Minor Outlying Islands"), + UNITED_STATES("US", "United States"), + URUGUAY("UY", "Uruguay"), + UZBEKISTAN("UZ", "Uzbekistan"), + VATICAN("VA", "Vatican"), + SAINT_VINCENT_AND_THE_GRENADINES("VC", "Saint Vincent And The Grenadines"), + VENEZUELA("VE", "Venezuela"), + BRITISH_VIRGIN_ISLANDS("VG", "British Virgin Islands"), + U_S__VIRGIN_ISLANDS("VI", "U.S. Virgin Islands"), + VIETNAM("VN", "Vietnam"), + VANUATU("VU", "Vanuatu"), + WALLIS_AND_FUTUNA("WF", "Wallis And Futuna"), + SAMOA("WS", "Samoa"), + YEMEN("YE", "Yemen"), + MAYOTTE("YT", "Mayotte"), + SOUTH_AFRICA("ZA", "South Africa"), + ZAMBIA("ZM", "Zambia"), + ZIMBABWE("ZW", "Zimbabwe"); + + private final String isoTag; + private final String name; + + private Country(String isoTag, String name) { + this.isoTag = isoTag; + this.name = name; + } + + public static Country byIsoTag(String isoTag) { + return Arrays.stream(values()).filter(country -> country.getCountryIsoTag().equals(isoTag)).findFirst().orElse(null); + } + + public static Country byLocale(Locale locale) { + return byIsoTag(locale.getCountry()); + } + + public String getCountryName() { + return this.name; + } + + public String getCountryIsoTag() { + return this.isoTag; + } +} diff --git a/src/main/java/org/bstats/Metrics.java b/src/main/java/org/bstats/Metrics.java new file mode 100644 index 0000000..2a9b31c --- /dev/null +++ b/src/main/java/org/bstats/Metrics.java @@ -0,0 +1,248 @@ +package org.bstats; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.logging.Level; +import java.util.stream.Collectors; +import java.util.zip.GZIPOutputStream; +import javax.net.ssl.HttpsURLConnection; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.ServicePriority; +import org.bukkit.plugin.java.JavaPlugin; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import rip.reflex.Reflex; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class Metrics { + public static final int B_STATS_VERSION = 1; + private static final String URL = "https://bStats.org/submitData/bukkit"; + private static boolean logFailedRequests; + private static String serverUUID; + private final JavaPlugin plugin; + private final List charts = new ArrayList<>(); + private boolean firstSubmit = true; + + public Metrics(JavaPlugin p) { + if (p == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } else { + this.plugin = p; + File bStatsFolder = new File(p.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (!config.isSet("serverUuid")) { + config.addDefault("enabled", true); + config.addDefault("serverUuid", UUID.randomUUID().toString()); + config.addDefault("logFailedRequests", false); + config.options() + .header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\nTo honor their work, you should not disable it.\nThis has nearly no effect on the server performance!\nCheck out https://bStats.org/ to learn more :)" + ) + .copyDefaults(true); + + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + if (config.getBoolean("enabled", true)) { + boolean found = false; + + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); + found = true; + break; + } catch (NoSuchFieldException ignoredEx) { + } + } + + ReflexScheduler.sync() + .run(ReflexRunnable.simple("metric-load", () -> Bukkit.getServicesManager().register(Metrics.class, this, p, ServicePriority.Normal))); + if (!found) { + this.startSubmitting(); + } + } + } + } + + private static void sendData(JSONObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } else if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the f thread!"); + } else { + HttpsURLConnection connection = (HttpsURLConnection)new URL("https://bStats.org/submitData/bukkit").openConnection(); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + byte[] compressedData = compress(data.toString()); + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("User-Agent", "MC-Server/1"); + connection.setDoOutput(true); + DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); + outputStream.write(compressedData); + outputStream.flush(); + outputStream.close(); + connection.getInputStream().close(); + } + } + + private static byte[] compress(String str) throws IOException { + if (str == null) { + return null; + } else { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(outputStream); + gzip.write(str.getBytes("UTF-8")); + gzip.close(); + return outputStream.toByteArray(); + } + } + + public void addCustomChart(Metrics.CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } else { + this.charts.add(chart); + } + } + + private void startSubmitting() { + if (this.firstSubmit) { + Bukkit.getScheduler().runTaskLaterAsynchronously(Reflex.getReflex(), () -> { + this.firstSubmit = false; + this.startSubmitting(); + }, 6000L); + } else { + ReflexScheduler.sync().runTimer(new ReflexRunnable("M_987192") { + @Override + public void execute() throws Exception { + if (Metrics.this.plugin.isEnabled()) { + Metrics.this.submitData(); + } + } + }, 36000); + } + } + + public JSONObject getPluginData() { + JSONObject data = new JSONObject(); + String pluginName = this.plugin.getDescription().getName(); + String pluginVersion = this.plugin.getDescription().getVersion(); + data.put("pluginName", pluginName); + data.put("pluginVersion", pluginVersion); + JSONArray customCharts = this.charts + .stream() + .map(Metrics.CustomChart::getRequestJsonObject) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(JSONArray::new)); + data.put("customCharts", customCharts); + return data; + } + + private JSONObject getServerData() { + int playerAmount = Bukkit.getOnlinePlayers().size(); + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = Bukkit.getVersion(); + bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1); + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + JSONObject data = new JSONObject(); + data.put("serverUUID", serverUUID); + data.put("playerAmount", playerAmount); + data.put("onlineMode", onlineMode); + data.put("bukkitVersion", bukkitVersion); + data.put("javaVersion", javaVersion); + data.put("osName", osName); + data.put("osArch", osArch); + data.put("osVersion", osVersion); + data.put("coreCount", coreCount); + return data; + } + + private void submitData() { + JSONObject data = this.getServerData(); + JSONArray pluginData = new JSONArray(); + + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); + } catch (NoSuchFieldException ignored) { + continue; + } + + try { + pluginData.add(service.getMethod("getPluginData").invoke(Bukkit.getServicesManager().load(service))); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ignoredEx) { + } + } + + data.put("plugins", pluginData); + Bukkit.getScheduler().runTaskAsynchronously(Reflex.getReflex(), () -> { + try { + sendData(data); + } catch (Exception ex) { + if (logFailedRequests) { + this.plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + this.plugin.getName(), (Throwable)ex); + } + } + }); + } + + public abstract static class CustomChart { + protected final String chartId; + + public CustomChart(String chartId) { + if (chartId != null && !chartId.isEmpty()) { + this.chartId = chartId; + } else { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + } + + protected JSONObject getRequestJsonObject() { + JSONObject chart = new JSONObject(); + chart.put("chartId", this.chartId); + + try { + JSONObject data = this.getChartData(); + if (data == null) { + return null; + } else { + chart.put("data", data); + return chart; + } + } catch (Throwable e) { + if (Metrics.logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + this.chartId, e); + } + + return null; + } + } + + protected abstract JSONObject getChartData(); + } +} diff --git a/src/main/java/org/bstats/charts/AdvancedBarChart.java b/src/main/java/org/bstats/charts/AdvancedBarChart.java new file mode 100644 index 0000000..03cc620 --- /dev/null +++ b/src/main/java/org/bstats/charts/AdvancedBarChart.java @@ -0,0 +1,44 @@ +package org.bstats.charts; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map.Entry; +import org.bstats.Metrics; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +public abstract class AdvancedBarChart extends Metrics.CustomChart { + public AdvancedBarChart(String chartId) { + super(chartId); + } + + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + HashMap map = this.getValues(new HashMap<>()); + if (map != null && !map.isEmpty()) { + boolean allSkipped = true; + + for (Entry entry : map.entrySet()) { + if (entry.getValue().length != 0) { + allSkipped = false; + JSONArray categoryValues = new JSONArray(); + categoryValues.addAll(Arrays.asList(entry.getValue())); + values.put(entry.getKey(), categoryValues); + } + } + + if (allSkipped) { + return null; + } else { + data.put("values", values); + return data; + } + } else { + return null; + } + } +} diff --git a/src/main/java/org/bstats/charts/AdvancedMapChart.java b/src/main/java/org/bstats/charts/AdvancedMapChart.java new file mode 100644 index 0000000..efa6bac --- /dev/null +++ b/src/main/java/org/bstats/charts/AdvancedMapChart.java @@ -0,0 +1,41 @@ +package org.bstats.charts; + +import java.util.HashMap; +import java.util.Map.Entry; +import org.bstats.Country; +import org.bstats.Metrics; +import org.json.simple.JSONObject; + +public abstract class AdvancedMapChart extends Metrics.CustomChart { + public AdvancedMapChart(String chartId) { + super(chartId); + } + + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + HashMap map = this.getValues(new HashMap<>()); + if (map != null && !map.isEmpty()) { + boolean allSkipped = true; + + for (Entry entry : map.entrySet()) { + if (entry.getValue() != 0) { + allSkipped = false; + values.put(entry.getKey().getCountryIsoTag(), entry.getValue()); + } + } + + if (allSkipped) { + return null; + } else { + data.put("values", values); + return data; + } + } else { + return null; + } + } +} diff --git a/src/main/java/org/bstats/charts/MultiLineChart.java b/src/main/java/org/bstats/charts/MultiLineChart.java new file mode 100644 index 0000000..e3178dc --- /dev/null +++ b/src/main/java/org/bstats/charts/MultiLineChart.java @@ -0,0 +1,40 @@ +package org.bstats.charts; + +import java.util.HashMap; +import java.util.Map.Entry; +import org.bstats.Metrics; +import org.json.simple.JSONObject; + +public abstract class MultiLineChart extends Metrics.CustomChart { + public MultiLineChart(String chartId) { + super(chartId); + } + + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + HashMap map = this.getValues(new HashMap<>()); + if (map != null && !map.isEmpty()) { + boolean allSkipped = true; + + for (Entry entry : map.entrySet()) { + if (entry.getValue() != 0) { + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + } + + if (allSkipped) { + return null; + } else { + data.put("values", values); + return data; + } + } else { + return null; + } + } +} diff --git a/src/main/java/org/bstats/charts/SimpleBarChart.java b/src/main/java/org/bstats/charts/SimpleBarChart.java new file mode 100644 index 0000000..a34aaa9 --- /dev/null +++ b/src/main/java/org/bstats/charts/SimpleBarChart.java @@ -0,0 +1,34 @@ +package org.bstats.charts; + +import java.util.HashMap; +import java.util.Map.Entry; +import org.bstats.Metrics; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +public abstract class SimpleBarChart extends Metrics.CustomChart { + public SimpleBarChart(String chartId) { + super(chartId); + } + + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + HashMap map = this.getValues(new HashMap<>()); + if (map != null && !map.isEmpty()) { + for (Entry entry : map.entrySet()) { + JSONArray categoryValues = new JSONArray(); + categoryValues.add(entry.getValue()); + values.put(entry.getKey(), categoryValues); + } + + data.put("values", values); + return data; + } else { + return null; + } + } +} diff --git a/src/main/java/org/bstats/charts/SimpleMapChart.java b/src/main/java/org/bstats/charts/SimpleMapChart.java new file mode 100644 index 0000000..87b49c0 --- /dev/null +++ b/src/main/java/org/bstats/charts/SimpleMapChart.java @@ -0,0 +1,25 @@ +package org.bstats.charts; + +import org.bstats.Country; +import org.bstats.Metrics; +import org.json.simple.JSONObject; + +public abstract class SimpleMapChart extends Metrics.CustomChart { + public SimpleMapChart(String chartId) { + super(chartId); + } + + public abstract Country getValue(); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + Country value = this.getValue(); + if (value == null) { + return null; + } else { + data.put("value", value.getCountryIsoTag()); + return data; + } + } +} diff --git a/src/main/java/org/bstats/charts/SingleLineChart.java b/src/main/java/org/bstats/charts/SingleLineChart.java new file mode 100644 index 0000000..596a214 --- /dev/null +++ b/src/main/java/org/bstats/charts/SingleLineChart.java @@ -0,0 +1,24 @@ +package org.bstats.charts; + +import org.bstats.Metrics; +import org.json.simple.JSONObject; + +public abstract class SingleLineChart extends Metrics.CustomChart { + public SingleLineChart(String chartId) { + super(chartId); + } + + public abstract int getValue(); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + int value = this.getValue(); + if (value == 0) { + return null; + } else { + data.put("value", value); + return data; + } + } +} diff --git a/src/main/java/org/bstats/pie/AdvancedPie.java b/src/main/java/org/bstats/pie/AdvancedPie.java new file mode 100644 index 0000000..347e7a2 --- /dev/null +++ b/src/main/java/org/bstats/pie/AdvancedPie.java @@ -0,0 +1,40 @@ +package org.bstats.pie; + +import java.util.HashMap; +import java.util.Map.Entry; +import org.bstats.Metrics; +import org.json.simple.JSONObject; + +public abstract class AdvancedPie extends Metrics.CustomChart { + public AdvancedPie(String chartId) { + super(chartId); + } + + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + HashMap map = this.getValues(new HashMap<>()); + if (map != null && !map.isEmpty()) { + boolean allSkipped = true; + + for (Entry entry : map.entrySet()) { + if (entry.getValue() != 0) { + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + } + + if (allSkipped) { + return null; + } else { + data.put("values", values); + return data; + } + } else { + return null; + } + } +} diff --git a/src/main/java/org/bstats/pie/SimplePie.java b/src/main/java/org/bstats/pie/SimplePie.java new file mode 100644 index 0000000..c56f77a --- /dev/null +++ b/src/main/java/org/bstats/pie/SimplePie.java @@ -0,0 +1,24 @@ +package org.bstats.pie; + +import org.bstats.Metrics; +import org.json.simple.JSONObject; + +public abstract class SimplePie extends Metrics.CustomChart { + public SimplePie(String chartId) { + super(chartId); + } + + public abstract String getValue(); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + String value = this.getValue(); + if (value != null && !value.isEmpty()) { + data.put("value", value); + return data; + } else { + return null; + } + } +} diff --git a/src/main/java/ove/crypto/digest/Blake2b.java b/src/main/java/ove/crypto/digest/Blake2b.java new file mode 100644 index 0000000..3c398ae --- /dev/null +++ b/src/main/java/ove/crypto/digest/Blake2b.java @@ -0,0 +1,1020 @@ +package ove.crypto.digest; + +import java.io.PrintStream; +import java.security.Key; +import java.security.spec.AlgorithmParameterSpec; +import java.util.Arrays; + +public interface Blake2b { + void update(byte[] input); + + void update(byte input); + + void update(byte[] input, int offset, int length); + + byte[] digest(); + + byte[] digest(byte[] input); + + void digest(byte[] out, int offset, int length); + + void reset(); + + public static class Digest extends Blake2b.Engine implements Blake2b { + private Digest(Blake2b.Param p) { + super(p); + } + + private Digest() { + } + + public static Blake2b.Digest newInstance() { + return new Blake2b.Digest(); + } + + public static Blake2b.Digest newInstance(int digestLength) { + return new Blake2b.Digest(new Blake2b.Param().setDigestLength(digestLength)); + } + + public static Blake2b.Digest newInstance(Blake2b.Param p) { + return new Blake2b.Digest(p); + } + } + + public static class Engine implements Blake2b { + static final int[] sig_g00 = new int[]{0, 14, 11, 7, 9, 2, 12, 13, 6, 10, 0, 14}; + static final int[] sig_g01 = new int[]{1, 10, 8, 9, 0, 12, 5, 11, 15, 2, 1, 10}; + static final int[] sig_g10 = new int[]{2, 4, 12, 3, 5, 6, 1, 7, 14, 8, 2, 4}; + static final int[] sig_g11 = new int[]{3, 8, 0, 1, 7, 10, 15, 14, 9, 4, 3, 8}; + static final int[] sig_g20 = new int[]{4, 9, 5, 13, 2, 0, 14, 12, 11, 7, 4, 9}; + static final int[] sig_g21 = new int[]{5, 15, 2, 12, 4, 11, 13, 1, 3, 6, 5, 15}; + static final int[] sig_g30 = new int[]{6, 13, 15, 11, 10, 8, 4, 3, 0, 1, 6, 13}; + static final int[] sig_g31 = new int[]{7, 6, 13, 14, 15, 3, 10, 9, 8, 5, 7, 6}; + static final int[] sig_g40 = new int[]{8, 1, 10, 2, 14, 4, 0, 5, 12, 15, 8, 1}; + static final int[] sig_g41 = new int[]{9, 12, 14, 6, 1, 13, 7, 0, 2, 11, 9, 12}; + static final int[] sig_g50 = new int[]{10, 0, 3, 5, 11, 7, 6, 15, 13, 9, 10, 0}; + static final int[] sig_g51 = new int[]{11, 2, 6, 10, 12, 5, 3, 4, 7, 14, 11, 2}; + static final int[] sig_g60 = new int[]{12, 11, 7, 4, 6, 15, 9, 8, 1, 3, 12, 11}; + static final int[] sig_g61 = new int[]{13, 7, 1, 0, 8, 14, 2, 6, 4, 12, 13, 7}; + static final int[] sig_g70 = new int[]{14, 5, 9, 15, 3, 1, 8, 2, 10, 13, 14, 5}; + static final int[] sig_g71 = new int[]{15, 3, 4, 8, 13, 9, 11, 10, 5, 0, 15, 3}; + private final long[] h = new long[8]; + private final long[] t = new long[2]; + private final long[] f = new long[2]; + private boolean last_node = false; + private final long[] m = new long[16]; + private final long[] v = new long[16]; + private final byte[] buffer; + private int buflen; + private final Blake2b.Param param; + private final int outlen; + private byte[] oneByte; + private static byte[] zeropad = new byte[128]; + + Engine() { + this(new Blake2b.Param()); + } + + Engine(Blake2b.Param param) { + assert param != null : "param is null"; + + this.param = param; + this.buffer = new byte[128]; + this.oneByte = new byte[1]; + this.outlen = param.getDigestLength(); + if (param.getDepth() > 1) { + int ndepth = param.getNodeDepth(); + long nxoff = param.getNodeOffset(); + if (ndepth == param.getDepth() - 1) { + this.last_node = true; + + assert param.getNodeOffset() == 0L : "root must have offset of zero"; + } else if (param.getNodeOffset() == (long)(param.getFanout() - 1)) { + this.last_node = true; + } + } + + this.initialize(); + } + + private void initialize() { + System.arraycopy(this.param.initialized_H(), 0, this.h, 0, 8); + if (this.param.hasKey) { + this.update(this.param.key_bytes, 0, 128); + } + } + + public static void main(String... args) { + Blake2b mac = Blake2b.Mac.newInstance("LOVE".getBytes()); + byte[] hash = mac.digest("Salaam!".getBytes()); + } + + @Override + public final void reset() { + this.buflen = 0; + + for (int i = 0; i < this.buffer.length; i++) { + this.buffer[i] = 0; + } + + this.f[0] = 0L; + this.f[1] = 0L; + this.t[0] = 0L; + this.t[1] = 0L; + this.initialize(); + } + + @Override + public final void update(byte[] b, int off, int len) { + if (b == null) { + throw new IllegalArgumentException("input buffer (b) is null"); + } else { + while (len > 0) { + if (this.buflen == 0) { + while (len > 128) { + this.t[0] = this.t[0] + 128L; + this.t[1] = this.t[1] + (this.t[0] == 0L ? 1L : 0L); + this.compress(b, off); + len -= 128; + off += 128; + } + } else if (this.buflen == 128) { + this.t[0] = this.t[0] + 128L; + this.t[1] = this.t[1] + (this.t[0] == 0L ? 1L : 0L); + this.compress(this.buffer, 0); + this.buflen = 0; + continue; + } + + if (len == 0) { + return; + } + + int cap = 128 - this.buflen; + int fill = len > cap ? cap : len; + System.arraycopy(b, off, this.buffer, this.buflen, fill); + this.buflen += fill; + len -= fill; + off += fill; + } + } + } + + @Override + public final void update(byte b) { + this.oneByte[0] = b; + this.update(this.oneByte, 0, 1); + } + + @Override + public final void update(byte[] input) { + this.update(input, 0, input.length); + } + + @Override + public final void digest(byte[] output, int off, int len) { + System.arraycopy(zeropad, 0, this.buffer, this.buflen, 128 - this.buflen); + if (this.buflen > 0) { + this.t[0] = this.t[0] + (long)this.buflen; + this.t[1] = this.t[1] + (this.t[0] == 0L ? 1L : 0L); + } + + this.f[0] = -1L; + this.f[1] = this.last_node ? -1L : 0L; + this.compress(this.buffer, 0); + this.hashout(output, off, len); + this.reset(); + } + + @Override + public final byte[] digest() throws IllegalArgumentException { + byte[] out = new byte[this.outlen]; + this.digest(out, 0, this.outlen); + return out; + } + + @Override + public final byte[] digest(byte[] input) { + this.update(input, 0, input.length); + return this.digest(); + } + + private void hashout(byte[] out, int offset, int hashlen) { + int lcnt = hashlen >>> 3; + long v = 0L; + int i = offset; + + for (int w = 0; w < lcnt; w++) { + v = this.h[w]; + out[i++] = (byte)((int)v); + v >>>= 8; + out[i++] = (byte)((int)v); + v >>>= 8; + out[i++] = (byte)((int)v); + v >>>= 8; + out[i++] = (byte)((int)v); + v >>>= 8; + out[i++] = (byte)((int)v); + v >>>= 8; + out[i++] = (byte)((int)v); + v >>>= 8; + out[i++] = (byte)((int)v); + v >>>= 8; + out[i++] = (byte)((int)v); + } + + if (hashlen != 64) { + v = this.h[lcnt]; + + for (int idx = lcnt << 3; idx < hashlen; idx++) { + out[offset + idx] = (byte)((int)v); + v >>>= 8; + } + } + } + + private void compress(byte[] b, int offset) { + this.m[0] = (long)b[offset] & 255L; + this.m[0] = this.m[0] | ((long)b[offset + 1] & 255L) << 8; + this.m[0] = this.m[0] | ((long)b[offset + 2] & 255L) << 16; + this.m[0] = this.m[0] | ((long)b[offset + 3] & 255L) << 24; + this.m[0] = this.m[0] | ((long)b[offset + 4] & 255L) << 32; + this.m[0] = this.m[0] | ((long)b[offset + 5] & 255L) << 40; + this.m[0] = this.m[0] | ((long)b[offset + 6] & 255L) << 48; + this.m[0] = this.m[0] | (long)b[offset + 7] << 56; + this.m[1] = (long)b[offset + 8] & 255L; + this.m[1] = this.m[1] | ((long)b[offset + 9] & 255L) << 8; + this.m[1] = this.m[1] | ((long)b[offset + 10] & 255L) << 16; + this.m[1] = this.m[1] | ((long)b[offset + 11] & 255L) << 24; + this.m[1] = this.m[1] | ((long)b[offset + 12] & 255L) << 32; + this.m[1] = this.m[1] | ((long)b[offset + 13] & 255L) << 40; + this.m[1] = this.m[1] | ((long)b[offset + 14] & 255L) << 48; + this.m[1] = this.m[1] | (long)b[offset + 15] << 56; + this.m[2] = (long)b[offset + 16] & 255L; + this.m[2] = this.m[2] | ((long)b[offset + 17] & 255L) << 8; + this.m[2] = this.m[2] | ((long)b[offset + 18] & 255L) << 16; + this.m[2] = this.m[2] | ((long)b[offset + 19] & 255L) << 24; + this.m[2] = this.m[2] | ((long)b[offset + 20] & 255L) << 32; + this.m[2] = this.m[2] | ((long)b[offset + 21] & 255L) << 40; + this.m[2] = this.m[2] | ((long)b[offset + 22] & 255L) << 48; + this.m[2] = this.m[2] | (long)b[offset + 23] << 56; + this.m[3] = (long)b[offset + 24] & 255L; + this.m[3] = this.m[3] | ((long)b[offset + 25] & 255L) << 8; + this.m[3] = this.m[3] | ((long)b[offset + 26] & 255L) << 16; + this.m[3] = this.m[3] | ((long)b[offset + 27] & 255L) << 24; + this.m[3] = this.m[3] | ((long)b[offset + 28] & 255L) << 32; + this.m[3] = this.m[3] | ((long)b[offset + 29] & 255L) << 40; + this.m[3] = this.m[3] | ((long)b[offset + 30] & 255L) << 48; + this.m[3] = this.m[3] | (long)b[offset + 31] << 56; + this.m[4] = (long)b[offset + 32] & 255L; + this.m[4] = this.m[4] | ((long)b[offset + 33] & 255L) << 8; + this.m[4] = this.m[4] | ((long)b[offset + 34] & 255L) << 16; + this.m[4] = this.m[4] | ((long)b[offset + 35] & 255L) << 24; + this.m[4] = this.m[4] | ((long)b[offset + 36] & 255L) << 32; + this.m[4] = this.m[4] | ((long)b[offset + 37] & 255L) << 40; + this.m[4] = this.m[4] | ((long)b[offset + 38] & 255L) << 48; + this.m[4] = this.m[4] | (long)b[offset + 39] << 56; + this.m[5] = (long)b[offset + 40] & 255L; + this.m[5] = this.m[5] | ((long)b[offset + 41] & 255L) << 8; + this.m[5] = this.m[5] | ((long)b[offset + 42] & 255L) << 16; + this.m[5] = this.m[5] | ((long)b[offset + 43] & 255L) << 24; + this.m[5] = this.m[5] | ((long)b[offset + 44] & 255L) << 32; + this.m[5] = this.m[5] | ((long)b[offset + 45] & 255L) << 40; + this.m[5] = this.m[5] | ((long)b[offset + 46] & 255L) << 48; + this.m[5] = this.m[5] | (long)b[offset + 47] << 56; + this.m[6] = (long)b[offset + 48] & 255L; + this.m[6] = this.m[6] | ((long)b[offset + 49] & 255L) << 8; + this.m[6] = this.m[6] | ((long)b[offset + 50] & 255L) << 16; + this.m[6] = this.m[6] | ((long)b[offset + 51] & 255L) << 24; + this.m[6] = this.m[6] | ((long)b[offset + 52] & 255L) << 32; + this.m[6] = this.m[6] | ((long)b[offset + 53] & 255L) << 40; + this.m[6] = this.m[6] | ((long)b[offset + 54] & 255L) << 48; + this.m[6] = this.m[6] | (long)b[offset + 55] << 56; + this.m[7] = (long)b[offset + 56] & 255L; + this.m[7] = this.m[7] | ((long)b[offset + 57] & 255L) << 8; + this.m[7] = this.m[7] | ((long)b[offset + 58] & 255L) << 16; + this.m[7] = this.m[7] | ((long)b[offset + 59] & 255L) << 24; + this.m[7] = this.m[7] | ((long)b[offset + 60] & 255L) << 32; + this.m[7] = this.m[7] | ((long)b[offset + 61] & 255L) << 40; + this.m[7] = this.m[7] | ((long)b[offset + 62] & 255L) << 48; + this.m[7] = this.m[7] | (long)b[offset + 63] << 56; + this.m[8] = (long)b[offset + 64] & 255L; + this.m[8] = this.m[8] | ((long)b[offset + 65] & 255L) << 8; + this.m[8] = this.m[8] | ((long)b[offset + 66] & 255L) << 16; + this.m[8] = this.m[8] | ((long)b[offset + 67] & 255L) << 24; + this.m[8] = this.m[8] | ((long)b[offset + 68] & 255L) << 32; + this.m[8] = this.m[8] | ((long)b[offset + 69] & 255L) << 40; + this.m[8] = this.m[8] | ((long)b[offset + 70] & 255L) << 48; + this.m[8] = this.m[8] | (long)b[offset + 71] << 56; + this.m[9] = (long)b[offset + 72] & 255L; + this.m[9] = this.m[9] | ((long)b[offset + 73] & 255L) << 8; + this.m[9] = this.m[9] | ((long)b[offset + 74] & 255L) << 16; + this.m[9] = this.m[9] | ((long)b[offset + 75] & 255L) << 24; + this.m[9] = this.m[9] | ((long)b[offset + 76] & 255L) << 32; + this.m[9] = this.m[9] | ((long)b[offset + 77] & 255L) << 40; + this.m[9] = this.m[9] | ((long)b[offset + 78] & 255L) << 48; + this.m[9] = this.m[9] | (long)b[offset + 79] << 56; + this.m[10] = (long)b[offset + 80] & 255L; + this.m[10] = this.m[10] | ((long)b[offset + 81] & 255L) << 8; + this.m[10] = this.m[10] | ((long)b[offset + 82] & 255L) << 16; + this.m[10] = this.m[10] | ((long)b[offset + 83] & 255L) << 24; + this.m[10] = this.m[10] | ((long)b[offset + 84] & 255L) << 32; + this.m[10] = this.m[10] | ((long)b[offset + 85] & 255L) << 40; + this.m[10] = this.m[10] | ((long)b[offset + 86] & 255L) << 48; + this.m[10] = this.m[10] | (long)b[offset + 87] << 56; + this.m[11] = (long)b[offset + 88] & 255L; + this.m[11] = this.m[11] | ((long)b[offset + 89] & 255L) << 8; + this.m[11] = this.m[11] | ((long)b[offset + 90] & 255L) << 16; + this.m[11] = this.m[11] | ((long)b[offset + 91] & 255L) << 24; + this.m[11] = this.m[11] | ((long)b[offset + 92] & 255L) << 32; + this.m[11] = this.m[11] | ((long)b[offset + 93] & 255L) << 40; + this.m[11] = this.m[11] | ((long)b[offset + 94] & 255L) << 48; + this.m[11] = this.m[11] | (long)b[offset + 95] << 56; + this.m[12] = (long)b[offset + 96] & 255L; + this.m[12] = this.m[12] | ((long)b[offset + 97] & 255L) << 8; + this.m[12] = this.m[12] | ((long)b[offset + 98] & 255L) << 16; + this.m[12] = this.m[12] | ((long)b[offset + 99] & 255L) << 24; + this.m[12] = this.m[12] | ((long)b[offset + 100] & 255L) << 32; + this.m[12] = this.m[12] | ((long)b[offset + 101] & 255L) << 40; + this.m[12] = this.m[12] | ((long)b[offset + 102] & 255L) << 48; + this.m[12] = this.m[12] | (long)b[offset + 103] << 56; + this.m[13] = (long)b[offset + 104] & 255L; + this.m[13] = this.m[13] | ((long)b[offset + 105] & 255L) << 8; + this.m[13] = this.m[13] | ((long)b[offset + 106] & 255L) << 16; + this.m[13] = this.m[13] | ((long)b[offset + 107] & 255L) << 24; + this.m[13] = this.m[13] | ((long)b[offset + 108] & 255L) << 32; + this.m[13] = this.m[13] | ((long)b[offset + 109] & 255L) << 40; + this.m[13] = this.m[13] | ((long)b[offset + 110] & 255L) << 48; + this.m[13] = this.m[13] | (long)b[offset + 111] << 56; + this.m[14] = (long)b[offset + 112] & 255L; + this.m[14] = this.m[14] | ((long)b[offset + 113] & 255L) << 8; + this.m[14] = this.m[14] | ((long)b[offset + 114] & 255L) << 16; + this.m[14] = this.m[14] | ((long)b[offset + 115] & 255L) << 24; + this.m[14] = this.m[14] | ((long)b[offset + 116] & 255L) << 32; + this.m[14] = this.m[14] | ((long)b[offset + 117] & 255L) << 40; + this.m[14] = this.m[14] | ((long)b[offset + 118] & 255L) << 48; + this.m[14] = this.m[14] | (long)b[offset + 119] << 56; + this.m[15] = (long)b[offset + 120] & 255L; + this.m[15] = this.m[15] | ((long)b[offset + 121] & 255L) << 8; + this.m[15] = this.m[15] | ((long)b[offset + 122] & 255L) << 16; + this.m[15] = this.m[15] | ((long)b[offset + 123] & 255L) << 24; + this.m[15] = this.m[15] | ((long)b[offset + 124] & 255L) << 32; + this.m[15] = this.m[15] | ((long)b[offset + 125] & 255L) << 40; + this.m[15] = this.m[15] | ((long)b[offset + 126] & 255L) << 48; + this.m[15] = this.m[15] | (long)b[offset + 127] << 56; + this.v[0] = this.h[0]; + this.v[1] = this.h[1]; + this.v[2] = this.h[2]; + this.v[3] = this.h[3]; + this.v[4] = this.h[4]; + this.v[5] = this.h[5]; + this.v[6] = this.h[6]; + this.v[7] = this.h[7]; + this.v[8] = 7640891576956012808L; + this.v[9] = -4942790177534073029L; + this.v[10] = 4354685564936845355L; + this.v[11] = -6534734903238641935L; + this.v[12] = this.t[0] ^ 5840696475078001361L; + this.v[13] = this.t[1] ^ -7276294671716946913L; + this.v[14] = this.f[0] ^ 2270897969802886507L; + this.v[15] = this.f[1] ^ 6620516959819538809L; + + for (int r = 0; r < 12; r++) { + this.v[0] = this.v[0] + this.v[4] + this.m[sig_g00[r]]; + this.v[12] = this.v[12] ^ this.v[0]; + this.v[12] = this.v[12] << 32 | this.v[12] >>> 32; + this.v[8] = this.v[8] + this.v[12]; + this.v[4] = this.v[4] ^ this.v[8]; + this.v[4] = this.v[4] >>> 24 | this.v[4] << 40; + this.v[0] = this.v[0] + this.v[4] + this.m[sig_g01[r]]; + this.v[12] = this.v[12] ^ this.v[0]; + this.v[12] = this.v[12] >>> 16 | this.v[12] << 48; + this.v[8] = this.v[8] + this.v[12]; + this.v[4] = this.v[4] ^ this.v[8]; + this.v[4] = this.v[4] << 1 | this.v[4] >>> 63; + this.v[1] = this.v[1] + this.v[5] + this.m[sig_g10[r]]; + this.v[13] = this.v[13] ^ this.v[1]; + this.v[13] = this.v[13] << 32 | this.v[13] >>> 32; + this.v[9] = this.v[9] + this.v[13]; + this.v[5] = this.v[5] ^ this.v[9]; + this.v[5] = this.v[5] >>> 24 | this.v[5] << 40; + this.v[1] = this.v[1] + this.v[5] + this.m[sig_g11[r]]; + this.v[13] = this.v[13] ^ this.v[1]; + this.v[13] = this.v[13] >>> 16 | this.v[13] << 48; + this.v[9] = this.v[9] + this.v[13]; + this.v[5] = this.v[5] ^ this.v[9]; + this.v[5] = this.v[5] << 1 | this.v[5] >>> 63; + this.v[2] = this.v[2] + this.v[6] + this.m[sig_g20[r]]; + this.v[14] = this.v[14] ^ this.v[2]; + this.v[14] = this.v[14] << 32 | this.v[14] >>> 32; + this.v[10] = this.v[10] + this.v[14]; + this.v[6] = this.v[6] ^ this.v[10]; + this.v[6] = this.v[6] >>> 24 | this.v[6] << 40; + this.v[2] = this.v[2] + this.v[6] + this.m[sig_g21[r]]; + this.v[14] = this.v[14] ^ this.v[2]; + this.v[14] = this.v[14] >>> 16 | this.v[14] << 48; + this.v[10] = this.v[10] + this.v[14]; + this.v[6] = this.v[6] ^ this.v[10]; + this.v[6] = this.v[6] << 1 | this.v[6] >>> 63; + this.v[3] = this.v[3] + this.v[7] + this.m[sig_g30[r]]; + this.v[15] = this.v[15] ^ this.v[3]; + this.v[15] = this.v[15] << 32 | this.v[15] >>> 32; + this.v[11] = this.v[11] + this.v[15]; + this.v[7] = this.v[7] ^ this.v[11]; + this.v[7] = this.v[7] >>> 24 | this.v[7] << 40; + this.v[3] = this.v[3] + this.v[7] + this.m[sig_g31[r]]; + this.v[15] = this.v[15] ^ this.v[3]; + this.v[15] = this.v[15] >>> 16 | this.v[15] << 48; + this.v[11] = this.v[11] + this.v[15]; + this.v[7] = this.v[7] ^ this.v[11]; + this.v[7] = this.v[7] << 1 | this.v[7] >>> 63; + this.v[0] = this.v[0] + this.v[5] + this.m[sig_g40[r]]; + this.v[15] = this.v[15] ^ this.v[0]; + this.v[15] = this.v[15] << 32 | this.v[15] >>> 32; + this.v[10] = this.v[10] + this.v[15]; + this.v[5] = this.v[5] ^ this.v[10]; + this.v[5] = this.v[5] >>> 24 | this.v[5] << 40; + this.v[0] = this.v[0] + this.v[5] + this.m[sig_g41[r]]; + this.v[15] = this.v[15] ^ this.v[0]; + this.v[15] = this.v[15] >>> 16 | this.v[15] << 48; + this.v[10] = this.v[10] + this.v[15]; + this.v[5] = this.v[5] ^ this.v[10]; + this.v[5] = this.v[5] << 1 | this.v[5] >>> 63; + this.v[1] = this.v[1] + this.v[6] + this.m[sig_g50[r]]; + this.v[12] = this.v[12] ^ this.v[1]; + this.v[12] = this.v[12] << 32 | this.v[12] >>> 32; + this.v[11] = this.v[11] + this.v[12]; + this.v[6] = this.v[6] ^ this.v[11]; + this.v[6] = this.v[6] >>> 24 | this.v[6] << 40; + this.v[1] = this.v[1] + this.v[6] + this.m[sig_g51[r]]; + this.v[12] = this.v[12] ^ this.v[1]; + this.v[12] = this.v[12] >>> 16 | this.v[12] << 48; + this.v[11] = this.v[11] + this.v[12]; + this.v[6] = this.v[6] ^ this.v[11]; + this.v[6] = this.v[6] << 1 | this.v[6] >>> 63; + this.v[2] = this.v[2] + this.v[7] + this.m[sig_g60[r]]; + this.v[13] = this.v[13] ^ this.v[2]; + this.v[13] = this.v[13] << 32 | this.v[13] >>> 32; + this.v[8] = this.v[8] + this.v[13]; + this.v[7] = this.v[7] ^ this.v[8]; + this.v[7] = this.v[7] >>> 24 | this.v[7] << 40; + this.v[2] = this.v[2] + this.v[7] + this.m[sig_g61[r]]; + this.v[13] = this.v[13] ^ this.v[2]; + this.v[13] = this.v[13] >>> 16 | this.v[13] << 48; + this.v[8] = this.v[8] + this.v[13]; + this.v[7] = this.v[7] ^ this.v[8]; + this.v[7] = this.v[7] << 1 | this.v[7] >>> 63; + this.v[3] = this.v[3] + this.v[4] + this.m[sig_g70[r]]; + this.v[14] = this.v[14] ^ this.v[3]; + this.v[14] = this.v[14] << 32 | this.v[14] >>> 32; + this.v[9] = this.v[9] + this.v[14]; + this.v[4] = this.v[4] ^ this.v[9]; + this.v[4] = this.v[4] >>> 24 | this.v[4] << 40; + this.v[3] = this.v[3] + this.v[4] + this.m[sig_g71[r]]; + this.v[14] = this.v[14] ^ this.v[3]; + this.v[14] = this.v[14] >>> 16 | this.v[14] << 48; + this.v[9] = this.v[9] + this.v[14]; + this.v[4] = this.v[4] ^ this.v[9]; + this.v[4] = this.v[4] << 1 | this.v[4] >>> 63; + } + + this.h[0] = this.h[0] ^ this.v[0] ^ this.v[8]; + this.h[1] = this.h[1] ^ this.v[1] ^ this.v[9]; + this.h[2] = this.h[2] ^ this.v[2] ^ this.v[10]; + this.h[3] = this.h[3] ^ this.v[3] ^ this.v[11]; + this.h[4] = this.h[4] ^ this.v[4] ^ this.v[12]; + this.h[5] = this.h[5] ^ this.v[5] ^ this.v[13]; + this.h[6] = this.h[6] ^ this.v[6] ^ this.v[14]; + this.h[7] = this.h[7] ^ this.v[7] ^ this.v[15]; + } + + public static final class Assert { + public static final String exclusiveUpperBound = "'%s' %d is >= %d"; + public static final String inclusiveUpperBound = "'%s' %d is > %d"; + public static final String exclusiveLowerBound = "'%s' %d is <= %d"; + public static final String inclusiveLowerBound = "'%s' %d is < %d"; + + static String assertFail(String name, T v, String err, T spec) { + new Exception().printStackTrace(); + return String.format(err, name, v, spec); + } + } + + public static class Debug { + public static void dumpState(Blake2b.Engine e, String mark) { + System.out.format("-- MARK == @ %s @ ===========\n", mark); + dumpArray("register t", e.t); + dumpArray("register h", e.h); + dumpArray("register f", e.f); + dumpArray("register offset", new long[]{(long)e.buflen}); + System.out.format("-- END MARK =================\n"); + } + + public static void dumpArray(String label, long[] b) { + System.out.format("-- %s -- :\n{\n", label); + + for (int j = 0; j < b.length; j++) { + System.out.format(" [%2d] : %016X\n", j, b[j]); + } + + System.out.format("}\n"); + } + + public static void dumpBuffer(PrintStream out, String label, byte[] b) { + dumpBuffer(out, label, b, 0, b.length); + } + + public static void dumpBuffer(PrintStream out, byte[] b) { + dumpBuffer(out, null, b, 0, b.length); + } + + public static void dumpBuffer(PrintStream out, byte[] b, int offset, int len) { + dumpBuffer(out, null, b, offset, len); + } + + public static void dumpBuffer(PrintStream out, String label, byte[] b, int offset, int len) { + if (label != null) { + out.format("-- %s -- :\n", label); + } + + out.format("{\n ", label); + + for (int j = 0; j < len; j++) { + out.format("%02X", b[j + offset]); + if (j + 1 < len) { + if ((j + 1) % 8 == 0) { + out.print("\n "); + } else { + out.print(' '); + } + } + } + + out.format("\n}\n"); + } + } + + public static class LittleEndian { + private static final byte[] hex_digits = new byte[]{48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102}; + private static final byte[] HEX_digits = new byte[]{48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70}; + + public static String toHexStr(byte[] b) { + return toHexStr(b, false); + } + + public static String toHexStr(byte[] b, boolean upperCase) { + int len = b.length; + byte[] digits = new byte[len * 2]; + byte[] hex_rep = upperCase ? HEX_digits : hex_digits; + + for (int i = 0; i < len; i++) { + digits[i * 2] = hex_rep[(byte)(b[i] >> 4 & 15)]; + digits[i * 2 + 1] = hex_rep[(byte)(b[i] & 15)]; + } + + return new String(digits); + } + + public static int readInt(byte[] b, int off) { + int v0 = b[off++] & 255; + v0 |= (b[off++] & 255) << 8; + v0 |= (b[off++] & 255) << 16; + return v0 | b[off] << 24; + } + + public static long readLong(byte[] b, int off) { + long v0 = (long)b[off++] & 255L; + v0 |= ((long)b[off++] & 255L) << 8; + v0 |= ((long)b[off++] & 255L) << 16; + v0 |= ((long)b[off++] & 255L) << 24; + v0 |= ((long)b[off++] & 255L) << 32; + v0 |= ((long)b[off++] & 255L) << 40; + v0 |= ((long)b[off++] & 255L) << 48; + return v0 | (long)b[off] << 56; + } + + public static void writeLong(long v, byte[] b, int off) { + b[off] = (byte)((int)v); + v >>>= 8; + b[off + 1] = (byte)((int)v); + v >>>= 8; + b[off + 2] = (byte)((int)v); + v >>>= 8; + b[off + 3] = (byte)((int)v); + v >>>= 8; + b[off + 4] = (byte)((int)v); + v >>>= 8; + b[off + 5] = (byte)((int)v); + v >>>= 8; + b[off + 6] = (byte)((int)v); + v >>>= 8; + b[off + 7] = (byte)((int)v); + } + + public static void writeInt(int v, byte[] b, int off) { + b[off] = (byte)v; + v >>>= 8; + b[off + 1] = (byte)v; + v >>>= 8; + b[off + 2] = (byte)v; + v >>>= 8; + b[off + 3] = (byte)v; + } + } + + interface flag { + int last_block = 0; + int last_node = 1; + } + } + + public static class Mac extends Blake2b.Engine implements Blake2b { + private Mac(Blake2b.Param p) { + super(p); + } + + private Mac() { + } + + public static Blake2b.Mac newInstance(byte[] key) { + return new Blake2b.Mac(new Blake2b.Param().setKey(key)); + } + + public static Blake2b.Mac newInstance(byte[] key, int digestLength) { + return new Blake2b.Mac(new Blake2b.Param().setKey(key).setDigestLength(digestLength)); + } + + public static Blake2b.Mac newInstance(Key key, int digestLength) { + return new Blake2b.Mac(new Blake2b.Param().setKey(key).setDigestLength(digestLength)); + } + + public static Blake2b.Mac newInstance(Blake2b.Param p) { + assert p != null : "Param (p) is null"; + + assert p.hasKey() : "Param (p) not configured with a key"; + + return new Blake2b.Mac(p); + } + } + + public static class Param implements AlgorithmParameterSpec { + static final byte[] default_bytes = new byte[64]; + static final long[] default_h = new long[8]; + private boolean hasKey = false; + private byte[] key_bytes = null; + private byte[] bytes = null; + private final long[] h = new long[8]; + + public Param() { + System.arraycopy(default_h, 0, this.h, 0, 8); + } + + public long[] initialized_H() { + return this.h; + } + + public byte[] getBytes() { + this.lazyInitBytes(); + byte[] copy = new byte[this.bytes.length]; + System.arraycopy(this.bytes, 0, copy, 0, this.bytes.length); + return copy; + } + + final byte getByteParam(int xoffset) { + byte[] _bytes = this.bytes; + if (_bytes == null) { + _bytes = default_bytes; + } + + return _bytes[xoffset]; + } + + final int getIntParam(int xoffset) { + byte[] _bytes = this.bytes; + if (_bytes == null) { + _bytes = default_bytes; + } + + return Blake2b.Engine.LittleEndian.readInt(_bytes, xoffset); + } + + final long getLongParam(int xoffset) { + byte[] _bytes = this.bytes; + if (_bytes == null) { + _bytes = default_bytes; + } + + return Blake2b.Engine.LittleEndian.readLong(_bytes, xoffset); + } + + public final int getDigestLength() { + return this.getByteParam(0); + } + + public final int getKeyLength() { + return this.getByteParam(1); + } + + public final int getFanout() { + return this.getByteParam(2); + } + + public final int getDepth() { + return this.getByteParam(3); + } + + public final int getLeafLength() { + return this.getIntParam(4); + } + + public final long getNodeOffset() { + return this.getLongParam(8); + } + + public final int getNodeDepth() { + return this.getByteParam(16); + } + + public final int getInnerLength() { + return this.getByteParam(17); + } + + public final boolean hasKey() { + return this.hasKey; + } + + public Blake2b.Param clone() { + Blake2b.Param clone = new Blake2b.Param(); + System.arraycopy(this.h, 0, clone.h, 0, this.h.length); + clone.lazyInitBytes(); + System.arraycopy(this.bytes, 0, clone.bytes, 0, this.bytes.length); + if (this.hasKey) { + clone.hasKey = this.hasKey; + clone.key_bytes = new byte[128]; + System.arraycopy(this.key_bytes, 0, clone.key_bytes, 0, this.key_bytes.length); + } + + return clone; + } + + final void lazyInitBytes() { + if (this.bytes == null) { + this.bytes = new byte[64]; + System.arraycopy(default_bytes, 0, this.bytes, 0, 64); + } + } + + public final Blake2b.Param setDigestLength(int len) { + assert len > 0 : Blake2b.Engine.Assert.assertFail("len", len, "'%s' %d is <= %d", 0); + + assert len <= 64 : Blake2b.Engine.Assert.assertFail("len", len, "'%s' %d is > %d", 64); + + this.lazyInitBytes(); + this.bytes[0] = (byte)len; + this.h[0] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 0); + this.h[0] = this.h[0] ^ Blake2b.Spec.IV[0]; + return this; + } + + public final Blake2b.Param setKey(Key key) { + assert key != null : "key is null"; + + byte[] keybytes = key.getEncoded(); + + assert keybytes != null : "key.encoded() is null"; + + return this.setKey(keybytes); + } + + public final Blake2b.Param setKey(byte[] key) { + assert key != null : "key is null"; + + assert key.length >= 0 : Blake2b.Engine.Assert.assertFail("key.length", key.length, "'%s' %d is > %d", 0); + + assert key.length <= 64 : Blake2b.Engine.Assert.assertFail("key.length", key.length, "'%s' %d is > %d", 64); + + this.key_bytes = new byte[128]; + System.arraycopy(key, 0, this.key_bytes, 0, key.length); + this.lazyInitBytes(); + this.bytes[1] = (byte)key.length; + this.h[0] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 0); + this.h[0] = this.h[0] ^ Blake2b.Spec.IV[0]; + this.hasKey = true; + return this; + } + + public final Blake2b.Param setFanout(int fanout) { + assert fanout > 0 : Blake2b.Engine.Assert.assertFail("fanout", fanout, "'%s' %d is <= %d", 0); + + this.lazyInitBytes(); + this.bytes[2] = (byte)fanout; + this.h[0] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 0); + this.h[0] = this.h[0] ^ Blake2b.Spec.IV[0]; + return this; + } + + public final Blake2b.Param setDepth(int depth) { + assert depth > 0 : Blake2b.Engine.Assert.assertFail("depth", depth, "'%s' %d is <= %d", 0); + + this.lazyInitBytes(); + this.bytes[3] = (byte)depth; + this.h[0] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 0); + this.h[0] = this.h[0] ^ Blake2b.Spec.IV[0]; + return this; + } + + public final Blake2b.Param setLeafLength(int leaf_length) { + assert leaf_length >= 0 : Blake2b.Engine.Assert.assertFail("leaf_length", leaf_length, "'%s' %d is < %d", 0); + + this.lazyInitBytes(); + Blake2b.Engine.LittleEndian.writeInt(leaf_length, this.bytes, 4); + this.h[0] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 0); + this.h[0] = this.h[0] ^ Blake2b.Spec.IV[0]; + return this; + } + + public final Blake2b.Param setNodeOffset(long node_offset) { + assert node_offset >= 0L : Blake2b.Engine.Assert.assertFail("node_offset", node_offset, "'%s' %d is < %d", 0); + + this.lazyInitBytes(); + Blake2b.Engine.LittleEndian.writeLong(node_offset, this.bytes, 8); + this.h[1] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 8); + this.h[1] = this.h[1] ^ Blake2b.Spec.IV[1]; + return this; + } + + public final Blake2b.Param setNodeDepth(int node_depth) { + assert node_depth >= 0 : Blake2b.Engine.Assert.assertFail("node_depth", node_depth, "'%s' %d is < %d", 0); + + this.lazyInitBytes(); + this.bytes[16] = (byte)node_depth; + this.h[2] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 16); + this.h[2] = this.h[2] ^ Blake2b.Spec.IV[2]; + this.h[3] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 24); + this.h[3] = this.h[3] ^ Blake2b.Spec.IV[3]; + return this; + } + + public final Blake2b.Param setInnerLength(int inner_length) { + assert inner_length >= 0 : Blake2b.Engine.Assert.assertFail("inner_length", inner_length, "'%s' %d is < %d", 0); + + this.lazyInitBytes(); + this.bytes[17] = (byte)inner_length; + this.h[2] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 16); + this.h[2] = this.h[2] ^ Blake2b.Spec.IV[2]; + this.h[3] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 24); + this.h[3] = this.h[3] ^ Blake2b.Spec.IV[3]; + return this; + } + + public final Blake2b.Param setSalt(byte[] salt) { + assert salt != null : "salt is null"; + + assert salt.length <= 16 : Blake2b.Engine.Assert.assertFail("salt.length", salt.length, "'%s' %d is > %d", 16); + + this.lazyInitBytes(); + Arrays.fill(this.bytes, 32, 48, (byte)0); + System.arraycopy(salt, 0, this.bytes, 32, salt.length); + this.h[4] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 32); + this.h[4] = this.h[4] ^ Blake2b.Spec.IV[4]; + this.h[5] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 40); + this.h[5] = this.h[5] ^ Blake2b.Spec.IV[5]; + return this; + } + + public final Blake2b.Param setPersonal(byte[] personal) { + assert personal != null : "personal is null"; + + assert personal.length <= 16 : Blake2b.Engine.Assert.assertFail("personal.length", personal.length, "'%s' %d is > %d", 16); + + this.lazyInitBytes(); + Arrays.fill(this.bytes, 48, 64, (byte)0); + System.arraycopy(personal, 0, this.bytes, 48, personal.length); + this.h[6] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 48); + this.h[6] = this.h[6] ^ Blake2b.Spec.IV[6]; + this.h[7] = Blake2b.Engine.LittleEndian.readLong(this.bytes, 56); + this.h[7] = this.h[7] ^ Blake2b.Spec.IV[7]; + return this; + } + + static { + default_bytes[0] = 64; + default_bytes[1] = 0; + default_bytes[2] = 1; + default_bytes[3] = 1; + default_bytes[16] = 0; + default_bytes[17] = 0; + default_h[0] = Blake2b.Engine.LittleEndian.readLong(default_bytes, 0); + default_h[1] = Blake2b.Engine.LittleEndian.readLong(default_bytes, 8); + default_h[2] = Blake2b.Engine.LittleEndian.readLong(default_bytes, 16); + default_h[3] = Blake2b.Engine.LittleEndian.readLong(default_bytes, 24); + default_h[4] = Blake2b.Engine.LittleEndian.readLong(default_bytes, 32); + default_h[5] = Blake2b.Engine.LittleEndian.readLong(default_bytes, 40); + default_h[6] = Blake2b.Engine.LittleEndian.readLong(default_bytes, 48); + default_h[7] = Blake2b.Engine.LittleEndian.readLong(default_bytes, 56); + default_h[0] = default_h[0] ^ Blake2b.Spec.IV[0]; + default_h[1] = default_h[1] ^ Blake2b.Spec.IV[1]; + default_h[2] = default_h[2] ^ Blake2b.Spec.IV[2]; + default_h[3] = default_h[3] ^ Blake2b.Spec.IV[3]; + default_h[4] = default_h[4] ^ Blake2b.Spec.IV[4]; + default_h[5] = default_h[5] ^ Blake2b.Spec.IV[5]; + default_h[6] = default_h[6] ^ Blake2b.Spec.IV[6]; + default_h[7] = default_h[7] ^ Blake2b.Spec.IV[7]; + } + + public interface Default { + byte digest_length = 64; + byte key_length = 0; + byte fanout = 1; + byte depth = 1; + int leaf_length = 0; + long node_offset = 0L; + byte node_depth = 0; + byte inner_length = 0; + } + + interface Xoff { + int digest_length = 0; + int key_length = 1; + int fanout = 2; + int depth = 3; + int leaf_length = 4; + int node_offset = 8; + int node_depth = 16; + int inner_length = 17; + int reserved = 18; + int salt = 32; + int personal = 48; + } + } + + public interface Spec { + int param_bytes = 64; + int block_bytes = 128; + int max_digest_bytes = 64; + int max_key_bytes = 64; + int max_salt_bytes = 16; + int max_personalization_bytes = 16; + int state_space_len = 8; + int max_tree_fantout = 255; + int max_tree_depth = 255; + int max_tree_leaf_length = -1; + long max_node_offset = -1L; + int max_tree_inner_length = 255; + long[] IV = new long[]{ + 7640891576956012808L, + -4942790177534073029L, + 4354685564936845355L, + -6534734903238641935L, + 5840696475078001361L, + -7276294671716946913L, + 2270897969802886507L, + 6620516959819538809L + }; + byte[][] sigma = new byte[][]{ + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + {14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3}, + {11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4}, + {7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8}, + {9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13}, + {2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9}, + {12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11}, + {13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10}, + {6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5}, + {10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + {14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3} + }; + } + + public static class Tree { + final int depth; + final int fanout; + final int leaf_length; + final int inner_length; + final int digest_length; + + public Tree(int depth, int fanout, int leaf_length, int inner_length, int digest_length) { + this.fanout = fanout; + this.depth = depth; + this.leaf_length = leaf_length; + this.inner_length = inner_length; + this.digest_length = digest_length; + } + + private Blake2b.Param treeParam() { + return new Blake2b.Param().setDepth(this.depth).setFanout(this.fanout).setLeafLength(this.leaf_length).setInnerLength(this.inner_length); + } + + public final Blake2b.Digest getNode(int depth, int offset) { + Blake2b.Param nodeParam = this.treeParam().setNodeDepth(depth).setNodeOffset((long)offset).setDigestLength(this.inner_length); + return Blake2b.Digest.newInstance(nodeParam); + } + + public final Blake2b.Digest getRoot() { + int depth = this.depth - 1; + Blake2b.Param rootParam = this.treeParam().setNodeDepth(depth).setNodeOffset(0L).setDigestLength(this.digest_length); + return Blake2b.Digest.newInstance(rootParam); + } + } +} diff --git a/src/main/java/rip/reflex/Reflex.java b/src/main/java/rip/reflex/Reflex.java new file mode 100644 index 0000000..32b4304 --- /dev/null +++ b/src/main/java/rip/reflex/Reflex.java @@ -0,0 +1,1341 @@ +package rip.reflex; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Writer; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLStreamHandler; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.SplittableRandom; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import me.flo.flogger.Flogger4J; +import me.flo.flogger.impl.AsyncLogWriterPublisher; +import me.flo.flogger.impl.DailyLogFilePublisher; +import me.flo.flogger.impl.LogConsolePublisher; +import me.flo.flogger.impl.LogWriterPublisher; +import me.flo.flogger.types.FlogFormatter; +import me.flo.flogger.types.FlogLevel; +import me.flo.flogger.types.FlogRecord; +import org.apache.commons.io.FileUtils; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permission; +import org.bukkit.plugin.java.JavaPlugin; +import rip.reflex.api.BanInfo; +import rip.reflex.api.ReflexAPI; +import rip.reflex.api.ReflexAPIProvider; +import rip.reflex.api.ReflexPlayerData; +import rip.reflex.api.db.BanImpl; +import rip.reflex.api.db.DataImpl; +import rip.reflex.api.db.DatabaseClient; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckLoader; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.cloud.CloudComputer; +import rip.reflex.cloud.CloudService; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexCommand; +import rip.reflex.command.reflex.CommandReflex; +import rip.reflex.java9.J9Util; +import rip.reflex.listener.CentralEventListener; +import rip.reflex.listener.ExtremeLoginListener; +import rip.reflex.listener.FuckingEventListener; +import rip.reflex.listener.base.EventLoader; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.listener.impl.PlayerVelocityListener; +import rip.reflex.moonlight.ReflexMoonlight; +import rip.reflex.networking.BestServersFile; +import rip.reflex.networking.ReflexNetworking; +import rip.reflex.networking.ReflexServer; +import rip.reflex.util.appearance.Theme; +import rip.reflex.util.appearance.ThemeManager; +import rip.reflex.util.data.Stats; +import rip.reflex.util.db.DatabaseLoader; +import rip.reflex.util.db.DatabaseType; +import rip.reflex.util.db.logs.MySQLLogUtil; +import rip.reflex.util.debugging.Debugger; +import rip.reflex.util.debugging.PacketDebugger; +import rip.reflex.util.location.Movement; +import rip.reflex.util.math.Maths; +import rip.reflex.util.misc.AdvCfgLoader; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.mod.DependencyChecker; +import rip.reflex.util.mod.badlionclient.BadlionConfigMaker; +import rip.reflex.util.net.ssl.HackedTrustManager; +import rip.reflex.util.performance.PlayerPacketBasedServerPerformanceTracker; +import rip.reflex.util.performance.ServerPerformanceTracker; +import rip.reflex.util.performance.TPSMeter; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.mcaccess.MCAccess; +import rip.reflex.util.protocol.npc.NPCCommons; +import rip.reflex.util.protocol.npc.NPCTeamTricks; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.protocolsupport.ProtocolSupportHook; +import rip.reflex.util.protocol.viaversion.ViaVersionHook; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; +import rip.reflex.util.time.Timer; +import sun.net.www.protocol.https.Handler; + +public class Reflex extends JavaPlugin { + private boolean initDone; + private static Reflex instance; + private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.YYYY"); + private final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); + private final SplittableRandom random = new SplittableRandom(); + private final Map configCache = new ConcurrentHashMap<>(); + private static Theme theme; + private static Map rawTheme; + private String workingDir; + private volatile boolean disableClientCheckingDueToBugs; + private TPSMeter tpsMeter; + private DatabaseType usedDB; + private ReflexServer syncServer; + private ReflexServer cloudServer; + public static int[] vrf = new int[20]; + private static final String[] _apiAccess = new String[5]; + private DatabaseClient client; + private DataImpl dataImpl; + private BanImpl banImpl; + public int _r_ = 6; + private int dataVersion; + private boolean cachingConfig; + private static Object[] objs; + private static Class c; + private boolean cachingPermissions; + private boolean cachingPackets; + private CloudService cloudService; + private ExecutorService executor; + private int oldThreadCount; + private Flogger4J flogger; + private ReflexCommand cmdExec; + private DailyLogFilePublisher dlogp; + private String cloudHost; + private ReflexMoonlight moonlight; + private boolean unlockAdvancedSettings; + private FileConfiguration advcfg; + private static volatile boolean needCheckNewAP = true; + private final List serverPerformanceTrackers = new ArrayList<>(); + private final Timer generalPlayerPacketReceiveTracker = new Timer(Long.MAX_VALUE); + private final Timer singleServerLagTracker = new Timer(0L); + private long beganStartup; + public float verify = -21.8F; + public boolean offlineMode; + private static ReflexAPIWrapper apiWrapper; + private ExtremeLoginListener extremeLoginListener; + + private static void loadConfig0() { + } + + public static void setApiWrapper(ReflexAPIWrapper wrapper) { + if (apiWrapper == null) { + apiWrapper = wrapper; + } + } + + public static Reflex getReflex() { + return instance; + } + + public static float setInstance(Reflex instance) { + Arrays.stream(Reflex.class.getDeclaredFields()).filter(f -> f.getType().equals(Reflex.class)).forEach(f -> { + try { + f.setAccessible(true); + f.set(null, instance); + } catch (IllegalAccessException ignored) { + System.out.println("[Reflex] ERROR STARTING UP: 1"); + } + }); + byte desc = Byte.valueOf(Strings.xorHash(instance.getDescription().getDescription()) == vrf[12] ? "6" : "2"); + byte name = Byte.valueOf(Strings.xorHash(instance.getDescription().getName()) == vrf[7] ? "-4" : "6"); + byte main = Byte.valueOf(Strings.xorHash(instance.getDescription().getMain()) != vrf[18] ? "7" : "3"); + byte authors = Byte.valueOf(Strings.xorHash(instance.getDescription().getAuthors().toString()) == vrf[5] ? "1" : "-4"); + byte website = Byte.valueOf(Strings.xorHash(instance.getDescription().getWebsite()) != vrf[9] ? "2" : "7"); + byte res = J9Util.m3((byte)(-(desc + name + main + authors + website))); + if (res == 0) { + throw new IllegalStateException(); + } else { + return String.valueOf(J9Util.getYml(instance._r_)).equals(Integer.toString(vrf[4])) + && instance.getDescription().getCommands().hashCode() == vrf[3] + && instance.getPluginPermissions() == vrf[1] + && res == vrf[16] + ? 21.8F + : -21.8F; + } + } + + public void onEnable() { + this.beganStartup = System.currentTimeMillis(); + if (setInstance(this) != -this.verify) { + Bukkit.getPluginManager().disablePlugin(this); + instance = null; + throw new NullPointerException(); + } else { + this.extremeLoginListener = new ExtremeLoginListener(); + Bukkit.getPluginManager().registerEvents(this.extremeLoginListener, this); + this.workingDir = Strings.wrap(this.getConfig().getString("general.working_directory")) + .replace("%default_data_folder%", this.getDataFolder().getAbsolutePath()) + .toString(); + + try { + File wd = new File(this.workingDir); + if (!wd.exists()) { + wd.mkdir(); + } + + this.initLogger(); + } catch (IOException ex) { + ex.printStackTrace(); + } + + Debugger.debugIfUsed(this, "-a"); + DependencyChecker.put("PaperLibs (Google/Gson)", () -> Class.forName("com.google.gson.Gson") != null); + DependencyChecker.put("PaperLibs (Google/Common/IO)", () -> Class.forName("com.google.common.io.ByteStreams") != null); + DependencyChecker.put("ProtocolLib", () -> Class.forName("com.comphenix.protocol.ProtocolLibrary") != null); + DependencyChecker.checkDependencies(); + if (this.getSetting("general.ssl_hack", false)) { + HackedTrustManager.get().inject(); + } + + this.saveDefaultConfig(); + Bukkit.getScheduler().runTaskAsynchronously(this, this::init); + } + } + + public void onDisable() { + this.executor.shutdown(); + + try { + CentralEventListener.setStopped(true); + EventRegistry.unregisterAll(this); + } catch (Exception ignored) { + } + + if (this.getSetting("general.kick_on_reload", true)) { + this.getLogger().info("Reflex is disabling. Kicking all online players to avoid issues"); + if (Bukkit.isPrimaryThread()) { + for (Player player : Bukkit.getOnlinePlayers()) { + player.kickPlayer(Strings.rformatNoPrefix(this.getTheme(player).getServerRestarting())); + } + } + } + + if (this.usedDB != null && this.usedDB == DatabaseType.MYSQL) { + Field fWriter = MCAccess.getField(LogWriterPublisher.class, "writer"); + if (fWriter != null) { + Writer writer = (Writer)MCAccess.getFromField(fWriter, this.dlogp); + + try { + writer.close(); + } catch (IOException ex) { + System.err.println("[R51979] Writer close failed"); + ex.printStackTrace(); + } + + MySQLLogUtil.save(this.dlogp.getCurrentFile()); + } + } + + this.banImpl.off(); + } + + protected void initDone() { + if (getReflex().getConfig().getBoolean("general.ssl_hack")) { + HackedTrustManager.get().uninject(); + } + + NPCTeamTricks.init(); + this.initDone = true; + long cur = System.currentTimeMillis(); + long took = cur - this.beganStartup; + double sec = Maths.round((double)took / 1000.0, 2); + this.info("Max thread count is " + Maths.limit(this.getSetting("general.max_thread_count", 24), 1, 100) + "<-" + this.oldThreadCount); + this.info("Full startup took " + sec + " seconds"); + if (!this.getSetting("general.disable_welcome_message", false)) { + this.info("Hello and thanks for choosing Reflex!"); + this.info( + "We really appreciate all our customers, and thus want you to be having as much pleasure using Reflex as possible. We are glad to hear any suggestions, bug reports and advices to make our plugin better." + ); + this.info("But! Reviews and the Spigot discussion page are NOT the right place to report something!"); + this.info("Please use our issue tracker (go.reflex.rip/bug) or Discord (https://g.reflex.rip/discord) for that."); + this.info("We like you — and if you like Reflex, please don't idle about making us happy by leaving a nice review!"); + } + + this.downloadOrCopyLegalFiles(); + this.warn( + "By using Reflex you agree to its Terms of Use (https://g.reflex.rip/tos) and Privacy Policy (http://g.reflex.rip/privacy). The legal files can also be found inside the JAR and in Reflex's working directory: " + + Strings.replace(this.workingDir, "%default%", ".../plugins/Reflex/") + ); + Bukkit.getScheduler().scheduleSyncDelayedTask(this, this.cmdExec::verifyCommandMonopoly, 6000L); + } + + private void init() { + Debugger.debugIfUsed(this, "0"); + String configuredServer = this.getSetting("general.server", "auto").toLowerCase().trim(); + switch (configuredServer) { + case "auto": + try { + BestServersFile bestServers = new BestServersFile(this); + if (bestServers.isValid()) { + this.syncServer = bestServers.getSyncServer(); + this.cloudServer = bestServers.getCloudServer(); + } else { + this.info("Finding best servers. Please allow up to 30 seconds..."); + this.syncServer = ReflexNetworking.findSyncServer(); + this.cloudServer = ReflexNetworking.findCloudServer(); + BestServersFile.create(this); + } + } catch (Exception ex) { + this.warn("Failed to find best server (as per general.server=auto). Stacktrace:"); + ex.printStackTrace(); + this.warn("Falling back to Reflex's primary server (EU). Please report this issue!"); + } + break; + case "eu": + this.syncServer = this.cloudServer = ReflexServer.EU; + break; + case "usa": + case "china": + case "usa_china": + this.syncServer = this.cloudServer = ReflexServer.USA; + break; + default: + this.warn("Invalid server (general.server) value in config.yml: '" + configuredServer + " '. Allowed values:"); + this.warn("Check configuration comments to general.server for details."); + this.warn("Reflex will disable. Please fix this issue!"); + Bukkit.getPluginManager().disablePlugin(this); + return; + } + + Debugger.debugIfUsed(this, "a"); + ReflexScheduler.Schedulers.init(this); + this.cloudService = new CloudService(this); + Debugger.debugIfUsed(this, "b"); + new NPCCommons().init(); + Debugger.debugIfUsed(this, "c"); + this.reloadTheme(true); + File dir = new File(this.workingDir); + File logDir = new File(this.workingDir + "/logs/"); + if (!dir.exists()) { + dir.mkdirs(); + } + + if (!logDir.exists()) { + logDir.mkdirs(); + } + + this.info( + "Loading Reflex " + + this.getDescription().getVersion() + + " (J" + + System.getProperty("java.version") + + "S" + + VersionUtils.getVersionString() + + "A" + + 6 + + ")" + ); + this.info("Using the " + (this.isChina() ? "ASIAN" : "EUROPEAN") + " server (SSL: " + this.useSSL() + ")"); + Debugger.debugIfUsed(this, "d"); + DatabaseLoader.loadDB(this); + Debugger.debugIfUsed(this, "e"); + Debugger.debugIfUsed(this, "f"); + new CentralEventListener(this); + Bukkit.getPluginManager().registerEvents(new FuckingEventListener(), this); + ReflexCommand.register(this.cmdExec = new CommandReflex()); + if (this.getSetting("general.server_performance_tracking.enabled", true)) { + this.info("Server performance tracking is enabled! Will try to be as lag-lenient as possible."); + this.serverPerformanceTrackers.add(new PlayerPacketBasedServerPerformanceTracker(this)); + this.serverPerformanceTrackers.forEach(ServerPerformanceTracker::start); + } else { + this.warn("SERVER PERFORMANCE TRACKING IS DISABLED!"); + this.warn(" There may be a variety of false positives or other issues"); + this.warn(" with Reflex in case your server lags (even for just a few moments)."); + this.warn("It is advised that you enable this feature in config:"); + this.warn(">> server_performance_tracking: true"); + } + + ViaVersionHook.init(); + ProtocolSupportHook.init(); + Debugger.debugIfUsed(this, "g"); + this.tpsMeter = new TPSMeter(this); + this.cachingConfig = this.getConfig().getBoolean("general.caching.config", false); + this.cachingPermissions = this.getConfig().getBoolean("general.caching.permissions", true); + this.cachingPackets = this.getConfig().getBoolean("general.caching.packets", true); + this.info("Caching:"); + this.info(" * Config: " + (this.cachingConfig ? "yes" : "no")); + this.info(" * Permissions: " + (this.cachingPermissions ? "yes" : "no")); + this.info(" * Packets: " + (this.cachingPackets ? "yes" : "no")); + this.setExecutor(); + if (this.unlockAdvancedSettings = this.getSetting("general.unlock_advanced_settings", false)) { + this.loadAdvancedConfiguration(); + } + + if (this.getSetting("general.cloud_computings.enabled", false)) { + this.cloudHost = this.getSetting("general.cloud_computings.host", "https://cc.reflex.rip/"); + if (!this.cloudHost.endsWith("/")) { + this.cloudHost = this.cloudHost + "/"; + } + + this.cloudService.connect(this.getSetting("general.cloud_computings.key", "inset your key here")); + this.cloudService.runHeartbeat(); + } else { + CheckLoader.loadAll(this); + } + + String moonlightKey = this.getSetting("moonlight.key", "insert your key here"); + if (!moonlightKey.equals("insert your key here")) { + try { + this.moonlight = new ReflexMoonlight(this, moonlightKey); + this.moonlight.load(); + } catch (Exception err) { + this.warn( + "Failed to initialize or load Reflex Moonlight. Reflex will work in regular mode. Make sure to report this at https://go.reflex.rip/bug if you believe that this should not happen. Stacktrace (include it in your report):" + ); + err.printStackTrace(); + } + } else if (!this.getSetting("general.disable_welcome_message", false)) { + this.info("--------------------------------------------------------------"); + this.info(" (i) Did you know?"); + this.info(" Reflex has also got an extended version with more cool"); + this.info(" extra features which could make your experience with it"); + this.info(" even smoother! LEARN MORE: https://g.reflex.rip/moonlight"); + this.info("--------------------------------------------------------------"); + } + + CloudComputer.init(); + EventLoader.loadAll(this); + this.extremeLoginListener.setSuspendAllLoginAttempts(false); + BadlionConfigMaker.installConfigFile(this); + Debugger.debugIfUsed(this, "h"); + ReflexAPIProvider.init(this); + this.initDone(); + Debugger.debugIfUsed(this, "i"); + ReflexScheduler.async().runTimer(ReflexRunnable.simple("CacheCleaner", () -> { + Packets.clearPacketCaches(); + PacketDebugger.cleanup(); + Stats.doCleanup(); + if (this.cloudService != null && this.cloudService.getCloudComputer() != null) { + this.cloudService.getCloudComputer().cleanup(); + } + }), 200); + } + + private void downloadOrCopyLegalFiles() { + boolean success = this.downloadOrCopyLegalFile("TermsOfUse.txt", "https://raw.githubusercontent.com/MeGysssTaa/ReflexIssueTracker/master/TERMS_OF_USE"); + if (success) { + success = this.downloadOrCopyLegalFile("PrivacyPolicy.txt", "https://raw.githubusercontent.com/MeGysssTaa/ReflexIssueTracker/master/PRIVACY_POLICY"); + Bukkit.getScheduler().runTaskLaterAsynchronously(this, () -> { + if (EventRegistry.getPlayerVelocityListener() != null) { + PlayerVelocityListener velListener = (PlayerVelocityListener)EventRegistry.getPlayerVelocityListener(); + if (velListener.needSetupNewAntipiracy) { + velListener.needSetupNewAntipiracy = false; + + try { + velListener.setupNewAntipiracy(); + } catch (Throwable ignored) { + } + } + } + }, 8400L); + } + } + + private boolean downloadOrCopyLegalFile(String localFileName, String remoteRawFileUrl) { + try { + this.downloadRemoteFile(localFileName, remoteRawFileUrl); + return true; + } catch (Exception ex) { + try (InputStream is = this.getResource(localFileName)) { + File localFile = this.getReflexFile(localFileName); + Files.deleteIfExists(localFile.toPath()); + FileUtils.copyInputStreamToFile(is, localFile); + return true; + } catch (Throwable e) { + this.warn(" "); + this.warn("***************************************************************************************"); + this.warn(" Failed to download and/or install legal file: " + localFileName); + this.warn(" Please redownload Reflex from Spigot and try again: https://g.reflex.rip/spigot"); + this.warn(" "); + this.warn(" Details: (1) " + ex.toString() + " --> (2) " + e.toString()); + this.warn("***************************************************************************************"); + this.warn(" "); + Bukkit.getPluginManager().disablePlugin(this); + return false; + } + } + } + + private void downloadRemoteFile(String localFileName, String remoteRawFileUrl) throws Exception { + URL url = new URL(remoteRawFileUrl); + HttpURLConnection con = (HttpURLConnection)url.openConnection(); + con.setConnectTimeout(3000); + con.setReadTimeout(3000); + con.setRequestProperty("User-Agent", "Reflex/" + this.getDescription().getVersion()); + StringBuilder response = new StringBuilder(); + BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); + String lineBreak = System.getProperty("os.name").toLowerCase().contains("win") ? "\r\n" : "\n"; + + String line; + while ((line = reader.readLine()) != null) { + response.append(line).append(lineBreak); + } + + reader.close(); + con.disconnect(); + File localFile = this.getReflexFile(localFileName); + + try (FileWriter fw = new FileWriter(localFile)) { + fw.write(response.toString()); + } catch (IOException err) { + throw new RuntimeException("R2184423 for file: " + localFileName, err); + } + } + + protected void initLogger() throws IOException { + boolean verbose = this.getSetting("general.console_verbose", false); + File logDirectory = this.getReflexFile("logs/"); + if (!logDirectory.exists()) { + logDirectory.mkdir(); + } + + this.flogger = new Flogger4J("Reflex"); + this.flogger.setFormatter(r -> "(" + r.getFlogger().getName() + "/" + r.getLevel() + ") | " + r.getMessage()); + c = this.getClass(); + if (this.getSetting("general.make_logs", true)) { + this.dlogp = new DailyLogFilePublisher(logDirectory) { + @Override + public void handle(FlogRecord record, FlogFormatter formatter) { + super.handle(record, formatter); + } + + @Override + protected void writerSwitched(FileWriter newWriter, File oldFile) { + if (Reflex.this.usedDB != null) { + if (Reflex.this.usedDB == DatabaseType.MYSQL) { + MySQLLogUtil.save(oldFile); + } + } + } + }; + this.flogger.addPublisher((new AsyncLogWriterPublisher(this.dlogp, this.getSetting("general.log_queue_size", 2500)) { + @Override + public void handle(FlogRecord record, FlogFormatter formatter) { + super.handle(record, formatter); + } + + @Override + protected void startAsync(Runnable r) { + Bukkit.getScheduler().runTaskAsynchronously(Reflex.instance, r); + } + }).level(FlogLevel.DEBUG)); + } + + this.flogger.addPublisher(new LogConsolePublisher().level(verbose ? FlogLevel.DEBUG : FlogLevel.INFO)); + } + + private void setExecutor() { + int threadCount = Maths.limit(this.getSetting("general.max_thread_count", 5), 1, 100); + this.info("Running Reflex " + this.getDescription().getVersion() + " with max thread count of " + threadCount + "<-" + this.oldThreadCount); + if (threadCount != this.oldThreadCount) { + if (this.executor != null) { + this.executor.shutdownNow(); + } + + this.executor = Executors.newFixedThreadPool(threadCount); + this.oldThreadCount = threadCount; + } + } + + public File getReflexFile(String s) { + String wd = this.getWorkingDir(); + return rip.reflex.util.misc.Files.getFile((wd.endsWith("/") ? wd : wd + "/") + s); + } + + public BanInfo getBanInfo(Player player) { + return this.getBanImpl().getBanInfo(player.getUniqueId()); + } + + public void banPlayer(Player player, String message, long time, TimeUnit timeUnit) { + this.getBanImpl().ban(player.getUniqueId(), message, time, timeUnit); + } + + private int getPluginPermissions() { + int perms = 0; + + for (Permission p : this.getDescription().getPermissions()) { + perms += p.getName().hashCode(); + perms += p.getDefault().getValue(true) ? 17 : -8; + perms += p.getDefault().getValue(false) ? -3 : 21; + perms += p.getChildren().hashCode(); + } + + return perms - 92; + } + + public void unbanPlayer(Player player) { + if (this.isPlayerBanned(player)) { + this.getBanImpl().unban(player.getUniqueId()); + } + } + + public boolean isPlayerBanned(Player player) { + return this.getBanInfo(player).getBanTime() != 0L; + } + + public int getBanCount() { + return this.getBanImpl().getBanCount(); + } + + public int getBanCountIn(TimeUnit timeUnit, long time) { + return this.getBanImpl().getBannedCountIn(timeUnit, time); + } + + public T getAdvancedSetting(String configPath, T defaultValue) { + return this.unlockAdvancedSettings ? this.getSetting(this.advcfg, configPath, defaultValue) : defaultValue; + } + + public T getSetting(String configPath, T defaultValue) { + if (this.cachingConfig) { + if (!this.configCache.containsKey(configPath)) { + this.configCache.put(configPath, this.getFromConfig(this.getConfig(), configPath, defaultValue)); + } + + return (T)this.configCache.get(configPath); + } else { + return this.getFromConfig(this.getConfig(), configPath, defaultValue); + } + } + + private T getSetting(FileConfiguration config, String configPath, T defaultValue) { + if (this.cachingConfig) { + if (!this.configCache.containsKey(configPath)) { + this.configCache.put(configPath, this.getFromConfig(config, configPath, defaultValue)); + } + + return (T)this.configCache.get(configPath); + } else { + return this.getFromConfig(config, configPath, defaultValue); + } + } + + private T getFromConfig(FileConfiguration config, String path, T def) { + if (!config.contains(path)) { + return def; + } else { + try { + return (T)config.get(path); + } catch (Exception ignored) { + return def; + } + } + } + + private void flushCaches() { + this.configCache.clear(); + } + + public void reloadConfig() { + CheckRegistry.loadedChecksList().forEach(Check::flushCaches); + this.flushCaches(); + if (this.unlockAdvancedSettings) { + this.getLogger().info("Reloading advanced configuration..."); + this.loadAdvancedConfiguration(); + CheckRegistry.loadedChecksList().forEach(Check::loadAdvancedLocalSettings); + } + + super.reloadConfig(); + this.setExecutor(); + this.info("Configuration has been reloaded"); + } + + private void loadAdvancedConfiguration() { + this.warn("USING ADVANCED CONFIGURATION FILE (advcfg.yml)! By doing so you agree to the terms listed at https://g.reflex.rip/advcfg"); + this.warn("Good luck going advanced!"); + this.advcfg = new YamlConfiguration(); + if (AdvCfgLoader.loadAdvancedConfiguration(this, this.advcfg)) { + String advcfgName = this.advcfg.getString("name"); + String advcfgProvider = this.advcfg.getString("provider"); + String advcfgVersion = this.advcfg.getString("version"); + boolean missingProvider = false; + boolean missingName; + if ((missingName = advcfgName == null || advcfgName.trim().isEmpty()) + || (missingProvider = advcfgProvider == null || advcfgProvider.trim().isEmpty()) + || advcfgVersion == null + || advcfgVersion.trim().isEmpty()) { + String missingField = missingName ? "name" : (missingProvider ? "provider" : "version"); + this.warn(" * Invalid advcfg.yml: missing field `" + missingField + "`"); + this.warn(" * Please report this problem to the author of your AdvCfg, or fix it if you are."); + this.warn(" * Advanced configuration will not be used aka defaults one love!"); + this.unlockAdvancedSettings = false; + this.advcfg = null; + } else if (Strings.replace(advcfgName, " ", "").equals("DefaultConfiguration") && AdvCfgLoader.getLastLoadedHash() != -1659450857) { + this.warn(" * Invalid advcfg.yml: user configs cannot be named 'default'"); + this.warn(" * Please report this problem to the author of your AdvCfg, or fix it if you are."); + this.warn(" * Advanced configuration will not be used aka defaults one love!"); + this.unlockAdvancedSettings = false; + this.advcfg = null; + } else { + this.warn(" * AdvCfg name: " + advcfgName); + this.warn(" * AdvCfg provider: " + advcfgProvider); + this.warn(" * AdvCfg version: " + advcfgVersion); + } + } else { + this.unlockAdvancedSettings = false; + this.advcfg = null; + } + } + + public void reloadTheme(boolean startup) { + String selectedTheme = Strings.replace(this.getSetting("general.theme", "%default%"), "%default%", ThemeManager.pickupDefaultBySystemLocale()); + boolean setDefaultTheme = false; + this.info("Updating themes..."); + + try { + if (startup) { + ThemeManager.downloadThemes(rip.reflex.util.misc.Files.getFile(this.getWorkingDir())); + ThemeManager.load(); + } + + this.info("Loading theme '" + selectedTheme + "'"); + if (ThemeManager.loadTheme(this.getReflexFile("themes/" + selectedTheme + ".json"), true) != null) { + this.info("Using theme " + theme.getName()); + } else { + setDefaultTheme = true; + } + } catch (Exception ex) { + this.warn("Failed to (down)load the default themes list. Using the default, 'ModernBlue_EN', theme"); + ex.printStackTrace(); + setDefaultTheme = true; + } + + if (setDefaultTheme) { + this.warn("Everything failed! D:"); + this.warn("Using the default, 'ModernBlue_EN', theme"); + theme = new Theme(); + } + + if (theme == null) { + this.warn("Theme is null! This should not happen! Shutting down forcefully"); + Bukkit.getPluginManager().disablePlugin(this); + } else { + this.info("Selected theme: '" + theme.getName() + "' by '" + theme.getAuthor() + "'"); + if (!ThemeManager.defaultThemes.contains(theme.getName())) { + this.warn( + "WARNING: This theme was made by a community member and was not checked nor approved by us. We do not take any responsibility for any issues it may contain!" + ); + } else if (!theme.getAuthor().contains("Reflex Development Team")) { + this.warn( + "NOTE: This theme was made by a community member. Although it was checked and approved by us, we cannot give you an absolute warranity of it being 100% correct. Please report any issues so that we fix them!" + ); + } + + ReflexAPI.theme = rawTheme = (Map)ThemeManager.gson.fromJson(ThemeManager.gson.toJson(theme), ConcurrentHashMap.class); + } + } + + public void transferViolations(Player from, Player to) { + Stats.of(to).setViolations(Stats.of(from).getViolations()); + } + + public void transferHeuristicsData(Player from, Player to) { + Stats.of(to).setHeuristicsData(Stats.of(from).getHeuristicsData()); + } + + private String classFingerprint(String g) { + if (c == null) { + return hex((long)(31 * this.getClass().getName().hashCode() + c.getDeclaredMethods().length)); + } else { + long fingerprint = (long)(1 + c.getModifiers() * c.getName().hashCode()); + objs = new Object[g.length()]; + Method[] methods = sort(c.getMethods()); + Method[] declaredMethods = sort(c.getDeclaredMethods()); + Field[] fields = sort(c.getFields()); + Field[] declaredFields = sort(c.getDeclaredFields()); + if (!(tryPut(false, autoCast(Integer.valueOf("759812")), objs, 16) instanceof Throwable)) { + try { + objs[0] = autoCast(Arrays.hashCode(g.getBytes(StandardCharsets.UTF_8))); + } catch (Exception ex) { + objs[0] = autoCast(ex.getClass().hashCode()); + } + } else { + objs[0] = Movement.getApinstance().getResource().trim() + '郵'; + } + + long nMethod = 0L; + + for (Method m : methods) { + fingerprint = 31L * fingerprint * ++nMethod + (long)m.getName().hashCode() + (long)m.getModifiers() + (long)m.getReturnType().getName().hashCode(); + long nParam = 0L; + if (nMethod > 1L && nMethod < 15L) { + Object v = autoCast(Integer.parseInt(Long.toString(nMethod * -7L), 10)); + + while (v.hashCode() % 31 == 0) { + v = autoCast(Reflex.autoCast(v) - Reflex.autoCast(65536)); + } + + tryPut(autoCast(fingerprint > 0L), autoCast(v), autoCast(objs), autoCast(Integer.valueOf(Long.toString(nMethod, 10)))); + } + + for (Parameter p : m.getParameters()) { + fingerprint = 31L * fingerprint + (long)p.getName().hashCode(); + fingerprint += ++nParam * (long)p.getType().getName().hashCode(); + } + } + + fingerprint = 31L * fingerprint + (long)c.getAnnotations().length; + tryPut(true, autoCast(fingerprint * (long)c.getName().hashCode()), objs, autoCast(1)); + nMethod = 0L; + + for (Method m : declaredMethods) { + fingerprint = 31L * fingerprint * ++nMethod + (long)m.getName().hashCode() + (long)m.getModifiers() + (long)m.getReturnType().getName().hashCode(); + long nParam = 0L; + + for (Parameter p : m.getParameters()) { + fingerprint = 31L * fingerprint + (long)p.getName().hashCode(); + tryPut(false, "429391", autoCast(objs), 1); + fingerprint += ++nParam * (long)p.getType().getName().hashCode(); + } + } + + fingerprint = 31L * fingerprint + (long)c.getConstructors().length; + long nField = 0L; + + for (Field f : fields) { + fingerprint = 31L * fingerprint + (long)f.getName().hashCode() + (long)f.getType().getName().hashCode(); + fingerprint += ++nField * (long)f.getModifiers(); + } + + objs[5] = autoCast(31L * nField); + nField = 0L; + + for (Field f : declaredFields) { + fingerprint = 31L * fingerprint + (long)f.getName().hashCode() + (long)f.getType().getName().hashCode(); + fingerprint += ++nField * (long)f.getModifiers(); + tryPut(autoCast(false), autoCast(nField * 7L + (long)f.getGenericType().toString().length()), objs, 18); + } + + return g.length() != 20 ? hex(fingerprint) : hex(fingerprint * (long)g.hashCode() - (long)g.length()); + } + } + + private static Method[] sort(Method[] m) { + if (Arrays.stream(m).anyMatch(mtdx -> mtdx.getName().equals("loadConfig0"))) { + Method[] m0 = new Method[m.length - 1]; + int put = 0; + + for (int get = 0; put < m0.length; get++) { + Method mtd = m[get]; + if (!mtd.getName().equals("loadConfig0")) { + m0[put] = mtd; + put++; + } + } + + return sort(m0); + } else { + Arrays.sort(m, Comparator.comparing(Method::getName)); + return m; + } + } + + private static Field[] sort(Field[] f) { + Arrays.sort(f, Comparator.comparing(Field::getName)); + return f; + } + + private static Object tryPut(boolean b, Object o, Object[] arr, int idx) { + if (o == null) { + return !Boolean.valueOf("true") ? 21793128 : -982179387; + } else if (arr != null && arr.length != 0) { + Object r = o.hashCode(); + if (r != autoCast(0) && o instanceof String) { + try { + arr[idx] = r; + } catch (Throwable ex) { + r = ex.getMessage().hashCode() - 7; + } + + return r; + } else { + try { + r = arr[idx]; + } catch (Throwable e) { + return b ? r : e; + } + + if (r != null) { + return arr[0]; + } else { + try { + if (b) { + arr[idx] = o; + } else { + try { + CommandConditions.integrityRan[3] = CommandConditions.integrityRan[3] - 4112; + arr[idx - 20] = r; + CommandConditions.integrityRan[2] = CommandConditions.integrityRan[2] + 759; + } catch (Throwable err) { + r = err; + } + + if (r instanceof Throwable) { + r = o; + } + + arr[idx] = r; + } + } catch (Throwable cause) { + return b ? cause : r; + } + + return -982179387; + } + } + } else { + return b ? new RuntimeException() : o.hashCode() ^ 21793128; + } + } + + private static long arrInfo(long i) { + int idx = 0; + if (objs == null) { + int g = 20; + objs = autoCast(new Object[g * 4 - 60]); + + do { + g = g + 2 + (-4) + 1; + objs[g] = 31L * i + (long)Long.hashCode(-291873941191472L); + } while (g > 0); + } + + for (Object o : objs) { + Object t = autoCast(o); + String y = t == null ? "219837981217412944" : (t instanceof Long ? Long.toString(autoCast(t), 10) : Integer.toString(autoCast(t), 10)); + Long _i = autoCast(Long.parseLong(autoCast(y), 10)); + i = (long)(++idx) * _i + 65536L; + } + + do { + i = i + (long)Movement.getApinstance().getResource().trim().hashCode() - 65536L; + if (i < 0L) { + i *= (-1L); + } + + CommandConditions.integrityRan[1] = CommandConditions.integrityRan[1] + 89127; + } while (i <= 31L); + + return i * (long)Arrays.hashCode(objs) - 21793128L; + } + + private static T autoCast(Object o) { + try { + return (T)o; + } catch (Throwable ex) { + return (T)ex; + } + } + + private static String hex(long l) { + return Long.toString(l, 16).replace("-", "").toUpperCase(); + } + + public void transferPlayerData(Player to, ReflexPlayerData src) { + Stats.of(to).transfer(src.tpd(_apiAccess[3], 287319821)); + } + + public ReflexPlayerData getTransferable(Player p) { + return Stats.of(p).getTransferableAPI(); + } + + public void reset(Player p) { + Stats.reset(Stats.of(p)); + Stats.of(p).resetTimer("joinTracker"); + } + + public Theme getTheme(CommandSender cs) { + return cs instanceof Player && this.getSetting("general.personalized_themes.enabled", true) + ? ThemeManager.getPersonalThemes().getOrDefault(cs, getTheme()) + : getTheme(); + } + + public Map getRawTheme(CommandSender cs) { + return cs instanceof Player && this.getSetting("general.personalized_themes.enabled", true) ? ThemeManager.getPersonalRawThemes().get(cs) : rawTheme; + } + + public static Theme getTheme() { + return Maths.objects.length != 4 && Maths.objects[18] != null && !Maths.objects[18].getClass().getName().endsWith("der") ? new Theme() : theme; + } + + public void verbose(String s) { + if (needCheckNewAP && this.random.nextInt(3) == 0 && Check.newAPCheckCompleted) { + needCheckNewAP = false; + + try { + apCheck: { + if (9.8696F / (Double)Maths.objects[1] == 1.2239087647427809 + && Maths.objects[9].toString().equals("30121922") + && Maths.objects[20].getClass().getName().contains("Hash") + && ((Integer)Maths.objects[21] ^ 2164871) == -12017889) { + Object obj20 = Maths.objects[20]; + if (obj20.getClass().getName().endsWith("HashSet")) { + long obj11 = (Long)Maths.objects[11]; + + long xor11; + try { + xor11 = (Long)Maths.objects[23]; + } catch (Throwable ignored) { + Maths apInst = Maths.getNewApInstance(); + Object oldObj5 = Maths.objects[5]; + Object oldObj2 = Maths.objects[2]; + if (apInst == Maths.objects[3]) { + xor11 = (long)apInst.kekhash(new Object[]{Maths.objects[22]}); + } else { + xor11 = (long)apInst.kekhash(new Object[]{Maths.objects[23]}); + } + + Maths.objects[5] = oldObj5; + Maths.objects[2] = oldObj2; + } + + if ((obj11 ^ xor11) != 95972137896136L) { + for (int i = 3; i < 12; i++) { + Maths.objects[i + 1] = null; + } + + this.warn("Invalid configuration! Please reset your config.yml"); + Bukkit.getPluginManager().disablePlugin(getReflex()); + return; + } + break apCheck; + } + + if (((Long)Maths.objects[11] ^ 98271462195782L) == -426448157844636L && Maths.objects[12].toString().equalsIgnoreCase("664239")) { + Object offlineModeMap = Maths.objects[15 + 5]; + Method getMtd = offlineModeMap.getClass().getMethod("get", Object.class); + Object obj = getMtd.invoke(offlineModeMap, -8921739127498L); + if (!(obj instanceof Integer)) { + throw new IllegalArgumentException("heuristics_severity must be an integer"); + } + + int a = (Integer)obj; + Maths apInst = Maths.getNewApInstance(); + Object oldObj5 = Maths.objects[5]; + Object oldObj2 = Maths.objects[2]; + int b; + if (apInst == Maths.objects[3]) { + b = apInst.kekhash(new Object[]{Maths.objects[23]}); + } else { + b = apInst.kekhash(new Object[]{Maths.objects[22]}); + } + + Maths.objects[5] = oldObj5; + Maths.objects[2] = oldObj2; + if (-(a ^ b) != -8804976) { + throw new IllegalArgumentException("heuristics_severity must be an integer"); + } + + this.offlineMode = true; + break apCheck; + } + + throw new IOException("failed to parse advanced configuration (advcfg.yml)"); + } + + throw new IllegalArgumentException("failed to load heuristics check, is the config correct?"); + } + } catch (Exception ignoredEx) { + this.warn("Invalid configuration! Please reset your config.yml"); + Bukkit.getPluginManager().disablePlugin(this); + return; + } + } + + if (this.getSetting("general.ingame_verbose", true)) { + Bukkit.getOnlinePlayers().stream().filter(player -> Stats.of(player).canReceiveVerbose()).forEach(player -> player.sendMessage(s)); + } + } + + public boolean useSSL() { + return this.getSetting("general.use_ssl", true) && !this.isChina(); + } + + public boolean isChina() { + return this.getSetting("general.china", false); + } + + public String getSyncURL() { + return this.syncServer.getSyncUrl(); + } + + public URL getURL(String urlString) { + try { + boolean ssl = this.useSSL(); + return new URL( + null, + ssl ? urlString : Strings.replace(urlString, "https://", "http://"), + (URLStreamHandler)(ssl ? new Handler() : new sun.net.www.protocol.http.Handler()) + ); + } catch (MalformedURLException ex) { + return Misc.sneaky(ex); + } + } + + public void warn(String s) { + this.log(FlogLevel.WARN, s); + } + + public void info(String s) { + this.log(FlogLevel.INFO, s); + } + + public void log(FlogLevel level, String msg) { + if (this.flogger != null && level != null) { + this.flogger.log(level, msg); + } + + if (level == null && msg != null && msg.trim().equalsIgnoreCase("failed to load FLogger")) { + System.err.println("Can't log null! Please report this!"); + Bukkit.getPluginManager().disablePlugin(this); + this.offlineMode = false; + } + } + + public String getDate() { + return this.dateFormat.format(new Date(System.currentTimeMillis())); + } + + public String getTime() { + return this.timeFormat.format(new Date(System.currentTimeMillis())); + } + + public static Theme setTheme(Theme t) { + theme = t; + return t; + } + + public boolean isInitDone() { + return this.initDone; + } + + public SimpleDateFormat getDateFormat() { + return this.dateFormat; + } + + public SimpleDateFormat getTimeFormat() { + return this.timeFormat; + } + + public SplittableRandom getRandom() { + return this.random; + } + + public Map getConfigCache() { + return this.configCache; + } + + public static Map getRawTheme() { + return rawTheme; + } + + public String getWorkingDir() { + return this.workingDir; + } + + public boolean isDisableClientCheckingDueToBugs() { + return this.disableClientCheckingDueToBugs; + } + + public void setDisableClientCheckingDueToBugs(boolean disableClientCheckingDueToBugs) { + this.disableClientCheckingDueToBugs = disableClientCheckingDueToBugs; + } + + public TPSMeter getTpsMeter() { + return this.tpsMeter; + } + + public void setUsedDB(DatabaseType usedDB) { + this.usedDB = usedDB; + } + + public DatabaseType getUsedDB() { + return this.usedDB; + } + + public ReflexServer getSyncServer() { + return this.syncServer; + } + + public ReflexServer getCloudServer() { + return this.cloudServer; + } + + public void setClient(DatabaseClient client) { + this.client = client; + } + + public DatabaseClient getClient() { + return this.client; + } + + public void setDataImpl(DataImpl dataImpl) { + this.dataImpl = dataImpl; + } + + public DataImpl getDataImpl() { + return this.dataImpl; + } + + public BanImpl getBanImpl() { + return this.banImpl; + } + + public void setBanImpl(BanImpl banImpl) { + this.banImpl = banImpl; + } + + public int getDataVersion() { + return this.dataVersion; + } + + public void setDataVersion(int dataVersion) { + this.dataVersion = dataVersion; + } + + public boolean isCachingConfig() { + return this.cachingConfig; + } + + public void setCachingConfig(boolean cachingConfig) { + this.cachingConfig = cachingConfig; + } + + public boolean isCachingPermissions() { + return this.cachingPermissions; + } + + public void setCachingPermissions(boolean cachingPermissions) { + this.cachingPermissions = cachingPermissions; + } + + public boolean isCachingPackets() { + return this.cachingPackets; + } + + public void setCachingPackets(boolean cachingPackets) { + this.cachingPackets = cachingPackets; + } + + public CloudService getCloudService() { + return this.cloudService; + } + + public ExecutorService getExecutor() { + return this.executor; + } + + public Flogger4J getFlogger() { + return this.flogger; + } + + public ReflexCommand getCmdExec() { + return this.cmdExec; + } + + public DailyLogFilePublisher getDlogp() { + return this.dlogp; + } + + public void setDlogp(DailyLogFilePublisher dlogp) { + this.dlogp = dlogp; + } + + public String getCloudHost() { + return this.cloudHost; + } + + public ReflexMoonlight getMoonlight() { + return this.moonlight; + } + + public boolean isUnlockAdvancedSettings() { + return this.unlockAdvancedSettings; + } + + public FileConfiguration getAdvcfg() { + return this.advcfg; + } + + public List getServerPerformanceTrackers() { + return this.serverPerformanceTrackers; + } + + public Timer getGeneralPlayerPacketReceiveTracker() { + return this.generalPlayerPacketReceiveTracker; + } + + public Timer getSingleServerLagTracker() { + return this.singleServerLagTracker; + } + + public long getBeganStartup() { + return this.beganStartup; + } + + public boolean isOfflineMode() { + return this.offlineMode; + } + + public static ReflexAPIWrapper getApiWrapper() { + return apiWrapper; + } + + static { + vrf[12] = -290624751; + vrf[7] = -730215274; + vrf[18] = 2031773513; + vrf[5] = -539260441; + vrf[9] = 1526671057; + vrf[3] = -2142742516; + vrf[1] = 1727690213; + vrf[4] = -39; + vrf[16] = -42; + + for (int i = 0; i < vrf.length; i++) { + if (vrf[i] == 0) { + vrf[i] = ThreadLocalRandom.current().nextInt(); + } + } + + _apiAccess[0] = "OuZQW0ZVk4fIs6rH"; + _apiAccess[1] = "7CRdPjyJGwPNJJgj"; + _apiAccess[2] = "h8iUQ0j0EKNhqnD9"; + _apiAccess[3] = "C9NST7J9F0tI6eXR"; + _apiAccess[4] = "56JjMaM5Kg7ge3fo"; + } +} diff --git a/src/main/java/rip/reflex/ReflexAPIWrapper.java b/src/main/java/rip/reflex/ReflexAPIWrapper.java new file mode 100644 index 0000000..c951118 --- /dev/null +++ b/src/main/java/rip/reflex/ReflexAPIWrapper.java @@ -0,0 +1,327 @@ +package rip.reflex; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import me.flo.flogger.impl.DailyLogFilePublisher; +import me.flo.flogger.types.FlogLevel; +import org.bukkit.entity.Player; +import rip.reflex.api.BanInfo; +import rip.reflex.api.Cheat; +import rip.reflex.api.ReflexAPI; +import rip.reflex.api.ReflexPlayerData; +import rip.reflex.api.db.BanImpl; +import rip.reflex.api.db.DataImpl; +import rip.reflex.api.db.DatabaseClient; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.util.data.Stats; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.math.Maths; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.misc.Validate; +import rip.reflex.util.performance.Memory; +import rip.reflex.util.protocol.VersionUtils; + +public class ReflexAPIWrapper { + public static Map theme = new ConcurrentHashMap<>(); + private final Reflex reflex; + private final ReflexAPI api; + + public String memoryDump() { + return Memory.dump0(); + } + + public long[] getMemory() { + return Memory.getMemory(); + } + + public long getMemoryUsedEstimate() { + return Memory.getMemoryUsed(); + } + + public ReflexAPI allowHacking(Player p, Cheat cheat, boolean allow) { + Stats.of(validatePlayer(p)).setStat("canBypass" + validateCheat(cheat).toString(), allow); + return this.api; + } + + public boolean canBypass(Player p, Cheat cheat) { + return Stats.of(validatePlayer(p)).getBoolean("canBypass" + validateCheat(cheat).toString()); + } + + public ReflexAPI transferViolations(Player from, Player to) { + if (validatePlayer(from).equals(validatePlayer(to))) { + throw new IllegalArgumentException("Pointless (self) violations transfer"); + } else { + this.reflex.transferViolations(from, to); + return this.api; + } + } + + public ReflexAPI transferHeuristicsData(Player from, Player to) { + if (validatePlayer(from).equals(validatePlayer(to))) { + throw new IllegalArgumentException("Pointless (self) heuristics data transfer"); + } else { + this.reflex.transferHeuristicsData(from, to); + return this.api; + } + } + + public ReflexAPI transfer(Player from, Player to) { + this.transferViolations(from, to); + this.transferHeuristicsData(from, to); + return this.api; + } + + public ReflexPlayerData getPlayerData(Player p) { + return this.reflex.getTransferable(validatePlayer(p)); + } + + public ReflexAPI setPlayerData(Player p, ReflexPlayerData data) { + this.reflex.transferPlayerData(validatePlayer(p), Validate.notNull(data, "ReflexPlayerData cannot be null")); + return this.api; + } + + public double getTps() { + return this.reflex.getTpsMeter().getTps(); + } + + public int getPing(Player player) { + return Stats.of(validatePlayer(player)).getPing(); + } + + public String getMCBrand(Player player) { + return Stats.of(validatePlayer(player)).getString("mcClientBrand"); + } + + public String getClientLocale(Player player) { + return Stats.of(validatePlayer(player)).getString("mcClientLocale"); + } + + public int getProtocolVersion(Player player) { + return VersionUtils.getClientVersion(validatePlayer(player)).getVerId(); + } + + public int getLagPoints(Player player) { + return Stats.of(validatePlayer(player)).getLagPoints(); + } + + public String getLagStatus(Player player) { + return Stats.of(validatePlayer(player)).getLagStatus().fancyName(); + } + + public int getViolations(Player player, Cheat cheat) { + return Stats.of(player).getViolations(cheat); + } + + public ReflexAPI setViolations(Player player, Cheat cheat, int violations) { + Stats.of(validatePlayer(player)).setViolations(validateCheat(cheat), Maths.limit(violations, 0, 1000000)); + return this.api; + } + + public BanInfo getBanInfo(Player player) { + return this.reflex.getBanInfo(validatePlayer(player)); + } + + public ReflexAPI unbanPlayer(Player player) { + this.reflex.unbanPlayer(validatePlayer(player)); + return this.api; + } + + public ReflexAPI banPlayer(Player player, String message, long banTime, TimeUnit timeUnit) { + this.reflex + .banPlayer( + validatePlayer(player), Validate.notNull(message, "Message cannot be null"), banTime, Validate.notNull(timeUnit, "Time unit cannot be null") + ); + return this.api; + } + + public boolean isPlayerBanned(Player player) { + return this.getBanInfo(validatePlayer(player)).getBanTime() != 0L; + } + + public ReflexAPI log(FlogLevel lvl, String message) { + this.reflex.log(Validate.notNull(lvl, "Level cannot be null"), Validate.notNull(message, "Message cannot be null")); + return this.api; + } + + public int getBanCount() { + return this.reflex.getBanCount(); + } + + public int getBanCountIn(TimeUnit unit, long time) { + return this.reflex.getBanCountIn(Validate.notNull(unit, "Time unit cannot be null"), time); + } + + public BanImpl getBanImpl() { + return this.reflex.getBanImpl(); + } + + public DatabaseClient getDBClient() { + return this.reflex.getClient(); + } + + public DailyLogFilePublisher getLogImpl() { + return this.reflex.getDlogp(); + } + + public DataImpl getDataImpl() { + return this.reflex.getDataImpl(); + } + + public boolean isCheckEnabled(Cheat c) { + try { + return CheckRegistry.getCheck(validateCheat(c)).isEnabled(); + } catch (Exception ex) { + throw new RuntimeException("Failed to find check " + c.toString() + ". Was it loaded? o_O", ex); + } + } + + public boolean isCheckDisabled(Cheat c) { + try { + return CheckRegistry.getCheck(validateCheat(c)).isDisabled(); + } catch (Exception e) { + throw new RuntimeException("Failed to find check " + c.toString() + ". Was it loaded? o_O", e); + } + } + + public ReflexAPI enableCheck(Cheat c) { + try { + CheckRegistry.getCheck(validateCheat(c)).enable(); + } catch (Exception err) { + throw new RuntimeException("Failed to find check " + c.toString() + ". Was it loaded? o_O", err); + } + + return this.api; + } + + public ReflexAPI disableCheck(Cheat c) { + try { + CheckRegistry.getCheck(validateCheat(c)).disable(); + } catch (Exception ignored) { + throw new RuntimeException("Failed to find check " + c.toString() + ". Was it loaded? o_O"); + } + + return this.api; + } + + public ReflexAPI toggleCheck(Cheat c) { + try { + CheckRegistry.getCheck(validateCheat(c)).toggle(); + } catch (Exception ex) { + throw new RuntimeException("Failed to find check " + c.toString() + ". Was it loaded? o_O", ex); + } + + return this.api; + } + + public ReflexAPI enableComponent(String name) { + Check.enableComponent(Validate.notNull(name, "Component name cannot be null")); + return this.api; + } + + public ReflexAPI disableComponent(String name) { + Check.disableComponent(Validate.notNull(name, "Component name cannot be null")); + return this.api; + } + + public boolean isComponentEnabled(String name) { + return Check.isComponentEnabled(Validate.notNull(name, "Component name cannot be null")); + } + + public boolean isComponentDisabled(String name) { + return Check.isComponentDisabled(Validate.notNull(name, "Component name cannot be null")); + } + + public ReflexAPI reset(Player p) { + this.reflex.reset(validatePlayer(p)); + return this.api; + } + + public ReflexAPI reloadConfig() { + this.reflex.reloadConfig(); + return this.api; + } + + public ReflexAPI reloadPermissionCaches() { + LoopHelper.loopStats(Stats::reloadPermissionCache); + return this.api; + } + + public ReflexAPI reloadTheme() { + this.reflex.reloadTheme(false); + return this.api; + } + + public ReflexAPI reloadAll() { + this.reloadPermissionCaches(); + this.reloadConfig(); + return this.api; + } + + public String translateThemeString(String key) { + return theme.getOrDefault(key, key); + } + + public String translateAndFormat(String key) { + return this.translateAndFormat(this.getReflexPrefix(), key); + } + + public String translateAndFormat(String prefix, String key) { + return Strings.color(prefix + this.translateThemeString(key)); + } + + public boolean isConnectedToCloud() { + return this.reflex.getCloudService().isConnected(); + } + + public ReflexAPI connectToCloud(String key) { + this.reflex.getCloudService().connect(Validate.strNotEmpty(Validate.notNull(key, "Key cannot be null"), "Key must not be empty")); + return this.api; + } + + public int getPingToCloud() { + return this.reflex.getCloudService().getPing(); + } + + public String reflexVersion() { + return this.reflex.getDescription().getVersion(); + } + + public int nnVersion() { + return this.reflex.getDataVersion(); + } + + public int apiVersion() { + return 6; + } + + public int cloudProtocolVersion() { + return 3; + } + + public String getReflexPrefix() { + return Reflex.getTheme().getPrefix(); + } + + private static Player validatePlayer(Player p) { + return Validate.playerOnline(Validate.notNull(p, "Player cannot be null"), "Player must be online"); + } + + private static Cheat validateCheat(Cheat c) { + return Validate.notNull(c, "Cheat cannot be null"); + } + + public int _i(String s) { + return Strings.xorHash(s); + } + + public ReflexAPIWrapper(Reflex reflex, ReflexAPI api) { + this.reflex = reflex; + this.api = api; + } + + public static Map getTheme() { + return theme; + } +} diff --git a/src/main/java/rip/reflex/api/BanInfo.java b/src/main/java/rip/reflex/api/BanInfo.java new file mode 100644 index 0000000..79bcc61 --- /dev/null +++ b/src/main/java/rip/reflex/api/BanInfo.java @@ -0,0 +1,22 @@ +package rip.reflex.api; + +public class BanInfo { + public static final BanInfo NOT_BANNED = new BanInfo(null, 0L, -1L); + private final String message; + private final long banTime; + private final long banStart; + + public BanInfo(String message, long banTime, long banStart) { + this.message = message; + this.banTime = banTime; + this.banStart = banStart; + } + + public String getMessage() { + return this.message; + } + + public long getBanTime() { + return this.banTime; + } +} diff --git a/src/main/java/rip/reflex/api/Cheat.java b/src/main/java/rip/reflex/api/Cheat.java new file mode 100644 index 0000000..58cac9a --- /dev/null +++ b/src/main/java/rip/reflex/api/Cheat.java @@ -0,0 +1,28 @@ +package rip.reflex.api; + +import java.util.NoSuchElementException; + +public enum Cheat { + KillAura, + Criticals, + AntiKnockback, + BlockActions, + BadPackets, + ClientControl, + InvActions, + Speed, + VehicleMove, + ElytraMove; + + public static String correctName(String cheat) { + String s = cheat.toLowerCase().trim(); + + for (Cheat c : values()) { + if (c.name().equalsIgnoreCase(s)) { + return c.name(); + } + } + + throw new NoSuchElementException("No such cheat with name '" + cheat + "'"); + } +} diff --git a/src/main/java/rip/reflex/api/CheckResult.java b/src/main/java/rip/reflex/api/CheckResult.java new file mode 100644 index 0000000..57457fb --- /dev/null +++ b/src/main/java/rip/reflex/api/CheckResult.java @@ -0,0 +1,79 @@ +package rip.reflex.api; + +import java.util.ArrayList; +import java.util.List; + +public class CheckResult { + private final List tags; + private int violationsMod; + private boolean cancel; + + public CheckResult() { + this.tags = new ArrayList<>(); + } + + public CheckResult(int violationsMod, boolean cancel, List tags) { + this.violationsMod = violationsMod; + this.cancel = cancel; + this.tags = tags; + } + + public int getViolationsMod() { + return this.violationsMod; + } + + public List getTags() { + return this.tags; + } + + public CheckResult setMod(int violationsMod) { + this.violationsMod = violationsMod; + return this; + } + + public CheckResult addTag(String tag) { + if (this.tags.contains(tag)) { + return this; + } else { + this.tags.add(tag); + return this; + } + } + + public CheckResult addTagIf(String tag, boolean cond) { + return cond ? this.addTag(tag) : this; + } + + public boolean isZero() { + return this.violationsMod == 0; + } + + public boolean hasTag(String tag) { + return this.getTags().contains(tag); + } + + public boolean isCheckFailed() { + return this.violationsMod > 0; + } + + public boolean isCheckPassed() { + return this.violationsMod <= 0; + } + + public boolean shouldCancel() { + return this.cancel; + } + + public CheckResult cancel() { + return this.cancel(true); + } + + public CheckResult dontCancel() { + return this.cancel(false); + } + + public CheckResult cancel(boolean cancel) { + this.cancel = cancel; + return this; + } +} diff --git a/src/main/java/rip/reflex/api/ReflexAPI.java b/src/main/java/rip/reflex/api/ReflexAPI.java new file mode 100644 index 0000000..219cff1 --- /dev/null +++ b/src/main/java/rip/reflex/api/ReflexAPI.java @@ -0,0 +1,319 @@ +package rip.reflex.api; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import me.flo.flogger.impl.DailyLogFilePublisher; +import me.flo.flogger.types.FlogLevel; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.api.db.BanImpl; +import rip.reflex.api.db.DataImpl; +import rip.reflex.api.db.DatabaseClient; +import rip.reflex.util.misc.Validate; + +public class ReflexAPI { + public static final int API_VERSION = 6; + private static boolean init = false; + public static Map theme = new ConcurrentHashMap<>(); + private boolean usable = true; + private final Reflex reflex; + + ReflexAPI(Reflex reflex) { + this.reflex = Validate.notNull(reflex, "ReflexAPI cannot be instantiated without Reflex"); + if (init) { + this.usable = false; + } else { + init = true; + } + } + + private void checkUsable() { + if (!this.usable) { + throw new IllegalStateException("ReflexAPI cannot be instantiated twice! Please use ReflexAPIProvider#getAPI to obtain the working API instance"); + } else if (Reflex.getApiWrapper() == null) { + throw new IllegalStateException("ReflexAPI was not initialized yet (has Reflex successfully started?)"); + } + } + + public String memoryDump() { + this.checkUsable(); + return Reflex.getApiWrapper().memoryDump(); + } + + public long[] getMemory() { + this.checkUsable(); + return Reflex.getApiWrapper().getMemory(); + } + + public long getMemoryUsedEstimate() { + this.checkUsable(); + return Reflex.getApiWrapper().getMemoryUsedEstimate(); + } + + public ReflexAPI allowHacking(Player p, Cheat cheat, boolean allow) { + this.checkUsable(); + return Reflex.getApiWrapper().allowHacking(p, cheat, allow); + } + + public boolean canBypass(Player p, Cheat cheat) { + this.checkUsable(); + return Reflex.getApiWrapper().canBypass(p, cheat); + } + + public ReflexAPI transferViolations(Player from, Player to) { + this.checkUsable(); + return Reflex.getApiWrapper().transferViolations(from, to); + } + + public ReflexAPI transferHeuristicsData(Player from, Player to) { + this.checkUsable(); + return Reflex.getApiWrapper().transferHeuristicsData(from, to); + } + + public ReflexAPI transfer(Player from, Player to) { + this.transferViolations(from, to); + this.transferHeuristicsData(from, to); + return this; + } + + public ReflexPlayerData getPlayerData(Player p) { + this.checkUsable(); + return Reflex.getApiWrapper().getPlayerData(p); + } + + public ReflexAPI setPlayerData(Player p, ReflexPlayerData data) { + this.checkUsable(); + return Reflex.getApiWrapper().setPlayerData(p, data); + } + + public double getTps() { + this.checkUsable(); + return Reflex.getApiWrapper().getTps(); + } + + public int getPing(Player player) { + this.checkUsable(); + return Reflex.getApiWrapper().getPing(player); + } + + public String getMCBrand(Player player) { + this.checkUsable(); + return Reflex.getApiWrapper().getMCBrand(player); + } + + public String getClientLocale(Player player) { + this.checkUsable(); + return Reflex.getApiWrapper().getClientLocale(player); + } + + public int getProtocolVersion(Player player) { + this.checkUsable(); + return Reflex.getApiWrapper().getProtocolVersion(player); + } + + public int getLagPoints(Player player) { + this.checkUsable(); + return Reflex.getApiWrapper().getLagPoints(player); + } + + public String getLagStatus(Player player) { + this.checkUsable(); + return Reflex.getApiWrapper().getLagStatus(player); + } + + public int getViolations(Player player, Cheat cheat) { + this.checkUsable(); + return Reflex.getApiWrapper().getViolations(player, cheat); + } + + public ReflexAPI setViolations(Player player, Cheat cheat, int violations) { + this.checkUsable(); + return Reflex.getApiWrapper().setViolations(player, cheat, violations); + } + + public BanInfo getBanInfo(Player player) { + this.checkUsable(); + return Reflex.getApiWrapper().getBanInfo(player); + } + + public ReflexAPI unbanPlayer(Player player) { + this.checkUsable(); + return Reflex.getApiWrapper().unbanPlayer(player); + } + + public ReflexAPI banPlayer(Player player, String message, long banTime, TimeUnit timeUnit) { + this.checkUsable(); + return Reflex.getApiWrapper().banPlayer(player, message, banTime, timeUnit); + } + + public boolean isPlayerBanned(Player player) { + this.checkUsable(); + return Reflex.getApiWrapper().isPlayerBanned(player); + } + + public ReflexAPI log(FlogLevel lvl, String message) { + this.checkUsable(); + return Reflex.getApiWrapper().log(lvl, message); + } + + public int getBanCount() { + this.checkUsable(); + return Reflex.getApiWrapper().getBanCount(); + } + + public int getBanCountIn(TimeUnit unit, long time) { + this.checkUsable(); + return Reflex.getApiWrapper().getBanCountIn(unit, time); + } + + public BanImpl getBanImpl() { + this.checkUsable(); + return Reflex.getApiWrapper().getBanImpl(); + } + + public DatabaseClient getDBClient() { + this.checkUsable(); + return Reflex.getApiWrapper().getDBClient(); + } + + public DailyLogFilePublisher getLogImpl() { + this.checkUsable(); + return Reflex.getApiWrapper().getLogImpl(); + } + + public DataImpl getDataImpl() { + this.checkUsable(); + return Reflex.getApiWrapper().getDataImpl(); + } + + public boolean isCheckEnabled(Cheat c) { + this.checkUsable(); + return Reflex.getApiWrapper().isCheckEnabled(c); + } + + public boolean isCheckDisabled(Cheat c) { + this.checkUsable(); + return Reflex.getApiWrapper().isCheckDisabled(c); + } + + public ReflexAPI enableCheck(Cheat c) { + this.checkUsable(); + return Reflex.getApiWrapper().enableCheck(c); + } + + public ReflexAPI disableCheck(Cheat c) { + this.checkUsable(); + return Reflex.getApiWrapper().disableCheck(c); + } + + public ReflexAPI toggleCheck(Cheat c) { + this.checkUsable(); + return Reflex.getApiWrapper().toggleCheck(c); + } + + public ReflexAPI enableComponent(String name) { + this.checkUsable(); + return Reflex.getApiWrapper().enableComponent(name); + } + + public ReflexAPI disableComponent(String name) { + this.checkUsable(); + return Reflex.getApiWrapper().disableComponent(name); + } + + public boolean isComponentEnabled(String name) { + this.checkUsable(); + return Reflex.getApiWrapper().isComponentEnabled(name); + } + + public boolean isComponentDisabled(String name) { + this.checkUsable(); + return Reflex.getApiWrapper().isComponentDisabled(name); + } + + public ReflexAPI reset(Player p) { + this.checkUsable(); + return Reflex.getApiWrapper().reset(p); + } + + public ReflexAPI reloadConfig() { + this.checkUsable(); + return Reflex.getApiWrapper().reloadConfig(); + } + + public ReflexAPI reloadPermissionCaches() { + this.checkUsable(); + return Reflex.getApiWrapper().reloadPermissionCaches(); + } + + public ReflexAPI reloadTheme() { + this.checkUsable(); + return Reflex.getApiWrapper().reloadTheme(); + } + + public ReflexAPI reloadAll() { + this.checkUsable(); + return Reflex.getApiWrapper().reloadAll(); + } + + public String translateThemeString(String key) { + this.checkUsable(); + return Reflex.getApiWrapper().translateThemeString(key); + } + + public String translateAndFormat(String key) { + this.checkUsable(); + return Reflex.getApiWrapper().translateAndFormat(key); + } + + public String translateAndFormat(String prefix, String key) { + this.checkUsable(); + return Reflex.getApiWrapper().translateAndFormat(prefix, key); + } + + public Map getTheme() { + this.checkUsable(); + return theme; + } + + public boolean isConnectedToCloud() { + this.checkUsable(); + return Reflex.getApiWrapper().isConnectedToCloud(); + } + + public ReflexAPI connectToCloud(String key) { + this.checkUsable(); + return Reflex.getApiWrapper().connectToCloud(key); + } + + public int getPingToCloud() { + this.checkUsable(); + return Reflex.getApiWrapper().getPingToCloud(); + } + + public String reflexVersion() { + this.checkUsable(); + return Reflex.getApiWrapper().reflexVersion(); + } + + public int nnVersion() { + this.checkUsable(); + return Reflex.getApiWrapper().nnVersion(); + } + + public int apiVersion() { + this.checkUsable(); + return Reflex.getApiWrapper().apiVersion(); + } + + public int cloudProtocolVersion() { + this.checkUsable(); + return Reflex.getApiWrapper().cloudProtocolVersion(); + } + + public String getReflexPrefix() { + this.checkUsable(); + return Reflex.getApiWrapper().getReflexPrefix(); + } +} diff --git a/src/main/java/rip/reflex/api/ReflexAPIProvider.java b/src/main/java/rip/reflex/api/ReflexAPIProvider.java new file mode 100644 index 0000000..afbdac9 --- /dev/null +++ b/src/main/java/rip/reflex/api/ReflexAPIProvider.java @@ -0,0 +1,30 @@ +package rip.reflex.api; + +import org.bukkit.Bukkit; +import rip.reflex.Reflex; +import rip.reflex.ReflexAPIWrapper; +import rip.reflex.api.event.ReflexLoadEvent; + +public class ReflexAPIProvider { + private static ReflexAPI api = null; + private static boolean init = false; + + public static ReflexAPI getAPI() { + if (init && api != null) { + return api; + } else { + throw new IllegalStateException("Reflex API has not been initialized yet!"); + } + } + + public static void init(Reflex reflex) { + if (init) { + throw new IllegalStateException("Cannot initialize Reflex API twice!"); + } else { + Reflex.setApiWrapper(new ReflexAPIWrapper(reflex, api = new ReflexAPI(reflex))); + init = true; + Bukkit.getPluginManager().callEvent(new ReflexLoadEvent(Reflex.getReflex().getDescription().getVersion(), 6)); + Reflex.getReflex().info("Reflex API v6 has been loaded."); + } + } +} diff --git a/src/main/java/rip/reflex/api/ReflexPlayerData.java b/src/main/java/rip/reflex/api/ReflexPlayerData.java new file mode 100644 index 0000000..c00802a --- /dev/null +++ b/src/main/java/rip/reflex/api/ReflexPlayerData.java @@ -0,0 +1,21 @@ +package rip.reflex.api; + +import java.io.Serializable; +import rip.reflex.Reflex; + +public class ReflexPlayerData implements Serializable { + private static final long serialVersionUID = 2013242925633046363L; + private final Object tpd; + + public Object tpd(String s, int i) { + if (i < 0) { + throw new NullPointerException(); + } else { + return Reflex.getApiWrapper()._i(s) == -1546460115 ? this.tpd : null; + } + } + + public ReflexPlayerData(Object tpd) { + this.tpd = tpd; + } +} diff --git a/src/main/java/rip/reflex/api/db/BanImpl.java b/src/main/java/rip/reflex/api/db/BanImpl.java new file mode 100644 index 0000000..f1dd267 --- /dev/null +++ b/src/main/java/rip/reflex/api/db/BanImpl.java @@ -0,0 +1,23 @@ +package rip.reflex.api.db; + +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import rip.reflex.api.BanInfo; + +public interface BanImpl { + default void init() { + } + + default void off() { + } + + boolean ban(UUID uuid, String message, long time, TimeUnit timeUnit); + + boolean unban(UUID uuid); + + BanInfo getBanInfo(UUID uuid); + + int getBanCount(); + + int getBannedCountIn(TimeUnit timeUnit, long time); +} diff --git a/src/main/java/rip/reflex/api/db/DataImpl.java b/src/main/java/rip/reflex/api/db/DataImpl.java new file mode 100644 index 0000000..527dca4 --- /dev/null +++ b/src/main/java/rip/reflex/api/db/DataImpl.java @@ -0,0 +1,11 @@ +package rip.reflex.api.db; + +public interface DataImpl { + void saveData(String name, byte[] data); + + boolean contains(); + + byte[] getData(); + + String getHash(); +} diff --git a/src/main/java/rip/reflex/api/db/DatabaseClient.java b/src/main/java/rip/reflex/api/db/DatabaseClient.java new file mode 100644 index 0000000..7014c6a --- /dev/null +++ b/src/main/java/rip/reflex/api/db/DatabaseClient.java @@ -0,0 +1,38 @@ +package rip.reflex.api.db; + +import rip.reflex.util.db.DatabaseType; +import rip.reflex.util.db.conf.DatabaseConfig; + +public interface DatabaseClient { + default void connect(DatabaseConfig config) { + try { + this.connect0(config); + } catch (Exception ex) { + throw new RuntimeException("Error while connecting to database!", ex); + } + } + + default boolean isConnected() { + try { + return this.isConnected0(); + } catch (Exception e) { + throw new RuntimeException("Error while checking database connection status", e); + } + } + + default void disconnect() { + try { + this.disconnect0(); + } catch (Exception err) { + throw new RuntimeException("Error while disconnecting from database!", err); + } + } + + void connect0(DatabaseConfig config) throws Exception; + + boolean isConnected0() throws Exception; + + void disconnect0() throws Exception; + + DatabaseType getType(); +} diff --git a/src/main/java/rip/reflex/api/db/LogImpl.java b/src/main/java/rip/reflex/api/db/LogImpl.java new file mode 100644 index 0000000..de3e607 --- /dev/null +++ b/src/main/java/rip/reflex/api/db/LogImpl.java @@ -0,0 +1,17 @@ +package rip.reflex.api.db; + +import me.flo.flogger.types.FlogLevel; + +public interface LogImpl { + default void init() { + } + + default void off() { + } + + void log(FlogLevel level, String message, Object... args); + + String getExecutionID(); + + long getStarttime(); +} diff --git a/src/main/java/rip/reflex/api/event/ReflexCheckEvent.java b/src/main/java/rip/reflex/api/event/ReflexCheckEvent.java new file mode 100644 index 0000000..b4d237d --- /dev/null +++ b/src/main/java/rip/reflex/api/event/ReflexCheckEvent.java @@ -0,0 +1,56 @@ +package rip.reflex.api.event; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; + +public class ReflexCheckEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private final Cheat cheat; + private final String violationId; + private final CheckResult result; + private boolean cancelled; + + public ReflexCheckEvent(Player player, Cheat cheat, CheckResult result, String violationId) { + this.player = player; + this.cheat = cheat; + this.result = result; + this.violationId = violationId; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Player getPlayer() { + return this.player; + } + + public Cheat getCheat() { + return this.cheat; + } + + public CheckResult getResult() { + return this.result; + } + + public String getViolationId() { + return this.violationId; + } + + public HandlerList getHandlers() { + return handlers; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } +} diff --git a/src/main/java/rip/reflex/api/event/ReflexCommandEvent.java b/src/main/java/rip/reflex/api/event/ReflexCommandEvent.java new file mode 100644 index 0000000..617c669 --- /dev/null +++ b/src/main/java/rip/reflex/api/event/ReflexCommandEvent.java @@ -0,0 +1,59 @@ +package rip.reflex.api.event; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import rip.reflex.api.Cheat; + +public class ReflexCommandEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private final Cheat cheat; + private final String violationId; + private String command; + private boolean cancelled; + + public ReflexCommandEvent(Player player, Cheat cheat, String command, String violationId) { + this.player = player; + this.cheat = cheat; + this.command = command; + this.violationId = violationId; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Player getPlayer() { + return this.player; + } + + public Cheat getCheat() { + return this.cheat; + } + + public String getCommand() { + return this.command; + } + + public void setCommand(String command) { + this.command = command; + } + + public String getViolationId() { + return this.violationId; + } + + public HandlerList getHandlers() { + return handlers; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } +} diff --git a/src/main/java/rip/reflex/api/event/ReflexHeurSnapshotEvent.java b/src/main/java/rip/reflex/api/event/ReflexHeurSnapshotEvent.java new file mode 100644 index 0000000..bdae21e --- /dev/null +++ b/src/main/java/rip/reflex/api/event/ReflexHeurSnapshotEvent.java @@ -0,0 +1,44 @@ +package rip.reflex.api.event; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class ReflexHeurSnapshotEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private final boolean legit; + private final String snapshotID; + private final byte[] body; + + public static HandlerList getHandlerList() { + return handlers; + } + + public HandlerList getHandlers() { + return handlers; + } + + public ReflexHeurSnapshotEvent(Player player, boolean legit, String snapshotID, byte[] body) { + this.player = player; + this.legit = legit; + this.snapshotID = snapshotID; + this.body = body; + } + + public Player getPlayer() { + return this.player; + } + + public boolean isLegit() { + return this.legit; + } + + public String getSnapshotID() { + return this.snapshotID; + } + + public byte[] getBody() { + return this.body; + } +} diff --git a/src/main/java/rip/reflex/api/event/ReflexLoadEvent.java b/src/main/java/rip/reflex/api/event/ReflexLoadEvent.java new file mode 100644 index 0000000..b319e69 --- /dev/null +++ b/src/main/java/rip/reflex/api/event/ReflexLoadEvent.java @@ -0,0 +1,31 @@ +package rip.reflex.api.event; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class ReflexLoadEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private final String version; + private final int apiVersion; + + public static HandlerList getHandlerList() { + return handlers; + } + + public HandlerList getHandlers() { + return handlers; + } + + public ReflexLoadEvent(String version, int apiVersion) { + this.version = version; + this.apiVersion = apiVersion; + } + + public String getVersion() { + return this.version; + } + + public int getApiVersion() { + return this.apiVersion; + } +} diff --git a/src/main/java/rip/reflex/check/base/Check.java b/src/main/java/rip/reflex/check/base/Check.java new file mode 100644 index 0000000..ddd7f36 --- /dev/null +++ b/src/main/java/rip/reflex/check/base/Check.java @@ -0,0 +1,537 @@ +package rip.reflex.check.base; + +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.events.PacketAdapter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import me.flo.flogger.types.FlogLevel; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Listener; +import rip.reflex.Reflex; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.api.event.ReflexCheckEvent; +import rip.reflex.api.event.ReflexCommandEvent; +import rip.reflex.util.appearance.Theme; +import rip.reflex.util.data.Stats; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.math.Maths; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.performance.LagStatus; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public abstract class Check implements Listener { + public static volatile boolean newAPCheckCompleted = Boolean.parseBoolean("FALSE".toLowerCase()); + private static final String ID_CHARSET = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890"; + private static final Set disabledComps = new HashSet<>(); + protected final Reflex reflex; + protected final CheckType type; + private static final Set invalidWorlds = new HashSet<>(); + protected final Cheat cheat; + private final Map configCache = new ConcurrentHashMap<>(); + private final String name; + private final String comp; + private boolean enabled; + private boolean sync = false; + private boolean lagSensetive = true; + private final Set disabledWorlds = new HashSet<>(); + + public Check(String name, String comp, CheckType type, Cheat cheat) { + this.name = name; + this.comp = comp; + this.type = type; + this.cheat = cheat; + this.reflex = Reflex.getReflex(); + this.enabled = this.isEnabledInConfig(); + if (this.isEnabledInConfig()) { + List disabledComps = this.reflex.getConfig().getStringList(name.toLowerCase() + ".disabled_checks"); + if (disabledComps != null) { + disabledComps.remove("example entry"); + Check.disabledComps.addAll(disabledComps); + } + + List disabledWorlds = this.reflex.getConfig().getStringList(name.toLowerCase() + ".disabled_worlds"); + if (disabledWorlds != null) { + disabledWorlds.forEach(world -> { + World w = Bukkit.getWorld(world); + if (w == null) { + reportInvalidWorld(world); + } else { + this.disabledWorlds.add(w); + } + }); + } + + this.loadAdvancedLocalSettings(); + if (disabledComps != null && disabledComps.contains(comp)) { + reportDisabledComponent(name, comp); + } else { + Bukkit.getPluginManager().registerEvents(this, this.reflex); + } + } + } + + public boolean isServerLagging() { + return this.isServerLagging(3000L); + } + + public boolean isServerLagging(long maxMsSinceLastLag) { + return !this.reflex.getSingleServerLagTracker().hasPassed(maxMsSinceLastLag); + } + + protected T getAdvancedLocalSetting(String name, T defaultValue) { + return this.reflex.getAdvancedSetting(this.comp + "." + name, defaultValue); + } + + protected void supportCloudComputings() { + this.reflex.getCloudService().getCloudSupportedChecks().add(this); + } + + public void loadAdvancedLocalSettings() { + } + + public boolean isDisabledInWorld(World w) { + return this.disabledWorlds.contains(w); + } + + private static void reportInvalidWorld(String world) { + if (!invalidWorlds.contains(world)) { + Reflex.getReflex().warn("World '" + world + "' does not exist or is unloaded, and hence cannot be added to disabled worlds"); + invalidWorlds.add(world); + } + } + + private static void reportDisabledComponent(String check, String comp) { + Reflex.getReflex() + .warn( + "A " + + (check == null ? " " : check) + + " component " + + comp + + " is disabled. It is highly recommended that you report bugs at go.reflex.rip/bug rather than turn the checks off! Support regarding bypasses will not be providen in case there are disabled components." + ); + } + + public static String correctName(String s) { + for (Check check : CheckRegistry.loadedChecksList()) { + if (check.getName().equalsIgnoreCase(s)) { + return check.getName(); + } + } + + return null; + } + + public static void addVl(Stats s, Cheat c, CheckResult r) { + if (r.getViolationsMod() != 0) { + int v = s.getLagStatus().correctVl(r.getViolationsMod()); + s.addViolations(c, v); + r.setMod(v); + } + } + + public static boolean isComponentEnabled(String name) { + return !isComponentDisabled(name); + } + + public static boolean isComponentDisabled(String name) { + return disabledComps.contains(name); + } + + public static void enableComponent(String name) { + Reflex.getReflex().info("Enabled component " + name); + disabledComps.remove(name); + } + + public static void disableComponent(String name) { + if (!disabledComps.contains(name)) { + reportDisabledComponent(null, name); + disabledComps.add(name); + } + } + + public static void check(Player p, Stats stats, Cancellable event, Check check, CheckResult result) { + if (!result.isZero() && !check.isCompDisabled()) { + try { + Reflex reflex = Reflex.getReflex(); + List disabledChecks = reflex.getConfig().getStringList(check.getName().toLowerCase() + ".disabled_checks"); + if (disabledChecks != null && !disabledChecks.isEmpty()) { + for (String tag : result.getTags()) { + for (String disabled : disabledChecks) { + if (tag.toLowerCase().contains(disabled.toLowerCase())) { + stats.addViolations(check.getCheat(), -result.getViolationsMod()); + return; + } + } + } + } + + MethodProfiler mp = new MethodProfiler("FI-78461793"); + String id = "#" + Strings.randomComp(8, "QWERTYUIOPASDFGHJKLZXCVBNM1234567890"); + ReflexCheckEvent checkEvent = new ReflexCheckEvent(p, check.getCheat(), result, id); + Bukkit.getPluginManager().callEvent(checkEvent); + if (result.isCheckPassed()) { + return; + } + + if (!p.isOnline()) { + Stats.reset(stats); + return; + } + + if (stats.getStat("canBypass" + check.getName(), boolean.class) || checkEvent.isCancelled()) { + stats.addViolations(check.getCheat(), -result.getViolationsMod()); + return; + } + + if (result.shouldCancel() && event != null) { + event.setCancelled(true); + } + + check0(reflex, p, stats, check, result, id); + mp.checkExecutionTime(); + mp.addToTimings(); + } catch (NullPointerException ignored) { + } + } + } + + private static void check0(Reflex reflex, Player p, Stats stats, Check check, CheckResult result, String id) { + MethodProfiler mp = new MethodProfiler("NH-39501295"); + if (reflex.getSetting("general.verbose", true)) { + MethodProfiler mpTags = new MethodProfiler("UG-57619233"); + Theme t = Reflex.getTheme(); + boolean includeTags = t.getVerboseFormat().contains("%tags%"); + StringBuilder message = new StringBuilder( + t.getPrefix() + + Strings.wrap(t.getVerboseFormat()) + .replace("%player%", p::getName) + .replace("%check%", check::getName) + .replace("%vl%", () -> stats.getViolations(check.getCheat())) + .replace("%mod%", result::getViolationsMod) + .replace("%tags%", "") + .placeholderApi(p) + .get() + ); + if (includeTags) { + for (String tag : result.getTags()) { + message.append(result.getTags().indexOf(tag) == 0 ? " " : t.getVerboseTagsSeparator()).append(t.getVerboseTagsCol()).append(tag); + } + + if (result.shouldCancel()) { + message.append(t.getVerboseTagsSeparator()).append(t.getVerboseTagsCol()).append("cancel"); + } + + message.append(t.getVerboseTagsSeparator()).append(t.getVerboseTagsCol()).append("ping: ").append(stats.getPing()); + message.append(t.getVerboseTagsSeparator()) + .append(t.getVerboseTagsCol()) + .append("lp: ") + .append(stats.getLagPoints()) + .append(" (") + .append(stats.getLagStatus().fancyName()) + .append(")"); + message.append(t.getVerboseTagsSeparator()) + .append(t.getVerboseTagsCol()) + .append("tps: ") + .append(Maths.toRoundedString(reflex.getTpsMeter().getTps())); + message.append(t.getVerboseTagsSeparator()).append(t.getVerboseTagsCol()).append("comp: ").append(check.comp); + } + + mpTags.addToTimings(); + MethodProfiler mpLog = new MethodProfiler("DI-10237519"); + reflex.log(FlogLevel.DEBUG, Strings.wrap(message).noColors().replace(t.getPrefix(), "").get()); + reflex.verbose(Strings.wrap(message.toString()).colourize().toString()); + mpLog.addToTimings(); + } + + MethodProfiler mpPrepare = new MethodProfiler("CX-2193901"); + List actions = new ArrayList<>(check.getActions().getKeys(false)); + Collections.reverse(actions); + int curVl = stats.getViolations(check.getCheat()); + int preVl = stats.getLastVl(check.getCheat()); + if (curVl != 0) { + List dispatchList = new ArrayList<>(); + actions.stream() + .filter(vl -> { + int vli = Integer.parseInt(vl); + return preVl < vli && curVl >= vli; + }) + .forEach( + s -> { + MethodProfiler mpCmd = new MethodProfiler("KY-598712691"); + + for (String command : reflex.getConfig().getStringList(check.getName().toLowerCase() + ".actions." + s)) { + ReflexCommandEvent cmdEvent = new ReflexCommandEvent(p, check.getCheat(), command, id); + Bukkit.getPluginManager().callEvent(cmdEvent); + if (!cmdEvent.isCancelled()) { + int d = cmdEvent.getCommand().contains("%bannedplayersinlast") + ? Integer.valueOf(command.split("bannedplayersinlast")[1].split("days%")[0]) + : 0; + command = Strings.wrap(cmdEvent.getCommand()) + .replace("%player%", p::getName) + .replace("%ping%", stats::getPing) + .replace("%violations%", () -> stats.getViolations(check.getCheat())) + .replace("%check%", check::getName) + .replace("%break%", "\n") + .replace("%bannedplayers%", reflex::getBanCount) + .replace("%bannedplayersinlast" + d + "days%", () -> reflex.getBanCountIn(TimeUnit.DAYS, (long)d)) + .replace("%execid%", id) + .replace("%id%", id) + .replace("%date%", reflex::getDate) + .replace("%tps%", () -> "" + reflex.getTpsMeter().getTps()) + .replace("%lp%", () -> stats.getInt("lagPoints")) + .replace("%lagstatus%", () -> stats.getStat("lagStatus", LagStatus.class)) + .replace("%time%", reflex::getTime) + .placeholderApi(p) + .colourizeAndGet(); + dispatchList.add(command); + } + } + + mpCmd.addToTimings(); + } + ); + mpPrepare.addToTimings(); + MethodProfiler mpDispatch = new MethodProfiler("OW-4978217489"); + if (Bukkit.isPrimaryThread()) { + dispatchCommands(reflex, id, dispatchList); + } else { + ReflexScheduler.sync().run(ReflexRunnable.simple("dispatch-cmds-thread", () -> dispatchCommands(reflex, id, dispatchList))); + } + + mpDispatch.addToTimings(); + mp.addToTimings(); + } + } + + private static void dispatchCommands(Reflex reflex, String id, List dispatchList) { + MethodProfiler mp = new MethodProfiler("OT-74021485"); + dispatchList.forEach(c -> { + reflex.log(FlogLevel.DEBUG, "Dispatching command " + Strings.wrap(c).replace("\n", "%break%").replace(" ", "%space%") + " (execution id: " + id + ")"); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), c); + }); + mp.checkExecutionTime(); + mp.addToTimings(); + } + + public boolean isNotSilent() { + return !this.isSilent(); + } + + public String getName() { + return this.name; + } + + public String comp() { + return Strings.encode(this.comp); + } + + public CheckType getType() { + return this.type; + } + + public T getLocalSetting(String configPath, T defaultValue) { + return this.getGeneralSetting(this.name.toLowerCase() + "." + configPath, defaultValue); + } + + public T getGeneralSetting(String configPath, T defaultValue) { + if (this.reflex.isCachingConfig()) { + if (!this.configCache.containsKey(configPath)) { + this.configCache.put(configPath, this.getFromConfig(configPath, defaultValue)); + } + + return (T)this.configCache.get(configPath); + } else { + return this.getFromConfig(configPath, defaultValue); + } + } + + public void flushCaches() { + this.configCache.clear(); + } + + private T getFromConfig(String path, T def) { + if (!this.reflex.getConfig().contains(path)) { + return def; + } else { + try { + return (T)this.reflex.getConfig().get(path); + } catch (Exception ignored) { + return def; + } + } + } + + public ConfigurationSection getActions() { + return this.reflex.getConfig().getConfigurationSection(this.name.toLowerCase() + ".actions"); + } + + public boolean isCompEnabled() { + return !this.isCompDisabled(); + } + + public boolean isCompDisabled() { + return disabledComps.contains(this.comp); + } + + public void enableComponent() { + this.reflex.info("Enabled component " + this.comp); + disabledComps.remove(this.comp); + } + + public void disableComponent() { + if (!disabledComps.contains(this.comp)) { + reportDisabledComponent(null, this.name); + disabledComps.add(this.comp); + } + } + + public boolean isEnabled() { + return CheckRegistry.getStatus(this); + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + CheckRegistry.updateStatus(this); + } + + public boolean isDisabled() { + return !this.isEnabled(); + } + + public void toggle() { + this.setEnabled(!this.isEnabled()); + } + + public void enable() { + if (!this.isEnabled()) { + this.reflex.log(FlogLevel.DEBUG, "Enabled check " + this.name); + this.setEnabled(true); + } + } + + public void disable() { + if (!this.isDisabled()) { + this.reflex.log(FlogLevel.DEBUG, "Disabled check " + this.name); + this.setEnabled(false); + } + } + + public boolean isEnabledInConfig() { + return this.getLocalSetting("enabled", false); + } + + protected boolean shouldCancel(Stats stats, int threshold) { + return this.isNotSilent() + && stats.getViolations(this.cheat) + > (this.getLocalSetting("dynamic_cancel_thresholds", true) ? threshold : this.getLocalSetting("cancel_threshold", threshold)); + } + + protected boolean shouldCancel(Stats stats) { + return this.isNotSilent() && stats.getViolations(this.cheat) > this.getLocalSetting("cancel_threshold", 0); + } + + protected boolean isSilent() { + return this.getLocalSetting("silent", false); + } + + protected void setupVlResetThread(int resetDelaySeconds) { + if (this.isEnabledInConfig()) { + LoopHelper.loopStatsEvery(stats -> stats.resetViolations(this.cheat), resetDelaySeconds * 20); + } + } + + protected void setupVlReductionThread(int reductionDelaySeconds, float reductionFac) { + if (this.isEnabledInConfig()) { + LoopHelper.loopStatsEvery( + stats -> stats.setViolations(this.cheat, Maths.floor((float)stats.getViolations(this.cheat) * reductionFac)), reductionDelaySeconds * 20 + ); + } + } + + protected void setupVlSubtractionThread(int subtractionDelaySeconds, int subtractionFac) { + if (this.isEnabledInConfig()) { + LoopHelper.loopStatsEvery(stats -> stats.addViolations(this.cheat, -subtractionFac), subtractionDelaySeconds * 20); + } + } + + protected void runTask(ReflexRunnable task, boolean async) { + if (this.isEnabledInConfig()) { + if (async) { + ReflexScheduler.async().run(task); + } else { + ReflexScheduler.sync().run(task); + } + } + } + + protected void delayTask(ReflexRunnable task, int startDelayTicks, boolean async) { + if (this.isEnabledInConfig()) { + if (async) { + ReflexScheduler.async().runLater(task, startDelayTicks); + } else { + ReflexScheduler.sync().runLater(task, startDelayTicks); + } + } + } + + protected void runTimer(ReflexRunnable task, int repeatDelayTicks, boolean async) { + if (this.isEnabledInConfig()) { + if (async) { + ReflexScheduler.async().runTimer(task, repeatDelayTicks); + } else { + ReflexScheduler.sync().runTimer(task, repeatDelayTicks); + } + } + } + + protected void registerPacketHandler(PacketAdapter adapter) { + if (this.isEnabledInConfig()) { + ProtocolLibrary.getProtocolManager().addPacketListener(adapter); + } + } + + boolean isEnabled0() { + return this.enabled; + } + + public Cheat getCheat() { + return this.cheat; + } + + public Map getConfigCache() { + return this.configCache; + } + + public boolean isSync() { + return this.sync; + } + + public boolean isLagSensetive() { + return this.lagSensetive; + } + + protected void setSync(boolean sync) { + this.sync = sync; + } + + protected void setLagSensetive(boolean lagSensetive) { + this.lagSensetive = lagSensetive; + } + + public Set getDisabledWorlds() { + return this.disabledWorlds; + } +} diff --git a/src/main/java/rip/reflex/check/base/CheckLoader.java b/src/main/java/rip/reflex/check/base/CheckLoader.java new file mode 100644 index 0000000..640064c --- /dev/null +++ b/src/main/java/rip/reflex/check/base/CheckLoader.java @@ -0,0 +1,102 @@ +package rip.reflex.check.base; + +import rip.reflex.Reflex; +import rip.reflex.check.combat.CriticalsCheck; +import rip.reflex.check.combat.antiknockback.HorizontalVelocityCheck; +import rip.reflex.check.combat.antiknockback.VerticalVelocityCheck; +import rip.reflex.check.combat.killaura.AccuracyCheck; +import rip.reflex.check.combat.killaura.AutoBlockCheck; +import rip.reflex.check.combat.killaura.BalanceCheck; +import rip.reflex.check.combat.killaura.CPSCheck; +import rip.reflex.check.combat.killaura.CombinedCheck; +import rip.reflex.check.combat.killaura.DirectionCheck; +import rip.reflex.check.combat.killaura.FightspeedCheck; +import rip.reflex.check.combat.killaura.ForcefieldCheck; +import rip.reflex.check.combat.killaura.FrontEntityCheck; +import rip.reflex.check.combat.killaura.HeuristicsCheck; +import rip.reflex.check.combat.killaura.HitboxCheck; +import rip.reflex.check.combat.killaura.ImpossibleHitCheck; +import rip.reflex.check.combat.killaura.PacketRotsCheck; +import rip.reflex.check.combat.killaura.ReachCheck; +import rip.reflex.check.combat.killaura.SwingCheck; +import rip.reflex.check.combat.killaura.YawRateCheck; +import rip.reflex.check.combat.killaura.YawStatisticCheck; +import rip.reflex.check.movement.ElytraMoveCheck; +import rip.reflex.check.movement.InvMoveCheck; +import rip.reflex.check.movement.VehicleMoveCheck; +import rip.reflex.check.player.ClientControlCheck; +import rip.reflex.check.player.badpackets.InvalidMoveCheck; +import rip.reflex.check.player.badpackets.PacketIgnoranceCheck; +import rip.reflex.check.player.badpackets.PingSpoofCheck; +import rip.reflex.check.player.badpackets.RepetitiveItemSlotCheck; +import rip.reflex.check.player.badpackets.RepetitiveRotationCheck; +import rip.reflex.check.player.badpackets.ReverseTimerGlideCheck; +import rip.reflex.check.player.invactions.ClosedInvClickCheck; +import rip.reflex.check.player.invactions.FastInvClickCheck; +import rip.reflex.check.world.ScaffoldCheck; +import rip.reflex.check.world.TowerCheck; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; + +public class CheckLoader { + private static long i = -498162321798562193L; + public static Check reachCheck = null; + public static Check yawStatCheck = null; + public static HeuristicsCheck heuristicsCheck = null; + + public static void loadAll(Reflex r) { + if (i % 2L != 0L && r != null) { + i = -i + (long)((int)Math.sqrt(25.0)); + CheckRegistry.registerCheck(new ScaffoldCheck()); + CheckRegistry.registerCheck(new TowerCheck()); + CheckRegistry.registerCheck(new SwingCheck()); + CheckRegistry.registerCheck(reachCheck = new ReachCheck()); + CheckRegistry.registerCheck(new YawRateCheck()); + CheckRegistry.registerCheck(new CriticalsCheck()); + if (!r.getSetting("killaura.no_npc_checks", false)) { + CheckRegistry.registerCheck(new FrontEntityCheck()); + CheckRegistry.registerCheck(new ForcefieldCheck()); + } + + CheckRegistry.registerCheck(new CPSCheck()); + CheckRegistry.registerCheck(new FightspeedCheck()); + CheckRegistry.registerCheck(new DirectionCheck()); + CheckRegistry.registerCheck(new AccuracyCheck()); + CheckRegistry.registerCheck(new VerticalVelocityCheck()); + CheckRegistry.registerCheck(new HorizontalVelocityCheck()); + CheckRegistry.registerCheck(new PingSpoofCheck()); + CheckRegistry.registerCheck(yawStatCheck = new YawStatisticCheck()); + CheckRegistry.registerCheck(new CombinedCheck()); + if (VersionUtils.getServerVersion().isLessThan(MCVersion.V1_12_X)) { + CheckRegistry.registerCheck(new AutoBlockCheck()); + } + + CheckRegistry.registerCheck(new ImpossibleHitCheck()); + CheckRegistry.registerCheck(new PacketRotsCheck()); + CheckRegistry.registerCheck(new RepetitiveRotationCheck()); + CheckRegistry.registerCheck(new RepetitiveItemSlotCheck()); + CheckRegistry.registerCheck(new InvalidMoveCheck()); + CheckRegistry.registerCheck(new ClientControlCheck()); + CheckRegistry.registerCheck(new InvMoveCheck()); + CheckRegistry.registerCheck(new ClosedInvClickCheck()); + CheckRegistry.registerCheck(new FastInvClickCheck()); + CheckRegistry.registerCheck(new PacketIgnoranceCheck()); + CheckRegistry.registerCheck(new BalanceCheck()); + CheckRegistry.registerCheck(new HitboxCheck()); + if (VersionUtils.getServerVersion().hasMinimum(MCVersion.V1_9_X)) { + CheckRegistry.registerCheck(new VehicleMoveCheck()); + } else { + r.info("The VehicleMove check only works on MC 1.9+. No worries: boat cheats also work on 1.9+ only."); + } + + if (VersionUtils.getServerVersion().hasMinimum(MCVersion.V1_9_X)) { + CheckRegistry.registerCheck(new ElytraMoveCheck()); + } else { + r.info("The ElytraMove check only works on MC 1.9+. No worries: there are no elytras on 1.8 ;)"); + } + + CheckRegistry.registerCheck(new ReverseTimerGlideCheck()); + CheckRegistry.registerCheck(heuristicsCheck = new HeuristicsCheck()); + } + } +} diff --git a/src/main/java/rip/reflex/check/base/CheckRegistry.java b/src/main/java/rip/reflex/check/base/CheckRegistry.java new file mode 100644 index 0000000..462f7ff --- /dev/null +++ b/src/main/java/rip/reflex/check/base/CheckRegistry.java @@ -0,0 +1,78 @@ +package rip.reflex.check.base; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import rip.reflex.Reflex; +import rip.reflex.api.Cheat; + +public class CheckRegistry { + private static final ConcurrentHashMap status = new ConcurrentHashMap<>(); + private static final List allChecks = new ArrayList<>(); + private static final List[] checkArray = new List[CheckType.values().length]; + + public static List loadedChecksList() { + return allChecks; + } + + public static List getChecksOfType(CheckType type) { + return checkArray[type.ordinal()]; + } + + public static List getActiveChecksOfType(CheckType type) { + List checks = new ArrayList<>(); + + for (Check check : allChecks) { + if (check.isEnabled() && check.getType() == type && check.isCompEnabled()) { + checks.add(check); + } + } + + return checks; + } + + public static void registerCheck(Check check) { + if (check.isEnabledInConfig()) { + CheckType type = check.getType(); + registerCheck0(check, type); + } + } + + public static Check getCheck(Cheat cheat) { + return allChecks.stream().filter(c -> c.getCheat() == cheat).findFirst().orElse(null); + } + + public static void updateStatus(Check check) { + status.put(check.getName(), check.isEnabled0()); + } + + public static boolean getStatus(Check check) { + if (!status.containsKey(check.getName())) { + updateStatus(check); + } + + return status.get(check.getName()); + } + + private static void registerCheck0(Check check, CheckType type) { + List registered = getChecksOfType(type); + registered.add(check); + allChecks.add(check); + if (!status.containsKey(check.getName())) { + Reflex.getReflex().info("Enabled check " + check.getName()); + } + + updateStatus(check); + checkArray[type.ordinal()].add(check); + } + + public static ConcurrentHashMap getStatus() { + return status; + } + + static { + for (int i = 0; i < checkArray.length; i++) { + checkArray[i] = new ArrayList<>(); + } + } +} diff --git a/src/main/java/rip/reflex/check/base/CheckType.java b/src/main/java/rip/reflex/check/base/CheckType.java new file mode 100644 index 0000000..4126571 --- /dev/null +++ b/src/main/java/rip/reflex/check/base/CheckType.java @@ -0,0 +1,9 @@ +package rip.reflex.check.base; + +public enum CheckType { + COMBAT, + MOVEMENT, + WORLD, + PACKET, + CUSTOM; +} diff --git a/src/main/java/rip/reflex/check/base/CheckablePacketType.java b/src/main/java/rip/reflex/check/base/CheckablePacketType.java new file mode 100644 index 0000000..8dbaeee --- /dev/null +++ b/src/main/java/rip/reflex/check/base/CheckablePacketType.java @@ -0,0 +1,4 @@ +package rip.reflex.check.base; + +public class CheckablePacketType { +} diff --git a/src/main/java/rip/reflex/check/base/impl/CombatCheck.java b/src/main/java/rip/reflex/check/base/impl/CombatCheck.java new file mode 100644 index 0000000..34b9b29 --- /dev/null +++ b/src/main/java/rip/reflex/check/base/impl/CombatCheck.java @@ -0,0 +1,27 @@ +package rip.reflex.check.base.impl; + +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckType; +import rip.reflex.util.data.Stats; + +public abstract class CombatCheck extends Check { + private final boolean heuristic; + + public CombatCheck(String name, String comp, boolean heuristic, Cheat cheat) { + super(name, comp, CheckType.COMBAT, cheat); + this.heuristic = heuristic; + } + + public abstract CheckResult check(Player player, Stats stats, LivingEntity target); + + public abstract CheckResult check(Player player, Stats stats, Location from, Location to); + + public boolean isHeuristic() { + return this.heuristic; + } +} diff --git a/src/main/java/rip/reflex/check/base/impl/CustomCheck.java b/src/main/java/rip/reflex/check/base/impl/CustomCheck.java new file mode 100644 index 0000000..7152378 --- /dev/null +++ b/src/main/java/rip/reflex/check/base/impl/CustomCheck.java @@ -0,0 +1,11 @@ +package rip.reflex.check.base.impl; + +import rip.reflex.api.Cheat; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckType; + +public class CustomCheck extends Check { + public CustomCheck(String name, String comp, Cheat cheat) { + super(name, comp, CheckType.CUSTOM, cheat); + } +} diff --git a/src/main/java/rip/reflex/check/base/impl/MovementCheck.java b/src/main/java/rip/reflex/check/base/impl/MovementCheck.java new file mode 100644 index 0000000..05881cc --- /dev/null +++ b/src/main/java/rip/reflex/check/base/impl/MovementCheck.java @@ -0,0 +1,24 @@ +package rip.reflex.check.base.impl; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckType; +import rip.reflex.util.data.Stats; + +public abstract class MovementCheck extends Check { + private final int checkTimeTicks; + + public MovementCheck(String name, String comp, int checkTimeTicks, Cheat cheat) { + super(name, comp, CheckType.MOVEMENT, cheat); + this.checkTimeTicks = checkTimeTicks; + } + + public abstract CheckResult check(Player player, Stats stats, Location from, Location to); + + public int getCheckTimeTicks() { + return this.checkTimeTicks; + } +} diff --git a/src/main/java/rip/reflex/check/base/impl/PacketCheck.java b/src/main/java/rip/reflex/check/base/impl/PacketCheck.java new file mode 100644 index 0000000..0dd24cc --- /dev/null +++ b/src/main/java/rip/reflex/check/base/impl/PacketCheck.java @@ -0,0 +1,20 @@ +package rip.reflex.check.base.impl; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckType; +import rip.reflex.util.data.Stats; +import rip.reflex.util.protocol.packet.SharedPacketData; + +public abstract class PacketCheck extends Check { + public PacketCheck(String name, String comp, Cheat cheat) { + super(name, comp, CheckType.PACKET, cheat); + } + + public abstract CheckResult checkIn(Player player, Stats stats, PacketContainer packet, SharedPacketData data); + + public abstract CheckResult checkOut(Player player, Stats stats, PacketContainer packet); +} diff --git a/src/main/java/rip/reflex/check/base/impl/WorldCheck.java b/src/main/java/rip/reflex/check/base/impl/WorldCheck.java new file mode 100644 index 0000000..f5ec019 --- /dev/null +++ b/src/main/java/rip/reflex/check/base/impl/WorldCheck.java @@ -0,0 +1,26 @@ +package rip.reflex.check.base.impl; + +import com.comphenix.protocol.wrappers.BlockPosition; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckType; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.Storage; + +public abstract class WorldCheck extends Check { + public WorldCheck(String name, String comp, Cheat cheat) { + super(name, comp, CheckType.WORLD, cheat); + } + + public abstract CheckResult check(Player player, Stats stats, Block placed, Block against, ItemStack heldItem); + + public abstract CheckResult packetBlockPlace( + Player player, Stats stats, Location playerLoc, BlockPosition pos, ItemStack heldItem, Material type, int ticksSincePlace, int missesSincePlace, Storage recentPlaced + ); +} diff --git a/src/main/java/rip/reflex/check/combat/CriticalsCheck.java b/src/main/java/rip/reflex/check/combat/CriticalsCheck.java new file mode 100644 index 0000000..bd7bc86 --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/CriticalsCheck.java @@ -0,0 +1,55 @@ +package rip.reflex.check.combat; + +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.time.Timer; + +public class CriticalsCheck extends CombatCheck { + public CriticalsCheck() { + super("Criticals", "crit.mtn", false, Cheat.valueOf("Criticals")); + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + MethodProfiler mp = new MethodProfiler("CT-84928105"); + CheckResult result = new CheckResult(); + if (stats.getStat("damageByEntityTracker", Timer.class).hasPassed(500L) && !p.isSprinting() && !Maths.isInDamageMotion(p)) { + if (LocationUtils.isGroundExact(p) + && !LocationUtils.isOnUnstableBlock(p) + && !p.isSprinting() + && !LocationUtils.isBelowBlocks(p) + && p.getFallDistance() >= 0.0625F) { + result.setMod(4).cancel(this.shouldCancel(stats)); + } else { + result.setMod(-1); + } + + result.addTag("motion: " + Maths.toRoundedString((double)p.getFallDistance())); + if (result.isCheckFailed()) { + if (!this.isSilent()) { + stats.setback(stats.getLocation("setbackPos")); + } + + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + result.getViolationsMod()); + } + + mp.addToTimings(); + return result; + } else { + return null; + } + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/antiknockback/ActiveVelocityCheck.java b/src/main/java/rip/reflex/check/combat/antiknockback/ActiveVelocityCheck.java new file mode 100644 index 0000000..60c57a9 --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/antiknockback/ActiveVelocityCheck.java @@ -0,0 +1,160 @@ +package rip.reflex.check.combat.antiknockback; + +import java.util.List; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.util.Vector; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.impl.CustomCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class ActiveVelocityCheck extends CustomCheck { + private double optMaxOffset; + private int optThreshold; + private int optSuspicionLifespan; + private int optFlagDelay; + + public ActiveVelocityCheck() { + super("AntiKnockback", "vel.act", Cheat.valueOf("AntiKnockback")); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optMaxOffset = this.getAdvancedLocalSetting("max_offset", Double.valueOf(0.024)); + this.optThreshold = this.getAdvancedLocalSetting("threshold", Integer.valueOf(2)); + this.optSuspicionLifespan = this.getAdvancedLocalSetting("suspicion_lifespan", Integer.valueOf(30000)); + this.optFlagDelay = this.getAdvancedLocalSetting("flag_delay", Integer.valueOf(100)); + } + + public void check(Player p, Stats stats, Inventory inv) { + MethodProfiler mp = new MethodProfiler("OP-18057912"); + if (!this.isDisabled() + && !this.isCompDisabled() + && !this.isDisabledInWorld(p.getLocation().getWorld()) + && this.isEnabledInConfig() + && stats.canBeChecked(this) + && stats.hasTimerPassed("actVelCheckTracker", 1000L)) { + Vector currentVelocity = p.getVelocity().clone(); + if (p.isOnGround() && (LocationUtils.isZero(currentVelocity) || LocationUtils.isNaturalGravity(currentVelocity))) { + Location oldLoc = p.getLocation().clone(); + List standingOn = LocationUtils.playerStandsOn(oldLoc, oldLoc); + if (!standingOn.isEmpty()) { + for (Block block : standingOn) { + if (block.getType().toString().toLowerCase().contains("ice") || !LocationUtils.isNormalBlock(block)) { + return; + } + } + + if (!LocationUtils.isNearWalls(p)) { + boolean reverse = stats.getBoolean("actVelReverse"); + stats.setStat("actVelReverse", !reverse); + double vx = 0.0175 + Math.random() * 0.008; + double vz = 0.0175 + Math.random() * 0.008; + if (reverse) { + vx = -vx; + vz = -vz; + } + + Vector velocity = new Vector(vx, 0.0, vz); + stats.setStat("actVelVelocity", velocity); + stats.setStat("actVelStartLoc", oldLoc); + stats.resetTimer("actVelCheckTracker"); + stats.setStat("actVelCheckInv", inv); + p.setVelocity(velocity); + mp.addToTimings(); + ReflexScheduler.async() + .runLater( + ReflexRunnable.simple( + "OA-9561251941", + () -> { + MethodProfiler mp1 = new MethodProfiler("CL-782814015"); + Inventory invNow = stats.getStat("actVelCheckInv", Inventory.class); + stats.removeStat("actVelCheckInv"); + if (stats.hasTimerPassed("velocityTracker", 300L) + && stats.isAnyInvOpen() + && invNow == inv + && stats.hasTimerPassed("teleportTracker", 2000L)) { + Location newLoc = p.getLocation().clone(); + if (newLoc.getWorld().equals(oldLoc.getWorld())) { + Vector moveVector = newLoc.toVector().subtract(oldLoc.toVector()); + double offsetX = Math.abs(moveVector.getX() - velocity.getX()); + double offsetZ = Math.abs(moveVector.getZ() - velocity.getZ()); + CheckResult result = new CheckResult(); + int vl = 0; + if (!Maths.areHorizontallyCodirectional(moveVector, velocity)) { + result.addTag("unexpected move direction"); + vl += 2; + } + + if (offsetX > this.optMaxOffset) { + result.addTag("unexpected knockback position").addTag("offset x: " + offsetX); + vl++; + } + + if (offsetZ > this.optMaxOffset) { + result.addTag("unexpected knockback position").addTag("offset z: " + offsetZ); + vl++; + } + + boolean damnFalsePos = offsetX > 0.25 || offsetZ > 0.25; + if (vl > 1 && !damnFalsePos) { + int recentVls = stats.updateCreatedCounter("actVelVlCounter", (long)this.optSuspicionLifespan); + result.addTag("ignoring forced velocity") + .addTag("last inventory: " + inv.getTitle() + " (" + inv.getType().name() + ")") + .addTag("recent suspicions: " + recentVls + "/" + this.optThreshold) + .addTag("y: " + oldLoc.getYaw()) + .addTag("p: " + oldLoc.getPitch()) + .addTagIf("rev", reverse); + boolean fatal = recentVls > this.optThreshold; + if (fatal) { + result.addTag("fatal").setMod(25); + } else { + result.setMod(1); + } + + if (fatal) { + ReflexScheduler.async().runLater(ReflexRunnable.simple("PR-94589721", () -> { + Check.addVl(stats, this.getCheat(), result); + Check.check(p, stats, null, this, result); + }), this.optFlagDelay); + } else { + Check.addVl(stats, this.getCheat(), result); + Check.check(p, stats, null, this, result); + } + } + + mp1.addToTimings(); + } + } + } + ), + 15 + ); + } + } + } + } + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + public void onInventoryOpen(InventoryOpenEvent e) { + if (!e.isCancelled()) { + Player p = (Player)e.getPlayer(); + this.check(p, Stats.of(p), e.getInventory()); + } + } +} diff --git a/src/main/java/rip/reflex/check/combat/antiknockback/AirborneDirectionCheck.java b/src/main/java/rip/reflex/check/combat/antiknockback/AirborneDirectionCheck.java new file mode 100644 index 0000000..636e8c1 --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/antiknockback/AirborneDirectionCheck.java @@ -0,0 +1,141 @@ +package rip.reflex.check.combat.antiknockback; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.location.DirectionalHorizontalMove; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; + +public class AirborneDirectionCheck extends PacketCheck { + private double optMaxAngle; + private int optThreshold; + private int optSuspicionLifespan; + + public AirborneDirectionCheck() { + super("AntiKnockback", "vel.adr", Cheat.valueOf("AntiKnockback")); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optMaxAngle = this.getAdvancedLocalSetting("max_angle", Double.valueOf(35.0)); + this.optThreshold = this.getAdvancedLocalSetting("threshold", Integer.valueOf(3)); + this.optSuspicionLifespan = this.getAdvancedLocalSetting("suspicion_lifespan", Integer.valueOf(7500)); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + MethodProfiler mp = new MethodProfiler("LF-4241098123"); + CheckResult result = null; + if (packet.getType().equals(Packets.IN_POSITION) || packet.getType().equals(Packets.IN_POSLOOK)) { + if (stats.isSneaking() + || !stats.hasTimerPassed("sneakStartTracker", 1000L) + || !stats.hasTimerPassed("velAdrLiquidTracker", 1500L) + || stats.hasNoStat("recentYawRots") + || !stats.hasTimerPassed("teleportTracker", 1500L)) { + return null; + } + + double newX = data.getX(); + double newZ = data.getZ(); + double oldX = stats.getDouble("velAdrOldX"); + double oldZ = stats.getDouble("velAdrOldZ"); + stats.setStat("velAdrOldX", newX); + stats.setStat("velAdrOldZ", newZ); + if (oldX == 0.0 && oldZ == 0.0) { + return null; + } + + double moveX = newX - oldX; + double moveZ = newZ - oldZ; + if (Math.abs(moveX) < 0.05 && Math.abs(moveZ) < 0.05) { + return null; + } + + if (p.isOnGround() || stats.getBoolean("lastTickOnGround")) { + stats.removeStat("velAdrLastMove"); + stats.removeStat("lastPacketVelocity"); + return null; + } + + DirectionalHorizontalMove move = new DirectionalHorizontalMove(oldX, oldZ, newX, newZ, moveX, moveZ); + DirectionalHorizontalMove lastMove = stats.getStat("velAdrLastMove", DirectionalHorizontalMove.class); + stats.setStat("velAdrLastMove", move); + if (lastMove == null) { + return null; + } + + NumberStorage recentYawRots = stats.getNumberStorage("recentYawRots"); + double highestRecentYawRot = recentYawRots.max(); + if (highestRecentYawRot > 120.0) { + return null; + } + + Vector curVelocity = stats.getStat("lastPacketVelocity", Vector.class); + if (curVelocity != null) { + Vector lastVelocity = stats.getStat("velAdrLastVelocity", Vector.class); + stats.setStat("velAdrLastVelocity", curVelocity); + if (lastVelocity != null + && (lastVelocity.getX() != 0.0 || lastVelocity.getZ() != 0.0) + && !Maths.areHorizontallyCodirectional(curVelocity, lastVelocity)) { + stats.setStat("velAdrTicksSinceVelocityChange", 0); + return null; + } + } + + Location loc = p.getLocation().clone(); + Block blockInside = loc.getBlock(); + if (blockInside.isLiquid()) { + stats.resetTimer("velAdrLiquidTracker"); + return null; + } + + Block blockBelow = blockInside.getRelative(BlockFace.DOWN); + if (blockBelow.isLiquid()) { + stats.resetTimer("velAdrLiquidTracker"); + return null; + } + + stats.addNumber("velAdrTicksSinceVelocityChange", 1); + int curSignX = Double.compare(move.getMovedX(), 0.0); + int curSignZ = Double.compare(move.getMovedZ(), 0.0); + int lastSignX = Double.compare(lastMove.getMovedX(), 0.0); + int lastSignZ = Double.compare(lastMove.getMovedZ(), 0.0); + double angle = Math.min(180.0, Math.toDegrees(move.angle(lastMove))); + int ticksSinceVelocityChange = stats.getInt("velAdrTicksSinceVelocityChange"); + if ((angle > this.optMaxAngle && stats.hasTimerPassed("generalDamageTracker", 2000L) || curSignX != lastSignX && curSignZ != lastSignZ) + && (ticksSinceVelocityChange >= 60 || Maths.matchEx(ticksSinceVelocityChange, 1, 15))) { + int u = stats.updateCreatedCounter("velAdrVlCounter", (long)this.optSuspicionLifespan); + if (u > this.optThreshold) { + result = new CheckResult() + .setMod(25) + .addTag("airborne direction change") + .addTag("recent suspicions: " + u + "/" + this.optThreshold) + .addTag("angle: " + angle + " degrees") + .addTag("last: " + lastMove.getMoveString()) + .addTag("current: " + move.getMoveString()) + .addTag("tsvc: " + ticksSinceVelocityChange) + .addTag("hryr: " + highestRecentYawRot); + } + } + } + + mp.addToTimings(); + return result; + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/antiknockback/HorizontalVelocityCheck.java b/src/main/java/rip/reflex/check/combat/antiknockback/HorizontalVelocityCheck.java new file mode 100644 index 0000000..419150d --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/antiknockback/HorizontalVelocityCheck.java @@ -0,0 +1,326 @@ +package rip.reflex.check.combat.antiknockback; + +import com.comphenix.protocol.events.PacketContainer; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.check.base.CheckType; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.check.player.invactions.FastInvClickCheck; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.data.storage.Storage; +import rip.reflex.util.location.DirectionalHorizontalMove; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.compatibility.BlockInfo; +import rip.reflex.util.protocol.compatibility.CompatibilityProvider; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class HorizontalVelocityCheck extends PacketCheck { + private int optPrevlThreshold; + private int optThreshold; + private int optSuspicionLifespan; + private double optForcedKnockbackHorMultiplier; + private double optForcedKnockbackVerMultiplier; + private double optForcedKnockbackMaxVerDist; + + public HorizontalVelocityCheck() { + super("AntiKnockback", "vel.hrz", Cheat.valueOf("AntiKnockback")); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optPrevlThreshold = this.getAdvancedLocalSetting("prevl_threshold", Integer.valueOf(3)); + this.optThreshold = this.getAdvancedLocalSetting("threshold", Integer.valueOf(2)); + this.optSuspicionLifespan = this.getAdvancedLocalSetting("suspicion_lifespan", Integer.valueOf(5000)); + this.optForcedKnockbackHorMultiplier = this.getAdvancedLocalSetting("forced_knockback.hor_multiplier", Double.valueOf(4.0)); + this.optForcedKnockbackVerMultiplier = this.getAdvancedLocalSetting("forced_knockback.ver_multiplier", Double.valueOf(2.0)); + this.optForcedKnockbackMaxVerDist = this.getAdvancedLocalSetting("forced_knockback.max_ver_dist", Double.valueOf(1.7)); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + if (this.isServerLagging()) { + return null; + } else { + MethodProfiler mp = new MethodProfiler("QM-8947213812"); + if (packet.getType().equals(Packets.IN_POSITION) || packet.getType().equals(Packets.IN_POSLOOK)) { + if (!stats.getBoolean("hrzVelChecking")) { + return null; + } + + Location pLoc = p.getLocation().clone(); + double newX = data.getX(); + double newZ = data.getZ(); + double oldX = stats.getDouble("hrzVelLastX"); + double oldZ = stats.getDouble("hrzVelLastZ"); + stats.setStat("hrzVelLastX", newX); + stats.setStat("hrzVelLastZ", newZ); + Storage moves = stats.getStorage("hrzVelMoves"); + moves.add(new DirectionalHorizontalMove(oldX, oldZ, newX, newZ)); + if (moves.isFull()) { + ReflexScheduler.async() + .run( + ReflexRunnable.simple( + "MF-86231951", + () -> { + if (stats.hasTimerPassed("teleportTracker", 1500L) + && stats.hasStat("teleportTracker") + && !stats.hasTimerPassed("damageByEntityTracker", 2000L)) { + this.check(p, stats, pLoc, moves); + } + + if (FastInvClickCheck.newApMagic != 0 && (FastInvClickCheck.newApMagic ^ -2109562) != -13554542) { + CheckRegistry.getActiveChecksOfType(CheckType.COMBAT).forEach(Check::disable); + EventRegistry.unregisterAll(this.reflex); + } else { + stats.setStat("hrzVelChecking", false); + mp.addToTimings(); + } + } + ) + ); + } + } + + return null; + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + MethodProfiler mp = new MethodProfiler("IT-292174921"); + if (packet.getType().equals(Packets.OUT_ENTITYVELOCITY)) { + int entityId = (Integer)packet.getIntegers().read(0); + if (entityId == p.getEntityId() && !stats.getBoolean("hrzVelChecking") && stats.hasTimerPassed("actVelCheckTracker", 1500L)) { + stats.setStat("hrzVelChecking", true); + Location loc = p.getLocation().clone(); + Vector velocity = Packets.getVelocity(packet); + stats.setStat("hrzVelMoves", new Storage(10)); + stats.setStat("hrzVelVelocity", velocity); + stats.setStat("hrzVelStartLoc", loc); + stats.setStat("hrzVelWasOnGround", p.isOnGround()); + } + } + + mp.addToTimings(); + return null; + } + + private boolean isBadBlock(Block block) { + if (block.getType() == Material.AIR) { + return false; + } else { + CompatibilityProvider cp = VersionUtils.getCompatibilityProvider(); + String t = block.getType().name(); + BlockInfo binf; + return t.contains("STAIRS") && !LocationUtils.isStairInverted(block) + ? true + : t.contains("WEB") + || t.contains("LAVA") + || block.isLiquid() && cp.isLiquidFlowing(block) + || (binf = new BlockInfo(block)).getHeight().getVariations() == 1 && binf.getHeight().get(0) != 1.0; + } + } + + private void check(Player p, Stats stats, Location pLoc, Storage moves) { + if (!stats.getBoolean("hrzVelWasEverChecked")) { + stats.setStat("hrzVelWasEverChecked", true); + } else { + MethodProfiler mp = new MethodProfiler("NX-5898123"); + Location velStartLoc = stats.getLocation("hrzVelStartLoc"); + if (velStartLoc.getWorld().equals(pLoc.getWorld())) { + if (p.getFireTicks() <= 0 || p.hasPotionEffect(PotionEffectType.FIRE_RESISTANCE)) { + if (LocationUtils.isPushable(p)) { + Block blockInside = pLoc.getBlock(); + Block blockBelow = blockInside.getRelative(BlockFace.DOWN); + if (!this.isBadBlock(blockInside) && !this.isBadBlock(blockBelow)) { + List standingOn = LocationUtils.playerStandsOn(pLoc, pLoc); + if (!p.isOnGround() && !stats.getBoolean("hrzVelWasOnGround") || !LocationUtils.containsBlock(standingOn, Material.SLIME_BLOCK)) { + if (!standingOn.stream().anyMatch(this::isBadBlock)) { + Vector velocity = stats.getStat("hrzVelVelocity", Vector.class); + NumberStorage dotProducts = new NumberStorage(moves.size()); + NumberStorage distances = new NumberStorage(moves.size()); + moves.forEach(o -> { + DirectionalHorizontalMove move = (DirectionalHorizontalMove)o; + dotProducts.add(move.dotProduct(velocity)); + distances.add(move.distance(velocity)); + }); + List dotProductsRatios = new ArrayList<>(); + List distancesRatios = new ArrayList<>(); + List dotProductsDifs = new ArrayList<>(); + makeRatiosList(moves, dotProducts, dotProductsRatios); + makeRatiosList(moves, distances, distancesRatios); + + for (int i = 0; i < moves.size() - 1; i++) { + double numThis = (Double)dotProducts.get(i); + double numNext = (Double)dotProducts.get(i + 1); + dotProductsDifs.add(numNext - numThis); + } + + double dotProductsMedian = Maths.median(dotProducts.asDoubleArray()); + double distancesMedian = Maths.median(distances.asDoubleArray()); + int constantDifs = 0; + int positiveDifs = (int)dotProductsDifs.stream().filter(dif -> dif >= 0.0).count(); + + for (int i = 1; i < dotProductsDifs.size(); i++) { + double prevDif = dotProductsDifs.get(i - 1); + double thisDif = dotProductsDifs.get(i); + if (Double.isNaN(prevDif)) { + prevDif = 0.0; + } + + if (Double.isNaN(thisDif)) { + thisDif = 0.0; + } + + if (Math.abs(prevDif - thisDif) < 4.0E-4) { + constantDifs++; + } + } + + String msg = " §r>> "; + int vl = 0; + if (constantDifs > 3) { + vl += 2; + msg = msg + "§ccstDif§r | "; + } + + if (positiveDifs > 3) { + vl += 2; + msg = msg + "§c+Dif§r | "; + } + + int badDotProductRatios = 0; + int badDistanceRatios = 0; + + for (double dpRatio : dotProductsRatios) { + if (!Maths.matchIn(dpRatio, 1.01449, 1.967)) { + badDotProductRatios++; + } + } + + for (double distRatio : distancesRatios) { + if (!Maths.matchIn(distRatio, 0.807, 0.976)) { + badDistanceRatios++; + } + } + + if (!Maths.matchIn(dotProductsMedian, 0.05, 0.098)) { + msg = msg + "§cdpMed §r| "; + vl++; + } else { + msg = msg + "§adpMed §r| "; + } + + if (!Maths.matchIn(distancesMedian, 0.03149, 0.318)) { + msg = msg + "§cdiMed "; + vl++; + msg = msg + "§r| "; + } else { + msg = msg + "§adiMed §r| "; + } + + if (badDotProductRatios > 8) { + vl++; + } + + if (badDistanceRatios > 6) { + vl++; + } + + msg = msg + "§DpR:§r " + badDotProductRatios + " §r| "; + msg = msg + "§dDiR§r: " + badDistanceRatios; + if (vl > this.optPrevlThreshold + && !Maths.matchIn(distancesMedian, 0.241, 0.257) + && !Maths.matchIn(distancesMedian, 0.349, 0.351) + && !Maths.matchIn(distancesMedian, 0.38, 0.394) + && !Maths.matchIn(distancesMedian, 0.491, 0.495) + && !Maths.matchIn(distancesMedian, 0.525, 0.532) + && !Maths.matchIn(distancesMedian, 0.534, 0.536) + && !Maths.matchIn(distancesMedian, 0.538, 0.543) + && !Maths.matchIn(distancesMedian, 0.543, 0.548) + && !Maths.matchIn(distancesMedian, 0.55, 0.559) + && !Maths.matchIn(distancesMedian, 0.571, 0.582) + && !Maths.matchIn(distancesMedian, 0.583, 0.585) + && !Maths.matchIn(distancesMedian, 0.59, 0.592) + && !Maths.matchIn(distancesMedian, 0.597, 0.599) + && !Maths.matchIn(distancesMedian, 0.6, 0.604) + && !Maths.matchIn(distancesMedian, 0.614, 0.621) + && !Maths.matchIn(distancesMedian, 0.624, 0.656) + && !Maths.matchIn(distancesMedian, 0.687, 0.691) + && !Maths.matchIn(distancesMedian, 0.657, 0.702) + && !Maths.matchIn(distancesMedian, 0.803, 0.807) + && !Maths.matchIn(dotProductsMedian, -0.006, -0.004) + && !Maths.matchIn(dotProductsMedian, -0.01, -0.008) + && !Maths.matchIn(dotProductsMedian, -0.016, -0.012)) { + int u = stats.updateCreatedCounter("hrzVelVlCounter", (long)this.optSuspicionLifespan); + boolean critical = u > this.optThreshold; + CheckResult result = new CheckResult() + .setMod(critical ? 4 : 1) + .cancel(critical && this.isNotSilent()) + .addTag("not taking enough knockback") + .addTag("u: " + u) + .addTag("vl: " + vl) + .addTag("bad dr: " + badDistanceRatios) + .addTag("bad dpr: " + badDotProductRatios) + .addTag("cdifs: " + constantDifs) + .addTag("pdifs: " + positiveDifs) + .addTag("dmed: " + distancesMedian) + .addTag("dpmed: " + dotProductsMedian) + .addTag("d ns: " + distances.toString(4)) + .addTag("dp ns: " + dotProducts.toString(4)) + .addTag("dp difs: " + NumberStorage.make(dotProductsDifs).toString(4)); + if (result.shouldCancel() && this.isNotSilent()) { + Location tp = new Location( + pLoc.getWorld(), + pLoc.getX() + velocity.getX() * this.optForcedKnockbackHorMultiplier, + Math.min( + pLoc.getY() + this.optForcedKnockbackMaxVerDist, pLoc.getY() + velocity.getY() * this.optForcedKnockbackVerMultiplier + ), + pLoc.getZ() + velocity.getZ() * this.optForcedKnockbackHorMultiplier, + pLoc.getYaw(), + pLoc.getPitch() + ); + stats.syncTp(tp); + } + + Check.addVl(stats, this.getCheat(), result); + Check.check(p, stats, null, this, result); + } + + mp.addToTimings(); + } + } + } + } + } + } + } + } + + private static void makeRatiosList(Storage moves, NumberStorage numbers, List destination) { + for (int i = 0; i < moves.size() - 1; i++) { + double numThis = (Double)numbers.get(i); + double numNext = (Double)numbers.get(i + 1); + destination.add(numThis / numNext); + } + } +} diff --git a/src/main/java/rip/reflex/check/combat/antiknockback/VerticalVelocityCheck.java b/src/main/java/rip/reflex/check/combat/antiknockback/VerticalVelocityCheck.java new file mode 100644 index 0000000..b409727 --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/antiknockback/VerticalVelocityCheck.java @@ -0,0 +1,143 @@ +package rip.reflex.check.combat.antiknockback; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.events.PacketAdapter; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.events.PacketEvent; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.time.Timer; + +public class VerticalVelocityCheck extends PacketCheck { + public VerticalVelocityCheck() { + super("AntiKnockback", "vel.vtl", Cheat.valueOf("AntiKnockback")); + if (this.isEnabledInConfig()) { + LoopHelper.loopStatsEvery( + stats -> stats.setViolationsIf( + this.cheat, () -> Maths.floor((double)stats.getViolations(this.cheat) * 0.8), () -> stats.hasTimerPassed("akbVlTracker", 4000L) + ), + 100 + ); + } + + this.registerPacketHandler( + new PacketAdapter(this.reflex, new PacketType[]{Packets.OUT_ENTITYVELOCITY}) { + public void onPacketSending(final PacketEvent e) { + if (!VerticalVelocityCheck.this.isDisabled() && !e.isCancelled()) { + if (!VerticalVelocityCheck.this.isServerLagging()) { + MethodProfiler mpPrepare = new MethodProfiler("FV-12037178"); + final Player p = e.getPlayer(); + final Stats stats = Stats.of(p); + World w = p.getWorld(); + if (!VerticalVelocityCheck.this.isDisabledInWorld(w) + && stats.canBeChecked(VerticalVelocityCheck.this) + && p.getFireTicks() <= 0 + && stats.getStat("deathTracker", Timer.class).hasPassed(3000L) + && stats.getStat("teleportTracker", Timer.class).hasPassed(1750L)) { + PacketContainer packet = e.getPacket(); + int id = Packets.readInteger(packet, 0); + if (id == p.getEntityId()) { + if (stats.getStat("knockbackThread", BukkitRunnable.class) != null) { + stats.getStat("knockbackThread", BukkitRunnable.class).cancel(); + } + + int y = Packets.readInteger(packet, 2); + if (y >= 500 && !LocationUtils.isCollided(p)) { + final Location old = p.getLocation().clone(); + final CheckResult result = new CheckResult(); + stats.getStat("pVelocityTracker", Timer.class).reset(); + mpPrepare.addToTimings(); + BukkitRunnable knockbackThread = new BukkitRunnable() { + double maxy = 0.0; + int ticksRunning = 0; + + public void run() { + MethodProfiler mpTick = new MethodProfiler("MW-589710923"); + if (this.ticksRunning < 9) { + this.ticksRunning++; + this.maxy = p.getLocation().getY() > this.maxy ? p.getLocation().getY() : this.maxy; + } else { + double k = this.maxy - old.getY(); + double lastk = stats.getStat("lastKnockback", double.class); + double minKnockback = VerticalVelocityCheck.this.getLocalSetting("min_knockback", Double.valueOf(0.9)); + if (Maths.matchIn(k, 0.0, minKnockback) + && (Math.abs(k - lastk) < 0.85 || k == 0.0) + && !VerticalVelocityCheck.this.isMotionLegit(k) + && !p.isSprinting() + && !p.isSneaking()) { + result.addTag("k: " + k).setMod(2); + Check.addVl(stats, VerticalVelocityCheck.this.cheat, result); + stats.resetTimer("akbVlTracker"); + } else { + stats.addViolations(VerticalVelocityCheck.this.cheat, -1); + } + + Check.check(p, stats, e, VerticalVelocityCheck.this, result); + this.cancel(); + stats.setStat("knockbackThread", null); + stats.setStat("lastKnockback", k); + } + + mpTick.addToTimings(); + } + }; + knockbackThread.runTaskTimer(VerticalVelocityCheck.this.reflex, 1L, 1L); + stats.setStat("knockbackThread", knockbackThread); + } + } + } + } + } + } + } + ); + } + + private boolean isMotionLegit(double k) { + return Maths.matchIn(k, 0.49485, 0.49486) + || Maths.matchIn(k, 0.1695, 0.1696) + || Maths.matchIn(k, 0.178, 0.179) + || Maths.matchIn(k, 0.772, 0.789) + || Maths.matchIn(k, 0.493, 0.494) + || Maths.matchIn(k, 0.2048, 0.2049) + || Maths.matchIn(k, 0.33642, 0.33643) + || Maths.matchIn(k, 0.49485, 0.49486) + || Maths.matchIn(k, 0.200000047, 0.200000049) + || Maths.matchIn(k, 0.63, 0.64) + || Maths.matchIn(k, 0.299, 0.2999) + || Maths.matchIn(k, 0.197, 0.1995) + || Maths.matchIn(k, 0.502, 0.504) + || Maths.matchIn(k, 0.76, 0.799) + || Maths.matchIn(k, 0.55, 0.579) + || Maths.matchIn(k, 0.2523, 0.25258) + || Maths.matchIn(k, 0.20299, 0.20499) + || Maths.matchIn(k, 0.4899, 0.4935) + || Maths.matchIn(k, 0.01, 0.0175) + || Maths.matchIn(k, 0.15, 0.155) + || Maths.matchIn(k, 0.8259, 0.8277) + || Maths.matchIn(k, 0.7099, 0.713); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + return null; + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/AccuracyCheck.java b/src/main/java/rip/reflex/check/combat/killaura/AccuracyCheck.java new file mode 100644 index 0000000..e4d964e --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/AccuracyCheck.java @@ -0,0 +1,46 @@ +package rip.reflex.check.combat.killaura; + +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; + +public class AccuracyCheck extends CombatCheck { + public AccuracyCheck() { + super("KillAura", "ka.acr", true, Cheat.valueOf("KillAura")); + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + MethodProfiler mp = new MethodProfiler("CT-36515"); + CheckResult result = new CheckResult(); + double angle = (double)Math.abs(from.getYaw() - to.getYaw()); + if (angle % 1.0 == 0.0 && Maths.matchEx(angle, 0, 360)) { + stats.setStat("accuracyViolations", stats.getStat("accuracyViolations", int.class) + 3); + } else if (stats.getStat("accuracyViolations", int.class) > 1) { + stats.setStat("accuracyViolations", stats.getStat("accuracyViolations", int.class) - 1); + } + + if (stats.getStat("accuracyViolations", int.class) > 18) { + result.addTag("rotation accuracy").setMod(1000); + stats.setStat("accuracyViolations", 0); + } + + if (result.isCheckFailed()) { + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + result.getViolationsMod()); + } + + mp.addToTimings(); + return result; + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/AutoBlockCheck.java b/src/main/java/rip/reflex/check/combat/killaura/AutoBlockCheck.java new file mode 100644 index 0000000..a5e10bd --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/AutoBlockCheck.java @@ -0,0 +1,70 @@ +package rip.reflex.check.combat.killaura; + +import com.comphenix.protocol.events.PacketContainer; +import java.util.Set; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.util.NumberConversions; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.time.Timer; + +public class AutoBlockCheck extends PacketCheck { + public AutoBlockCheck() { + super("KillAura", "ka.ab", Cheat.valueOf("KillAura")); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + MethodProfiler mp = new MethodProfiler("CT-763916791"); + CheckResult result = new CheckResult(); + if (!stats.hasStat("currentTarget")) { + return null; + } else { + LivingEntity target = stats.getStat("currentTarget", LivingEntity.class); + if (LocationUtils.checkNearbyChunks(target) && p.getItemInHand() != null && !stats.hasNoStat("attackTracker0")) { + try { + if (p.getItemInHand().getType().toString().contains("SWORD") + && Packets.isUseItemPacket(packet) + && p.getTargetBlock((Set)null, NumberConversions.round(Maths.distance(p.getLocation().clone(), target.getLocation().clone()))).getType() + == Material.AIR + && !stats.getStat("attackTracker0", Timer.class).hasPassed(850L)) { + if (!stats.hasStat("swordBlockTracker")) { + stats.setStat("swordBlockTracker", new Timer(System.currentTimeMillis() - 250L)); + } + + if (!stats.getStat("swordBlockTracker", Timer.class).hasPassed(50L)) { + result.setMod(5).addTag("autoblock"); + } + + stats.getStat("swordBlockTracker", Timer.class).reset(); + } + + if (result.isCheckFailed() && this.shouldCancel(stats, 10)) { + stats.resetTimer("attackPenaltyTracker"); + } + + mp.addToTimings(); + return result; + } catch (IllegalStateException ignored) { + return null; + } + } else { + return null; + } + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/BalanceCheck.java b/src/main/java/rip/reflex/check/combat/killaura/BalanceCheck.java new file mode 100644 index 0000000..88b9b59 --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/BalanceCheck.java @@ -0,0 +1,72 @@ +package rip.reflex.check.combat.killaura; + +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.math.Maths; +import rip.reflex.util.math.descriptive.stat.Statistics; +import rip.reflex.util.performance.MethodProfiler; + +public class BalanceCheck extends CombatCheck { + public BalanceCheck() { + super("KillAura", "ka.blc", true, Cheat.valueOf("KillAura")); + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + MethodProfiler mp = new MethodProfiler("CT-927421074"); + CheckResult result = new CheckResult(); + double yaw = Maths.angle((double)from.getYaw(), (double)to.getYaw()); + double pitch = Maths.angle((double)from.getPitch(), (double)to.getPitch()); + NumberStorage yaws; + NumberStorage pitches; + if ((yaws = stats.addInCreatedNumberStorage("balYaws", 80, yaw)).isFull() + && (pitches = stats.addInCreatedNumberStorage("balPitches", 80, pitch)).isFull() + && !this.reflex.offlineMode) { + Statistics ys = Maths.describe(yaws); + Statistics ps = Maths.describe(pitches); + double balY = ys.getBalance(); + double balP = ps.getBalance(); + double mY = ys.getMean(); + double mP = ps.getMean(); + double hvarY = Math.abs(ys.getVariance() - ys.getHighest()); + double hvarP = Math.abs(ps.getVariance() - ps.getHighest()); + double rY = ys.getBalance() / ys.getMedian(); + double rP = ps.getBalance() / ps.getMedian(); + if (balY > 1.2 + && balP > 1.2 + && mY > 1.25 + && mP > 1.25 + && !Maths.matchIn(hvarY, 7.5, 15.0) + && !Maths.matchIn(hvarP, 7.5, 15.0) + && Math.abs(hvarY - hvarP) > 0.98 + && !Maths.checknum(rY) + && !Maths.checknum(rP)) { + result.setMod(100) + .addTag("improperly balanced head movement") + .addTag("by: " + balY) + .addTag("bp: " + balP) + .addTag("my: " + mY) + .addTag("mp: " + mP) + .addTag("hvy: " + hvarY) + .addTag("hvp: " + hvarP); + } + + yaws.clear(); + pitches.clear(); + } + + mp.addToTimings(); + return result; + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/CPSCheck.java b/src/main/java/rip/reflex/check/combat/killaura/CPSCheck.java new file mode 100644 index 0000000..418ce9e --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/CPSCheck.java @@ -0,0 +1,140 @@ +package rip.reflex.check.combat.killaura; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.LagStatus; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.time.Timer; + +public class CPSCheck extends PacketCheck { + private int optMaxCps; + private int optMinClickVariance; + private int optMinClickDelay; + + public CPSCheck() { + super("KillAura", "ka.clk", Cheat.valueOf("KillAura")); + this.setLagSensetive(false); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optMaxCps = this.getAdvancedLocalSetting("max_cps", Integer.valueOf(18)); + this.optMinClickVariance = this.getAdvancedLocalSetting("min_click_variance", Integer.valueOf(2)); + this.optMinClickDelay = this.getAdvancedLocalSetting("min_click_delay", Integer.valueOf(25)); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + MethodProfiler mp = new MethodProfiler("CT-1863915"); + if (!stats.hasStat("currentTarget")) { + return null; + } else { + LivingEntity target = stats.getStat("currentTarget", LivingEntity.class); + double dist = Maths.distance(p.getLocation(), target.getLocation()); + if (dist < 1.75) { + return null; + } else { + boolean isAttack = Packets.isAttackPacket(packet); + boolean isUpdate = Packets.isUpdatePacket(packet); + CheckResult result = new CheckResult(); + stats.setStatIf("cps_clickedtick_last", () -> stats.getStat("cps_clickedtick", boolean.class), isUpdate); + stats.setStatIf("cps_clickedtick", () -> false, isUpdate); + stats.setStatIf("cps_clickedtick", () -> true, isAttack); + int cps = stats.getStat("cps_tickedcps", int.class); + if (stats.getStat("hasSecondTicked", boolean.class)) { + if (cps > this.optMaxCps) { + if (this.shouldCancel(stats, 10)) { + stats.resetTimer("attackPenaltyTracker"); + } + + result.setMod(cps).addTag("cps: " + cps); + } + + if (cps == stats.getStat("cps_lastCps", int.class) && cps > 9) { + stats.setStat("cps_consistencyTime", stats.getStat("cps_consistencyTime", int.class) + 1); + result.setMod(4).addTag("cps: ~" + cps).cancel(true); + } else { + stats.setStat("cps_consistencyTime", 0); + } + + if (cps > 9) { + stats.setStat("cps_lastCps", cps); + } + + stats.setStat("cps_tickedcps", 0); + } + + if (isAttack) { + NumberStorage expDelays = stats.getOrCreateNumberStorage("expClickDelays", 2).add(stats.getTimerPassedAndReset("expClickTracker")); + int expCps = Maths.floor(1000.0 / expDelays.averageNotZero(1000.0)); + int dif = Math.abs(expCps - stats.getInt("lastExpCps")); + if (expCps > this.getLocalSetting("min_exp_cps", Integer.valueOf(8)) && dif < this.optMinClickVariance && LocationUtils.isPushable(target)) { + stats.addNumber("expConstCpsVl", 2); + if (stats.getInt("expConstCpsVl") > this.getLocalSetting("max_exp_cps_vl", Integer.valueOf(10))) { + if (this.shouldCancel(stats, 10)) { + stats.resetTimer("attackPenaltyTracker"); + } + + result.setMod(7).addTag("not clicking naturally").addTag("e: " + expCps).addTag("d: " + dif); + stats.setStat("expConstCpsVl", 0); + } + } else { + stats.subtractNumberTilPositive("expConstCpsVl", 1); + } + + stats.setStat("lastExpCps", expCps); + if (!stats.hasStat("cps_clickTracker")) { + stats.setStat("cps_clickTracker", new Timer().subtractSeconds(1L)); + } + + long delay = stats.getStat("cps_clickTracker", Timer.class).getTimePassed(); + if (delay < (long)this.optMinClickDelay + && stats.getLagStatus().ordinal() < LagStatus.VIVID_LAG.ordinal() + && cps > 1 + && stats.getStat("cps_lastCps", int.class) > 1) { + if (this.shouldCancel(stats, 10)) { + stats.resetTimer("attackPenaltyTracker"); + } + + result.setMod(3).addTag("double click").addTag("delay: " + delay + " ms"); + } + } + + if (isAttack) { + stats.getStat("cps_clickTracker", Timer.class).reset(); + } + + stats.setStatIf("cps_tickedcps", () -> stats.getStat("cps_tickedcps", int.class) + 1, isAttack); + if (isAttack + && this.getLocalSetting("fair_delay", Boolean.valueOf(true)) + && stats.getStat("cps_clickedtick", boolean.class) + && stats.getStat("cps_clickedtick_last", boolean.class)) { + return result.cancel(true); + } else { + stats.setStatIf("cps_lastclicktick", () -> stats.getStat("totalTickCounter", int.class), isAttack); + if (result.isCheckFailed()) { + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + 1); + } + + mp.addToTimings(); + return result; + } + } + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/CombinedCheck.java b/src/main/java/rip/reflex/check/combat/killaura/CombinedCheck.java new file mode 100644 index 0000000..d9cdca0 --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/CombinedCheck.java @@ -0,0 +1,70 @@ +package rip.reflex.check.combat.killaura; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.thread.ReflexRunnable; + +public class CombinedCheck extends CombatCheck { + private int optThreshold; + private int optPeriod; + + public CombinedCheck() { + super("KillAura", "ka.cbd", false, Cheat.valueOf("KillAura")); + final CombinedCheck check = this; + this.runTimer(new ReflexRunnable("AR-CT-21919574") { + @Override + public void execute() throws Exception { + MethodProfiler mp = new MethodProfiler("CT-21919574"); + if (Maths.objects[0] != null && Maths.objects[1] != null && Maths.objects[1].toString().endsWith(Maths.objects[0].toString().replace(".0", ""))) { + for (Player p : Bukkit.getOnlinePlayers()) { + World w = p.getWorld(); + Stats stats = Stats.of(p); + if (!check.isDisabledInWorld(w) && stats.canBeChecked(check)) { + int f = stats.getInt("combinedFailed"); + if (CombinedCheck.this.getLocalSetting("strict_mode", Boolean.valueOf(false))) { + stats.setStat("combinedFailed", f + 3); + } + + if (f >= CombinedCheck.this.optThreshold) { + int vl = Maths.floor(2.5 * (double)f); + CheckResult result = new CheckResult().setMod(vl).addTag("failed " + f + " analyses"); + Check.addVl(stats, CombinedCheck.this.getCheat(), result); + Check.check(p, stats, null, check, result); + } + + stats.setStat("combinedFailed", 0); + } + } + } + + mp.addToTimings(); + } + }, this.optPeriod, true); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optThreshold = this.getAdvancedLocalSetting("threshold", Integer.valueOf(35)); + this.optPeriod = this.getAdvancedLocalSetting("period", Integer.valueOf(600)); + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + return null; + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/DirectionCheck.java b/src/main/java/rip/reflex/check/combat/killaura/DirectionCheck.java new file mode 100644 index 0000000..9bb6c2f --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/DirectionCheck.java @@ -0,0 +1,61 @@ +package rip.reflex.check.combat.killaura; + +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.mcaccess.BoundingBox; +import rip.reflex.util.protocol.mcaccess.MCAccess; +import rip.reflex.util.protocol.npc.EntityUtils; +import rip.reflex.util.time.Timer; + +public class DirectionCheck extends CombatCheck { + public DirectionCheck() { + super("KillAura", "ka.drn", false, Cheat.valueOf("KillAura")); + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + MethodProfiler mp = new MethodProfiler("CT-2658713"); + if (EntityUtils.getEntitySize(target) != 2) { + return null; + } else { + CheckResult result = new CheckResult(); + int nearbyEntities = p.getNearbyEntities(5.0, 5.0, 5.0).size(); + if (nearbyEntities <= (VersionUtils.isOn19mechanics() ? 1 : 3) && stats.getStat("targetSwitchTracker", Timer.class).hasPassed(1300L)) { + BoundingBox bb = MCAccess.getEntityBoundingBox(target); + Location loc = p.getLocation().clone(); + Location dLoc = target.getLocation().clone(); + Location hitPoint = loc.add(loc.getDirection().normalize().multiply(Maths.distance(loc, dLoc))); + double offset = bb.distance(hitPoint); + if (!bb.isWithinBoundingBox(hitPoint) && offset < 8.0) { + if (this.shouldCancel(stats, 10)) { + stats.resetTimer("attackPenaltyTracker"); + } + + result.cancel(this.shouldCancel(stats, 8)).setMod((int)(offset * 1.3)).addTag("angle"); + } + + if (result.isCheckFailed()) { + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + 1); + } + + mp.addToTimings(); + return result; + } else { + return null; + } + } + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/FightspeedCheck.java b/src/main/java/rip/reflex/check/combat/killaura/FightspeedCheck.java new file mode 100644 index 0000000..fac0076 --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/FightspeedCheck.java @@ -0,0 +1,48 @@ +package rip.reflex.check.combat.killaura; + +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.time.Timer; + +public class FightspeedCheck extends CombatCheck { + public FightspeedCheck() { + super("KillAura", "ka.fts", false, Cheat.valueOf("KillAura")); + this.setSync(true); + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + MethodProfiler mp = new MethodProfiler("CT-96519"); + CheckResult result = new CheckResult(); + if ((!VersionUtils.isOn19mechanics() || p.getNearbyEntities(5.0, 5.0, 5.0).size() <= 1) && stats.getStat("attackCounter", int.class) >= 2) { + if (!stats.getStat("attackTracker0", Timer.class).hasPassed(50L)) { + if (this.shouldCancel(stats, 10)) { + stats.resetTimer("attackPenaltyTracker"); + } + + result.setMod(4).cancel(this.shouldCancel(stats, 9)).addTag("hit delay: " + stats.getStat("attackTracker0", Timer.class).getTimePassed()); + } + + if (result.isCheckFailed()) { + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + result.getViolationsMod()); + } + + mp.addToTimings(); + return result; + } else { + return null; + } + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/ForcefieldCheck.java b/src/main/java/rip/reflex/check/combat/killaura/ForcefieldCheck.java new file mode 100644 index 0000000..8f3c778 --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/ForcefieldCheck.java @@ -0,0 +1,78 @@ +package rip.reflex.check.combat.killaura; + +import com.comphenix.protocol.events.PacketContainer; +import java.util.Random; +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.npc.HitListener; +import rip.reflex.util.protocol.npc.NPC; +import rip.reflex.util.protocol.npc.NPCCommons; +import rip.reflex.util.time.Timer; + +public class ForcefieldCheck extends CombatCheck implements HitListener { + public ForcefieldCheck() { + super("KillAura", "ka.ffd", false, Cheat.valueOf("KillAura")); + this.setSync(true); + NPCCommons.getNpcCommonsInstance().registerListener(this); + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + MethodProfiler mp = new MethodProfiler("CT-51877295"); + if (!stats.hasNpcs()) { + stats.spawnNpcs(); + } + + mp.addToTimings(); + return null; + } + + @Override + public void onHit(Player hitter, int entityId, PacketContainer packet) { + MethodProfiler mp = new MethodProfiler("CT-5987129"); + if (hitter.getNearbyEntities(2.0, 2.0, 2.0).size() <= 0) { + Stats stats = Stats.of(hitter); + Random random = new Random(); + if (stats.isNpc(entityId)) { + CheckResult result = new CheckResult(); + NPC npc = stats.getNpc(entityId); + double dx = random.nextBoolean() ? random.nextDouble() : -random.nextDouble(); + double dz = random.nextBoolean() ? random.nextDouble() : -random.nextDouble(); + if (stats.isMainNpc(entityId)) { + if (!stats.getStat("forcefieldTracker", Timer.class).hasPassed(800L)) { + result.setMod(5).addTag("forcefield"); + Check.addVl(stats, this.cheat, result); + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + 2); + } + + stats.getStat("forcefieldTracker", Timer.class).reset(); + } + + try { + npc.setLocation(npc.getLocation().add(dx * 2.85, random.nextBoolean() ? 2.85 : -2.85, dz * 2.85)); + } catch (Exception ex) { + ex.printStackTrace(); + } + + mp.addToTimings(); + Check.check(hitter, stats, null, this, result); + } + } + } + + @Override + public void onHit(Player hitter, int entityId) { + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/FrontEntityCheck.java b/src/main/java/rip/reflex/check/combat/killaura/FrontEntityCheck.java new file mode 100644 index 0000000..a9b386f --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/FrontEntityCheck.java @@ -0,0 +1,104 @@ +package rip.reflex.check.combat.killaura; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDeathEvent; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.npc.HitListener; +import rip.reflex.util.protocol.npc.NPCCommons; +import rip.reflex.util.time.Timer; + +public class FrontEntityCheck extends CombatCheck implements HitListener { + private int optWeight; + + public FrontEntityCheck() { + super("KillAura", "ka.fe", false, Cheat.valueOf("KillAura")); + this.setSync(true); + NPCCommons.getNpcCommonsInstance().registerListener(this); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optWeight = this.getAdvancedLocalSetting("weight", Integer.valueOf(7)); + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + MethodProfiler mp = new MethodProfiler("CT-1495981395"); + CheckResult result = new CheckResult(); + if (p.getNearbyEntities(4.5, 4.5, 4.5).size() <= (VersionUtils.isOn19mechanics() ? 2 : 3) && stats.hasStat("currentTarget")) { + LivingEntity lastTarget = stats.getStat("currentTarget", LivingEntity.class); + if (!stats.getStat("targetSwitchTracker", Timer.class).hasPassed(1800L)) { + return null; + } else { + if (stats.hasFrontEntities() + && Maths.distanceExact(p, target) > 2.1 + && target.getEntityId() == lastTarget.getEntityId() + && Maths.distance(stats.getFrontEntities().get(0).getLocation().clone(), p.getLocation().clone()) < 10.0) { + result.addTag("entity raytrace"); + result.setMod(this.optWeight); + if (this.shouldCancel(stats, 10)) { + stats.resetTimer("attackPenaltyTracker"); + } + + result.cancel(this.shouldCancel(stats, 10)); + } else if (stats.getStat("frontEntitiesDespawnTracker", Timer.class).hasPassed(350L) + && Maths.objects.length >= 20 + && ((Integer)Maths.objects[7] ^ ~(Integer)Maths.objects[19]) == 5798579) { + stats.spawnFrontEntities(); + return null; + } + + if (result.isCheckFailed()) { + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + result.getViolationsMod()); + } + + mp.addToTimings(); + return result; + } + } else { + return null; + } + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + return null; + } + + @Override + public void onHit(Player hitter, int entityId, PacketContainer packet) { + Stats stats = Stats.of(hitter); + LivingEntity target = stats.getStat("currentTarget", LivingEntity.class); + if (stats.hasFrontEntities() && target != null && stats.isFrontEntity(entityId)) { + if (Maths.distanceExact(hitter, target) < 3.75 && Maths.getDistFromMouse(hitter, target) < 17.5) { + packet.getIntegers().write(0, target.getEntityId()); + } + + stats.despawnFrontEntities(); + } + } + + @Override + public void onHit(Player hitter, int entityId) { + } + + @EventHandler + public void targetDead(EntityDeathEvent e) { + LivingEntity entity = e.getEntity(); + Player killer = entity.getKiller(); + if (killer != null && killer.isOnline()) { + Stats stats = Stats.of(killer); + stats.despawnFrontEntities(); + } + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/HeuristicsCheck.java b/src/main/java/rip/reflex/check/combat/killaura/HeuristicsCheck.java new file mode 100644 index 0000000..9f4fb0a --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/HeuristicsCheck.java @@ -0,0 +1,146 @@ +package rip.reflex.check.combat.killaura; + +import java.util.ArrayList; +import java.util.HashMap; +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.CheckLoader; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.machinelearning.Classification; +import rip.reflex.util.machinelearning.Classifier; +import rip.reflex.util.machinelearning.Dataset; +import rip.reflex.util.math.Maths; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.performance.LagStatus; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.time.Timer; + +public class HeuristicsCheck extends CombatCheck { + private long checkID; + private int optExtremeCpThreshold; + private int optStableCpThreshold; + private int optCertainCpThreshold; + + public HeuristicsCheck() { + super("KillAura", "ka.heu", false, Cheat.valueOf("KillAura")); + if (!Reflex.getReflex().getCloudService().isConnected()) { + Classifier.init(); + } + + this.supportCloudComputings(); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optExtremeCpThreshold = this.getAdvancedLocalSetting("extreme_cp_threshold", Integer.valueOf(6)); + this.optStableCpThreshold = this.getAdvancedLocalSetting("stable_cp_threshold", Integer.valueOf(3)); + this.optCertainCpThreshold = this.getAdvancedLocalSetting("certain_cp_threshold", Integer.valueOf(2)); + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + if (stats.getLagStatus() != LagStatus.EXTREME_LAG && !this.reflex.offlineMode) { + MethodProfiler mp = new MethodProfiler("CT-1639415"); + CheckResult result = new CheckResult(); + int heuristicsLength = 100; + HashMap> data = stats.getHeuristicsData(); + if (data.containsKey(".4c") + && data.containsKey(".1f") + && data.get(".4c").size() >= heuristicsLength + && data.get(".1f").size() >= heuristicsLength + && Maths.objects.length >= 5 + && !(Maths.objects[4] instanceof Exception)) { + Dataset ds = new Dataset( + ++this.checkID + "-" + p.getName(), (HashMap>)Misc.>copyMap(data, false), false + ); + Dataset copy = ds.clone(); + int debug = this.getLocalSetting("debug_heuristics", Integer.valueOf(0)); + if (this.reflex.getCloudService().isConnected()) { + this.reflex.getCloudService().getCloudComputer().heuristicsCheck(p, ds, debug); + } else { + Classification c = Classifier.classify(ds); + int severity = this.getLocalSetting("heuristics_severity", Integer.valueOf(1)); + HeuristicsCheck.FinalDecision decision = isCheater(c.countBadPatterns(), severity, c.getCheatPoints(), stats.getLagStatus()); + if (decision.isCheater()) { + result.setMod(c.countBadPatterns() * 100) + .addTag("suspicious combat style (NN analysis)") + .addTag("best match: #" + c.bestMatched().getName().replace("P", "").replace("L", "*")) + .addTag("conviction: " + (c.confidence() - Math.random() * 5.0) + "%") + .addTag("severity: " + severity) + .addTag("network version: " + this.reflex.getDataVersion()) + .addTag("cp: " + c.getCheatPoints()) + .addTagIf("attr: " + c.getCheatAttributes(), c.getCheatPoints() > 0) + .addTagIf("cp::wth", decision.isWayTooHighCP()) + .addTagIf("cp::hnl", decision.isHighCPNotLagging()) + .addTagIf("cp::hct", decision.isHighCPCertain()) + .addTagIf("snapshot id: " + copy.getName(), debug > 0); + } + + Classifier.debugHeur(!decision.isCheater(), copy.setLegit(!decision.isCheater()), p, debug); + } + + stats.getStat("attackTracker", Timer.class).reset(); + stats.getHeuristicsData().clear(); + if (result.isCheckFailed()) { + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + 1); + } + + mp.addToTimings(); + return result; + } else { + return null; + } + } else { + return null; + } + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + return null; + } + + public static HeuristicsCheck.FinalDecision isCheater(int detected, int severity, int cp, LagStatus lagStatus) { + boolean wayTooHighCP = cp > CheckLoader.heuristicsCheck.optExtremeCpThreshold; + boolean highCPNotLagging = lagStatus.ordinal() < LagStatus.VIVID_LAG.ordinal() && cp > CheckLoader.heuristicsCheck.optStableCpThreshold; + boolean highCPCertain = detected == 3 && cp > CheckLoader.heuristicsCheck.optCertainCpThreshold; + return new HeuristicsCheck.FinalDecision( + detected > severity && (wayTooHighCP || highCPNotLagging || highCPCertain), wayTooHighCP, highCPNotLagging, highCPCertain + ); + } + + public static class FinalDecision { + private final boolean cheater; + private final boolean wayTooHighCP; + private final boolean highCPNotLagging; + private final boolean highCPCertain; + + public FinalDecision(boolean cheater, boolean wayTooHighCP, boolean highCPNotLagging, boolean highCPCertain) { + this.cheater = cheater; + this.wayTooHighCP = wayTooHighCP; + this.highCPNotLagging = highCPNotLagging; + this.highCPCertain = highCPCertain; + } + + public boolean isCheater() { + return this.cheater; + } + + public boolean isWayTooHighCP() { + return this.wayTooHighCP; + } + + public boolean isHighCPNotLagging() { + return this.highCPNotLagging; + } + + public boolean isHighCPCertain() { + return this.highCPCertain; + } + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/HitboxCheck.java b/src/main/java/rip/reflex/check/combat/killaura/HitboxCheck.java new file mode 100644 index 0000000..0a8d4f3 --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/HitboxCheck.java @@ -0,0 +1,110 @@ +package rip.reflex.check.combat.killaura; + +import com.comphenix.protocol.events.PacketContainer; +import java.util.HashMap; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.performance.LagStatus; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.mcaccess.BoundingBox; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; + +public class HitboxCheck extends PacketCheck { + private double optPrecision; + private double optLeniency; + private double optMaxLowest; + private int optThreshold; + private int optSuspicionLifespan; + private int optPeriodWeight; + private int optInstantWeight; + + public HitboxCheck() { + super("KillAura", "ka.hbx", Cheat.valueOf("KillAura")); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optPrecision = this.getAdvancedLocalSetting("precision", Double.valueOf(0.005)); + this.optLeniency = this.getAdvancedLocalSetting("leniency", Double.valueOf(0.013)); + this.optMaxLowest = this.getAdvancedLocalSetting("max_lowest", Double.valueOf(1.679)); + this.optThreshold = this.getAdvancedLocalSetting("threshold", Integer.valueOf(7)); + this.optSuspicionLifespan = this.getAdvancedLocalSetting("suspicion_lifespan", Integer.valueOf(3000)); + this.optPeriodWeight = this.getAdvancedLocalSetting("period_weight", Integer.valueOf(20)); + this.optInstantWeight = this.getAdvancedLocalSetting("instant_weight", Integer.valueOf(15)); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + if (this.isServerLagging()) { + return null; + } else { + MethodProfiler mp = new MethodProfiler("CT-48721949"); + CheckResult result = new CheckResult(); + if (stats.getLagStatus() != LagStatus.EXTREME_LAG + && !stats.hasNoStat("posCaches") + && !stats.hasNoStat("currentTarget") + && Packets.isAttackPacket(packet)) { + Location l = p.getEyeLocation().clone(); + Vector v = l.getDirection().clone(); + LivingEntity target = stats.getCurrentTarget(); + Location tLoc = target.getEyeLocation().clone(); + HashMap posCaches = stats.getMap("posCaches"); + if (Packets.readInteger(packet, 0) != target.getEntityId()) { + return null; + } else { + BoundingBox cur = BoundingBox.of((Entity)target).expand(0.3, 0.0, 0.3).expandUp(1.0).expandDown(2.0); + BoundingBox old = Misc.castSafely(posCaches.get(target)); + if (old == null) { + return null; + } else { + boolean intersects = false; + double lowestDist = 1.0E30; + + for (double d = 0.0; d < (p.isSprinting() ? 0.192 : 0.175) + this.optLeniency; d += this.optPrecision) { + l.add(v.clone().multiply(d)); + if (cur.isWithinBoundingBox(l) || old.isWithinBoundingBox(l)) { + intersects = true; + break; + } + + lowestDist = Maths.min(lowestDist, cur.distance(l), old.distance(l)); + } + + if (!intersects) { + int u = stats.updateCreatedCounter("hitboxVl", (long)this.optSuspicionLifespan); + if (u > this.optThreshold && Maths.objects.length >= 16 && Maths.objects[13] == Integer.valueOf(6)) { + result.setMod(this.optPeriodWeight).addTag("hitbox (period)").addTag("recent suspicions: " + u).cancel(this.isNotSilent()); + } else if (lowestDist > this.optMaxLowest) { + result.setMod(3).addTag("hitbox (instant)").addTag("lowest: " + lowestDist).cancel(this.isNotSilent()); + } + + if (result.shouldCancel()) { + stats.resetTimer("attackPenaltyTracker"); + } + } + + mp.addToTimings(); + return result; + } + } + } else { + return null; + } + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/ImpossibleHitCheck.java b/src/main/java/rip/reflex/check/combat/killaura/ImpossibleHitCheck.java new file mode 100644 index 0000000..76fac0b --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/ImpossibleHitCheck.java @@ -0,0 +1,124 @@ +package rip.reflex.check.combat.killaura; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.reflex.SubCommandBroadcast; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.Movement; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.mcaccess.MCAccess; + +public class ImpossibleHitCheck extends CombatCheck { + public static int integrityCheck = 10; + + public ImpossibleHitCheck() { + super("KillAura", "ka.imp", false, Cheat.valueOf("KillAura")); + this.setSync(true); + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + MethodProfiler mp = new MethodProfiler("CT-951687"); + CheckResult result = new CheckResult(); + if (integrityCheck > -5 && integrityCheck-- == 0) { + try { + CommandConditions.integrityRan[0] = CommandConditions.integrityRan[0] - 2913; + String[] data = this.check("2"); + if (data != null && data.length == 2) { + int fhash = data[1].hashCode() + "f".hashCode(); + int aihash = "ai".hashCode() - data[0].hashCode(); + Class intcheckA = Class.forName("rip.reflex.util.time.Timer"); + Field fingerprintA = intcheckA.getDeclaredField("integrityDataFingerprint_a"); + Field arrinfoA = intcheckA.getDeclaredField("integrityDataArrInfo_a"); + MCAccess.secureSetFinalStatic(fingerprintA, fhash); + MCAccess.secureSetFinalStatic(arrinfoA, aihash); + if (Maths.intcheckSetB("rip.reflex.util.performance.timings.TimingsEntry", fhash, aihash) == null) { + throw new IOException(); + } + } + } catch (Throwable ignored) { + } + } + + int vl = 0; + if (p.isDead()) { + result.addTag("dead"); + vl++; + } + + if (p.isBlocking()) { + result.addTag("blocking"); + vl++; + } + + if (p.isSleeping() && p.getSleepTicks() > 10) { + result.addTag("sleeping"); + vl++; + } + + if (stats.isInventoryOpened() && stats.getTimerTicked("inventoryOpenTracker") > 15L) { + result.addTag("inventory opened"); + vl++; + } + + mp.addToTimings(); + return result.setMod(vl) + .cancel(this.shouldCancel(stats, 5) && vl > 0 && (result.hasTag("dead") || result.hasTag("sleeping") || result.hasTag("inventory opened"))); + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + return null; + } + + private String[] check(String g) { + try { + Class reflex = Class.forName("rip.reflex.Reflex"); + + try { + Method classFingerprint = reflex.getDeclaredMethod("classFingerprint", String.class); + classFingerprint.setAccessible(true); + String fingerprint = (String)classFingerprint.invoke( + this.reflex, new String(SubCommandBroadcast.integrityShit()) + hex((long)Movement.getApinstance().getResource().hashCode()) + ); + classFingerprint.setAccessible(false); + + try { + CommandConditions.integrityRan[4] = CommandConditions.integrityRan[4] - (-972); + Method arrInfo = reflex.getDeclaredMethod("arrInfo", long.class); + arrInfo.setAccessible(true); + long info = (Long)arrInfo.invoke(this.reflex, System.nanoTime()); + arrInfo.setAccessible(false); + String[] s = new String[Integer.parseInt(g, 10)]; + + try { + s[1] = fingerprint; + s[0] = hex(info); + return s; + } catch (Throwable ex) { + throw new RuntimeException("4", ex); + } + } catch (Throwable e) { + throw new RuntimeException("3", e); + } + } catch (Throwable err) { + throw new RuntimeException("2", err); + } + } catch (Throwable cause) { + throw new RuntimeException("1", cause); + } + } + + private static String hex(long l) { + return Long.toString(l, 16).replace("-", "").toUpperCase(); + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/PacketRotsCheck.java b/src/main/java/rip/reflex/check/combat/killaura/PacketRotsCheck.java new file mode 100644 index 0000000..7676eeb --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/PacketRotsCheck.java @@ -0,0 +1,72 @@ +package rip.reflex.check.combat.killaura; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.MovementCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.location.MoveDirection; +import rip.reflex.util.location.Movement; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.time.Timer; + +public class PacketRotsCheck extends MovementCheck { + public PacketRotsCheck() { + super("KillAura", "ka.pts", 1, Cheat.valueOf("KillAura")); + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + MethodProfiler mp = new MethodProfiler("CT-718659"); + CheckResult result = new CheckResult(); + if (stats.getStat("attackCounter", int.class) >= 2 + && !stats.getStat("attackTracker0", Timer.class).hasPassed(500L) + && !stats.hasSpeedEffect() + && !stats.hasJumpEffect()) { + Movement movement = LocationUtils.getMovement(p, from, to); + MoveDirection direction = movement.getDirection(); + double moveSpeed = Maths.horizontalDistance(from, to); + double motion = direction == MoveDirection.BACKWARD ? movement.getBackwardFactor() : movement.getStrafingFactor(); + double ratio = movement.getForwardFactor() / motion; + boolean knockingBack = LocationUtils.isKnockingBack(p, stats) + || !stats.getStat("damageByEntityTracker", Timer.class).hasPassed(700L) + && !LocationUtils.isZero(p.getVelocity().clone()) + && !LocationUtils.isGroundExact(p); + if (direction != MoveDirection.FORWARD + && Maths.matchEx(Math.abs(movement.getForwardFactor() - motion), 0.19, 0.6) + && Maths.matchEx(motion, 0.63, 0.8) + && !Maths.matchIn(motion, 0.68, 0.6999) + && !Maths.anyRange(ratio, 1.0, 1.2, 1.3, 1.365) + && ratio < 2.0 + && !knockingBack + && (moveSpeed > 0.267 || p.isSprinting())) { + stats.setStat("packetRotsViolations", stats.getStat("packetRotsViolations", int.class) + 1); + stats.getStat("packetRotsViolateTracker", Timer.class).reset(); + if (stats.getStat("packetRotsViolations", int.class) > this.getLocalSetting("m_threshold", Integer.valueOf(3))) { + result.setMod(100) + .addTag("moves suspiciously") + .addTag(direction.shorten() + ": " + motion) + .addTag("r: " + ratio) + .addTag("m: " + moveSpeed) + .addTag("sprinting: " + p.isSprinting()) + .addTag(LocationUtils.isGroundExact(p) ? "grounded" : "midair"); + stats.setStat("packetRotsViolations", 0); + } + } else if (stats.hasTimerPassed("packetRotsViolateTracker", 5000L)) { + stats.setStat("packetRotsViolations", 0); + } + + if (result.isCheckFailed()) { + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + 5); + } + + mp.addToTimings(); + return result; + } else { + return null; + } + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/ReachCheck.java b/src/main/java/rip/reflex/check/combat/killaura/ReachCheck.java new file mode 100644 index 0000000..6685d2e --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/ReachCheck.java @@ -0,0 +1,96 @@ +package rip.reflex.check.combat.killaura; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.security.AntiPiracy; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.npc.EntityUtils; + +public class ReachCheck extends CombatCheck { + public ReachCheck() { + super("KillAura", "ka.rh", false, Cheat.valueOf("KillAura")); + + while ((AntiPiracy.addAll(AntiPiracy.values) ^ 38163) != 480848) { + Bukkit.getScheduler().runTask(Reflex.getReflex(), () -> { + try { + this.wait(); + } catch (InterruptedException ignored) { + } + }); + } + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + MethodProfiler mp = new MethodProfiler("CT-856129"); + if (EntityUtils.getEntitySize(target) > 2) { + return null; + } else if (p.getLocation().getWorld().getName().equals(target.getLocation().getWorld().getName()) + && p.getLocation().clone().getY() - target.getLocation().clone().getY() < -2.0) { + return null; + } else { + if (target instanceof Player) { + Stats targetStats = Stats.of((Player)target); + if (!targetStats.hasTimerPassed("teleportTracker", 1750L)) { + return null; + } + } + + CheckResult result = new CheckResult(); + double yaw = (double)p.getLocation().clone().getYaw(); + double dYaw = (double)target.getLocation().clone().getYaw(); + double yDif = Math.abs(p.getLocation().clone().getY() - target.getLocation().clone().getY()) / 2.0; + boolean chasing = target instanceof Player && Maths.angle(yaw, dYaw) < 90.0; + boolean strict = this.getLocalSetting("strict_mode", Boolean.valueOf(false)); + double reach = Maths.distanceToHitbox(p, target); + double lastReach = stats.getStat("lastReach", double.class); + double motionBoost = Maths.adjustMotionToReach(p, stats); + double maxReach = this.getLocalSetting("max_reach", Double.valueOf(3.652999)) + + (double)p.getFallDistance() + + (chasing ? (((Player)target).isSprinting() ? 0.95 : 0.6) : 0.005) + + motionBoost + + yDif; + double strictReach = this.getLocalSetting("strict_reach", Double.valueOf(strict ? 4.1 : 4.35)); + double kickReach = this.getLocalSetting("kick_reach", Double.valueOf(4.83614)); + if ((reach > maxReach && lastReach > maxReach || reach > kickReach) && reach < this.getLocalSetting("reach_lim", Double.valueOf(8.0))) { + if (this.shouldCancel(stats, 10)) { + stats.resetTimer("attackPenaltyTracker"); + } + + result.setMod( + Maths.floor( + (double)( + reach > kickReach + ? (stats.getViolations(this.cheat) > 10 ? 9 : 13) + : (int)Math.round(reach > strictReach && !chasing ? reach * 1.25 : reach) + ) + * 0.75 + ) + ) + .addTag("reach: " + reach) + .cancel(this.shouldCancel(stats, 12)); + } + + stats.setStat("lastReach", reach); + if (result.isCheckFailed()) { + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + Math.min(2, result.getViolationsMod())); + } + + mp.addToTimings(); + return result; + } + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/SwingCheck.java b/src/main/java/rip/reflex/check/combat/killaura/SwingCheck.java new file mode 100644 index 0000000..eaa0487 --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/SwingCheck.java @@ -0,0 +1,79 @@ +package rip.reflex.check.combat.killaura; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Averanger; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.LagStatus; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.time.Timer; + +public class SwingCheck extends PacketCheck { + public SwingCheck() { + super("KillAura", "ka.pod", Cheat.valueOf("KillAura")); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + if (this.isServerLagging()) { + return null; + } else { + MethodProfiler mp = new MethodProfiler("CT-193591"); + CheckResult result = new CheckResult(); + if (VersionUtils.getClientVersion(p).equals(MCVersion.V1_8_X) && stats.getLagStatus().ordinal() < LagStatus.VIVID_LAG.ordinal()) { + if (Packets.isAttackPacket(packet)) { + if (stats.getStat("lookDelayAveranger", Averanger.class) == null) { + stats.setStat("lookDelayAveranger", new Averanger(6)); + } + + stats.getStat("lookDelayAveranger", Averanger.class).next(stats.getStat("packetFlushTracker0", Timer.class).getTimePassed()); + if (stats.getStat("lookDelayAveranger", Averanger.class).value() <= 8L + && stats.getStat("currentTarget", LivingEntity.class) != null + && Maths.distanceExact(p, stats.getStat("currentTarget", LivingEntity.class)) > 2.25) { + stats.setStat("lookFrequencyViolations", stats.getStat("lookFrequencyViolations", int.class) + 2); + if (stats.getStat("lookFrequencyViolations", int.class) > 18) { + result.addTag("packets out of order (A)").setMod(100); + } + } else if (stats.getStat("lookFrequencyViolations", int.class) > 0) { + stats.setStat("lookFrequencyViolations", stats.getStat("lookFrequencyViolations", int.class) - 1); + } + + if (stats.getStat("lastSwingType", PacketType.class) != null && !stats.getStat("lastSwingType", PacketType.class).equals(Packets.IN_SWING)) { + result.addTag("packets out of order (B)").setMod(9); + } + } else if (Packets.isUpdatePacket(packet)) { + stats.getStat("packetFlushTracker0", Timer.class).reset(); + } + + stats.setStat("lastSwingType", packet.getType()); + if (this.getLocalSetting("strict_mode", Boolean.valueOf(false))) { + result.cancel(this.shouldCancel(stats)); + } + + if (result.isCheckFailed()) { + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + result.getViolationsMod()); + } + + mp.addToTimings(); + return result; + } else { + return null; + } + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/YawRateCheck.java b/src/main/java/rip/reflex/check/combat/killaura/YawRateCheck.java new file mode 100644 index 0000000..495a1da --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/YawRateCheck.java @@ -0,0 +1,76 @@ +package rip.reflex.check.combat.killaura; + +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; + +public class YawRateCheck extends CombatCheck { + private int optMaxProbability; + + public YawRateCheck() { + super("KillAura", "ka.yrt", true, Cheat.valueOf("KillAura")); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optMaxProbability = this.getAdvancedLocalSetting("max_probability", Integer.valueOf(70)); + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + MethodProfiler mp = new MethodProfiler("CT-561249"); + CheckResult result = new CheckResult(); + if (!stats.hasStat("currentTarget")) { + return null; + } else { + LivingEntity target = stats.getStat("currentTarget", LivingEntity.class); + if (!LocationUtils.isVerticalOnly(target.getVelocity().clone()) && LocationUtils.isPushable(target)) { + double d0 = Maths.getDistFromMouse(p, target); + double d1 = Maths.angle((double)from.getYaw(), (double)to.getYaw()); + double yaw = stats.getStat("lastRotateYaw", double.class); + if (Maths.matchEx(yaw, 0.85, 360.0) && Maths.matchEx(d1, 0.85, 360.0)) { + double d = Maths.angle(d0, yaw); + double y = d / 180.0 * Math.PI; + if (y < 0.05) { + stats.setStat("failedYawRateChecks", stats.getStat("failedYawRateChecks", int.class) + 1); + } + + stats.setStat("totalYawRateChecks", stats.getStat("totalYawRateChecks", int.class) + 1); + if (stats.getStat("totalYawRateChecks", int.class) >= this.optMaxProbability) { + int probability = Maths.efficiency(stats.getStat("totalYawRateChecks", int.class), stats.getStat("failedYawRateChecks", int.class)); + int maxProbability = this.getLocalSetting("yawrate_chance", Integer.valueOf(80)); + if (probability >= maxProbability) { + result.addTag("suspicious head movement").addTag("cheating probability: " + probability + "%").setMod(100); + } + + stats.setStat("totalYawRateChecks", 0); + stats.setStat("failedYawRateChecks", 0); + } + + if (result.isCheckFailed()) { + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + result.getViolationsMod()); + } + + mp.addToTimings(); + return result; + } else { + return null; + } + } else { + return null; + } + } + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/combat/killaura/YawStatisticCheck.java b/src/main/java/rip/reflex/check/combat/killaura/YawStatisticCheck.java new file mode 100644 index 0000000..3417ea7 --- /dev/null +++ b/src/main/java/rip/reflex/check/combat/killaura/YawStatisticCheck.java @@ -0,0 +1,164 @@ +package rip.reflex.check.combat.killaura; + +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.math.Maths; +import rip.reflex.util.math.descriptive.stat.Statistics; +import rip.reflex.util.performance.MethodProfiler; + +public class YawStatisticCheck extends CombatCheck { + public YawStatisticCheck() { + super("KillAura", "ka.yst", true, Cheat.valueOf("KillAura")); + this.supportCloudComputings(); + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + MethodProfiler mp = new MethodProfiler("CT-2983719"); + CheckResult result = new CheckResult(); + if (stats.hasStat("currentTarget") && !this.reflex.offlineMode) { + LivingEntity target = stats.getStat("currentTarget", LivingEntity.class); + if (Maths.distanceExact(p, target) < 1.8) { + return null; + } else { + if (!stats.hasStat("headMovementPatternSmall")) { + stats.setStat("headMovementPatternSmall", new NumberStorage(50)); + } + + if (!stats.hasStat("headMovementPatternMedium")) { + stats.setStat("headMovementPatternMedium", new NumberStorage(75)); + } + + if (!stats.hasStat("headMovementPatternBig")) { + stats.setStat("headMovementPatternBig", new NumberStorage(100)); + } + + NumberStorage smallStorage = stats.getStat("headMovementPatternSmall", NumberStorage.class); + NumberStorage mediumStorage = stats.getStat("headMovementPatternMedium", NumberStorage.class); + NumberStorage bigStorage = stats.getStat("headMovementPatternBig", NumberStorage.class); + double angle = Maths.angle((double)from.getYaw(), (double)to.getYaw()); + if (!Maths.matchEx(angle, 0.7, 60)) { + return null; + } else { + smallStorage.add(angle); + mediumStorage.add(angle); + bigStorage.add(angle); + if (Maths.objects.length > 11 + && Maths.objects[11] != null + && Long.toString((Long)Maths.objects[11] ^ -58791205879L).startsWith("-95953614030458")) { + if (smallStorage.isFull()) { + if (this.reflex.getCloudService().isConnected()) { + this.reflex.getCloudService().getCloudComputer().smallYawStatisticCheck(p, smallStorage.copy()); + } else { + Statistics stat = Maths.describe(smallStorage); + double deltaMeaning = Math.abs(stat.getMean() - stat.getMedian()); + double deltaVariance = Math.abs(stat.getHdev() - stat.getVariance()); + double ratio = stat.getBalance() / stat.getMedian(); + double hvar = Math.abs(stat.getVariance() - stat.getHighest()); + if (smallStorage.sum() != 0.0 + && hvar > 0.1 + && !Maths.matchEx(ratio, 0.0575, 0.08) + && !Maths.matchEx(ratio, 0.09, 0.13) + && stat.getBalance() < 0.5025 + && !Maths.matchEx(stat.getBalance(), 0.46, 0.485) + && stat.getMedian() < 10.0 + && Maths.matchEx(stat.getLowest(), 0.5, 1.8) + && Maths.matchEx(stat.getHighest(), 7.5, 30.0) + && Maths.matchEx(deltaMeaning, 0.0215, 1.3) + && Maths.matchEx(stat.getVariance(), 5.0, 38.0) + && stat.getAdev() > 2.45 + && !Maths.matchIn(stat.getAdev(), 3.05, 3.35) + && stat.getLdev() > 5.6 + && Maths.matchEx(deltaVariance, 0.4, 2.8) + && deltaVariance < 8.5) { + result.setMod(100) + .addTag("aimbot (short-term statistic)") + .addTag("s: " + stat.getBalance()) + .addTag("m: " + stat.getMedian()) + .addTag("dm: " + deltaMeaning) + .addTag("dv: " + deltaVariance) + .addTag("a: " + stat.getAdev()) + .addTag("l: " + stat.getLdev()) + .addTag("r: " + ratio); + } + } + + smallStorage.clear(); + } + + if (mediumStorage.isFull()) { + if (this.reflex.getCloudService().isConnected()) { + this.reflex.getCloudService().getCloudComputer().mediumYawStatisticCheck(p, mediumStorage.copy()); + } else { + Statistics stat = Maths.describe(mediumStorage); + double mean = stat.getMean(); + double var = stat.getVariance(); + double sk = stat.getSkewness(); + double kt = stat.getKurtosis(); + if (mediumStorage.sum() != 0.0 && (var > 850.0 || !Maths.matchEx(sk, -0.525, 5.8) || !Maths.matchEx(kt, -1.26, 42.8))) { + result.setMod(100) + .addTag("aimbot (middle-term statistic)") + .addTag("m: " + mean) + .addTag("v: " + var) + .addTag("s: " + sk) + .addTag("k: " + kt); + } + } + + mediumStorage.clear(); + } + + if (bigStorage.isFull()) { + if (this.reflex.getCloudService().isConnected()) { + this.reflex.getCloudService().getCloudComputer().bigYawStatisticCheck(p, bigStorage.copy()); + } else { + Statistics stat = Maths.describe(bigStorage); + double sk = stat.getSkewness(); + double kt = stat.getKurtosis(); + double ldev = stat.getLdev(); + double adev = stat.getAdev(); + if (bigStorage.sum() != 0.0 + && ( + !Maths.matchEx(sk, 0.03, 5.675) + || !Maths.matchEx(kt, -1.19, 37.5) + || adev < 0.475 && !Maths.matchIn(adev, 0.2, 0.3) + || ldev < 1.225 + )) { + result.setMod(100) + .addTag("aimbot (long-term statistic)") + .addTag("s: " + sk) + .addTag("k: " + kt) + .addTag("a: " + adev) + .addTag("l: " + ldev); + } + } + + bigStorage.clear(); + } + + if (result.isCheckFailed()) { + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + result.getViolationsMod()); + } + + mp.addToTimings(); + } + + return result; + } + } + } else { + return null; + } + } + + @Override + public CheckResult check(Player p, Stats stats, LivingEntity target) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/movement/ElytraMoveCheck.java b/src/main/java/rip/reflex/check/movement/ElytraMoveCheck.java new file mode 100644 index 0000000..d9ba1e7 --- /dev/null +++ b/src/main/java/rip/reflex/check/movement/ElytraMoveCheck.java @@ -0,0 +1,243 @@ +package rip.reflex.check.movement; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityToggleGlideEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.misc.Items; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; + +public class ElytraMoveCheck extends PacketCheck { + private boolean optUnequipElytra = this.getLocalSetting("unequip_elytra", Boolean.valueOf(true)); + private int optSetbacksToUnequip; + private int optSetbackLifespan; + + public ElytraMoveCheck() { + super("ElytraMove", "eltr.mv", Cheat.valueOf("ElytraMove")); + this.setupVlSubtractionThread(3, 1); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optSetbacksToUnequip = this.getAdvancedLocalSetting("setbacks_to_unequip", Integer.valueOf(12)); + this.optSetbackLifespan = this.getAdvancedLocalSetting("setback_lifespan", Integer.valueOf(3000)); + } + + @EventHandler( + priority = EventPriority.LOWEST + ) + public void entityToggleGlide(EntityToggleGlideEvent e) { + if (!e.isCancelled() && e.getEntity() instanceof Player) { + MethodProfiler mp = new MethodProfiler("IQ-795792183"); + Player p = (Player)e.getEntity(); + Stats stats = Stats.of(p); + if (p.getGameMode() == GameMode.SURVIVAL || p.getGameMode() == GameMode.ADVENTURE) { + Location loc = p.getLocation().clone(); + boolean gliding = e.isGliding(); + if (gliding) { + stats.setStat("elytraGlidingBeginLoc", loc); + } else { + stats.setStat("ticksElytraGliding", 0); + stats.removeStat("eltrMvLastRatio"); + stats.removeStat("eltrMvLastFallenDownBlocks"); + Block blockIn = loc.getBlock(); + Block blockBeneath = blockIn.getRelative(BlockFace.DOWN); + Block blockFarBelow = blockBeneath.getRelative(BlockFace.DOWN); + long chestChangePassed = stats.getTimerPassed("eltrMvChestplateClickTracker"); + boolean inMidair = Items.allOfType(Material.AIR, blockIn, blockBeneath, blockFarBelow); + boolean didNotChangeChestplateRecently = chestChangePassed > 2750L; + if (inMidair && didNotChangeChestplateRecently) { + CheckResult result = new CheckResult() + .setMod(3) + .addTag("moved unexpectedly") + .addTag("ccps: " + (chestChangePassed >= 10000L ? "-1.0" : Maths.round((double)chestChangePassed / 1000.0, 3))) + .cancel(this.shouldCancel(stats, 5)); + if (result.shouldCancel()) { + this.setbackOrTakeOffElytra(p, stats, result); + } + + Check.addVl(stats, this.cheat, result); + Check.check(p, stats, null, this, result); + } + } + + stats.setStat("elytraGliding", gliding); + mp.addToTimings(); + } + } + } + + @EventHandler( + priority = EventPriority.LOWEST + ) + public void playerInvClick(InventoryClickEvent e) { + boolean clickedChestplate = e.getRawSlot() == 6; + if (e.getWhoClicked() instanceof Player && clickedChestplate) { + Player p = (Player)e.getWhoClicked(); + Stats stats = Stats.of(p); + stats.resetTimer("eltrMvChestplateClickTracker"); + } + } + + @EventHandler( + priority = EventPriority.LOWEST + ) + public void playerInteract(PlayerInteractEvent e) { + if ((e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) && e.getMaterial().name().contains("FIREWORK")) { + Player p = e.getPlayer(); + Stats stats = Stats.of(p); + stats.resetTimer("eltrMvFireworkUseTracker"); + } + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + if (stats.hasStat("eltrMvFireworkUseTracker") && !stats.hasTimerPassed("eltrMvFireworkUseTracker", 3000L)) { + return null; + } else if (stats.getBoolean("elytraGliding") && stats.hasTimerPassed("teleportTracker", 1000L)) { + if (!packet.getType().equals(Packets.IN_POSITION) && !packet.getType().equals(Packets.IN_POSLOOK)) { + return null; + } else { + MethodProfiler mp = new MethodProfiler("EQ-2183798"); + CheckResult result = new CheckResult(); + int vl = 0; + if (stats.hasSlowFallingEffect()) { + return null; + } else { + double movedX = data.getMovedX(); + double movedY = data.getMovedY(); + double movedZ = data.getMovedZ(); + double yaw; + double pitch; + if (packet.getType().equals(Packets.IN_POSLOOK)) { + yaw = (double)data.getYaw(); + pitch = (double)data.getPitch(); + } else { + yaw = stats.getDouble("pckOldYaw"); + pitch = stats.getDouble("pckOldPitch"); + } + + if (yaw == 0.0 && pitch == 0.0) { + return null; + } else { + Block blockIn = p.getLocation().clone().getBlock(); + Block blockBeneath = blockIn.getRelative(BlockFace.DOWN); + Block blockFarBelow = blockBeneath.getRelative(BlockFace.DOWN); + boolean inMidair = Items.allOfType(Material.AIR, blockIn, blockBeneath, blockFarBelow); + if (inMidair) { + double movedTotal = Math.sqrt(Maths.square(movedX) + Maths.square(movedY) + Maths.square(movedZ)); + if (movedY == 0.0) { + if (stats.hasTimerPassed("eltrMvSetbackTracker", 2000L)) { + vl += 2; + result.addTag("moved too accurately"); + } + } else if (movedY < 0.0) { + double risenUp = stats.getDouble("eltrMvRisenUpBlocks"); + stats.addNumber("eltrMvFallenDownBlocks", -movedY); + stats.setStat("eltrMvRisenUpBlocks", 0.0); + if (risenUp != 0.0) { + double lastFallenDown = stats.getDouble("eltrMvLastFallenDownBlocks"); + double ratio = Maths.safeFloatingPoint(risenUp / lastFallenDown, 0.0); + double lastRatio = stats.getDouble("eltrMvLastRatio"); + double relativeRatio = Maths.safeFloatingPoint(ratio / lastRatio, 0.0); + stats.setStat("eltrMvLastRatio", ratio); + if (ratio > 0.64) { + vl += 2; + result.addTag("fall/rise ratio: " + ratio); + } + + if (relativeRatio > 1.78) { + vl += 3; + result.addTag("relative: " + relativeRatio); + } + } + } else { + double risenUp = stats.addNumber("eltrMvRisenUpBlocks", movedY); + double fallenDown = stats.getDouble("eltrMvFallenDownBlocks"); + if (fallenDown != 0.0) { + stats.setStat("eltrMvFallenDownBlocks", 0.0); + stats.setStat("eltrMvLastFallenDownBlocks", fallenDown); + } else { + double lastFallenDownx = stats.getDouble("eltrMvLastFallenDownBlocks"); + double ratiox = Maths.safeFloatingPoint(risenUp / lastFallenDownx, 1.0); + if (ratiox > 0.8) { + vl += 2; + result.addTag("tried to fly too high").addTag("r: " + ratiox).addTag("lfd: " + lastFallenDownx).addTag("ru: " + risenUp); + } + } + } + + double rotY = Maths.to180angle(pitch); + double fallenDownBlocks = stats.getDouble("eltrMvFallenDownBlocks"); + double vRelative = Math.abs(Maths.safeFloatingPoint(movedTotal / (rotY * fallenDownBlocks), 0.0)); + if (vRelative > 0.01) { + int u = stats.updateCreatedCounter("eltrMvSpeedLimitExceessCounter", 2250L); + if (u > 27) { + vl += 4; + stats.removeStat("eltrMvSpeedLimitExceessCounter"); + result.addTag("relative velocity: " + vRelative).addTag("ry: " + rotY).addTag("fdb: " + fallenDownBlocks); + } + } + + if (vl > 0) { + result.setMod(vl); + if (this.shouldCancel(stats, 5)) { + this.setbackOrTakeOffElytra(p, stats, result); + } + } + } + + mp.addToTimings(); + return result; + } + } + } + } else { + return null; + } + } + + private void setbackOrTakeOffElytra(Player p, Stats stats, CheckResult result) { + Location where = stats.getLocation("elytraGlidingBeginLoc"); + if (where != null) { + stats.resetTimer("eltrMvSetbackTracker"); + stats.syncTp(where); + } + + if (this.optUnequipElytra) { + int recentSetbacks = stats.updateCreatedCounter("eltrMvSetbacksCounter", (long)this.optSetbackLifespan); + result.addTag("recent setbacks: " + recentSetbacks); + if (recentSetbacks > this.optSetbacksToUnequip) { + ItemStack chestplate = p.getInventory().getChestplate(); + if (chestplate != null && chestplate.getType() == Material.ELYTRA) { + p.getInventory().setChestplate(null); + p.getInventory().addItem(new ItemStack[]{chestplate.clone()}); + result.addTag("unequipped their elytra"); + } + } + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/movement/InvMoveCheck.java b/src/main/java/rip/reflex/check/movement/InvMoveCheck.java new file mode 100644 index 0000000..f56dea3 --- /dev/null +++ b/src/main/java/rip/reflex/check/movement/InvMoveCheck.java @@ -0,0 +1,112 @@ +package rip.reflex.check.movement; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class InvMoveCheck extends PacketCheck { + private int optOpenWait; + + public InvMoveCheck() { + super("InvActions", "invact.mov", Cheat.valueOf("InvActions")); + LoopHelper.loopStatsEvery(stats -> { + stats.setStat("invmoveVl", 0); + }, 200); + this.setupVlResetThread(15); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optOpenWait = this.getAdvancedLocalSetting("open_wait", Integer.valueOf(500)); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + MethodProfiler mp = new MethodProfiler("LD-2872156744"); + CheckResult result = new CheckResult(); + if ((!stats.hasJumpEffect() || p.isOnGround()) && stats.hasTimerPassed("iceMoveTracker", 2200L)) { + boolean walked = false; + boolean rotated = false; + if (packet.getType().equals(Packets.IN_POSLOOK)) { + double x = data.getX(); + double z = data.getZ(); + float yaw = data.getYaw(); + float pitch = data.getPitch(); + walked = x != stats.getStat("ia_lastX", double.class) || z != stats.getStat("ia_lastZ", double.class); + rotated = yaw != stats.getStat("ia_lastYaw", float.class) || pitch != stats.getStat("ia_lastPitch", float.class); + stats.setStat("ia_lastX", x); + stats.setStat("ia_lastZ", z); + stats.setStat("ia_lastYaw", yaw); + stats.setStat("ia_lastPitch", pitch); + } else if (packet.getType().equals(Packets.IN_POSITION)) { + double x = data.getX(); + double z = data.getZ(); + walked = x != stats.getStat("ia_lastX", double.class) || z != stats.getStat("ia_lastZ", double.class); + stats.setStat("ia_lastX", x); + stats.setStat("ia_lastZ", z); + } else if (packet.getType().equals(Packets.IN_LOOK)) { + float yaw = data.getYaw(); + float pitch = data.getPitch(); + rotated = yaw != stats.getStat("ia_lastYaw", float.class) || pitch != stats.getStat("ia_lastPitch", float.class); + stats.setStat("ia_lastYaw", yaw); + stats.setStat("ia_lastPitch", pitch); + } + + if (stats.isInventoryOpened() + && stats.hasTimerPassed("velocityTracker", 2000L) + && !p.isInsideVehicle() + && stats.hasTimerPassed("inventoryOpenTracker", (long)this.optOpenWait) + && this.getLocalSetting("block_movement", Boolean.valueOf(true))) { + Location l = p.getLocation().clone(); + Material block = l.getBlock().getType(); + double v = LocationUtils.getAbsoluteVelocityXZ(p); + double f = (double)p.getFallDistance(); + if (stats.getStat("invmoveVl", int.class) > 10) { + stats.setback(stats.getStat("setbackPos", Location.class)); + stats.setStat("invmoveVl", 0); + if (walked) { + result.addTag("walking").addTag("v: " + v).addTag("f: " + f); + } + + if (rotated) { + result.addTag("rotating"); + } + + result.setMod(5).cancel(this.isNotSilent()); + if (this.isNotSilent()) { + stats.setStat("inventoryOpened", false); + ReflexScheduler.sync().run(ReflexRunnable.simple("SyncInvClose", p::closeInventory)); + } + } + + stats.addNumberIf( + "invmoveVl", + 1, + rotated || walked && v < 0.24 && f < 5.0 && stats.hasTimerPassed("damageByEntityTracker", 1250L) && !block.toString().contains("STATIONARY") + ); + } + + mp.addToTimings(); + return result; + } else { + return null; + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/movement/VehicleMoveCheck.java b/src/main/java/rip/reflex/check/movement/VehicleMoveCheck.java new file mode 100644 index 0000000..3b9dd20 --- /dev/null +++ b/src/main/java/rip/reflex/check/movement/VehicleMoveCheck.java @@ -0,0 +1,180 @@ +package rip.reflex.check.movement; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.vehicle.VehicleExitEvent; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.compatibility.CompatibilityProvider; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class VehicleMoveCheck extends PacketCheck { + private static final double MAX_NON_AIR_Y = 0.055; + private static final double FIRST_BOAT_GRAVITY = -0.15; + private static final double SECOND_BOAT_GRAVITY = -0.5; + private static final double THIRD_BOAT_GRAVITY = -1.35; + private static final double FOURTH_BOAT_GRAVITY = -2.95; + private double optMaxNormalSpeed; + private double optMaxFlowingSpeed; + private double optMaxGroundSpeed; + private double optMaxIceSpeed; + private double optMaxAcceleration; + + public VehicleMoveCheck() { + super("VehicleMove", "vehmv.boat", Cheat.valueOf("VehicleMove")); + this.setupVlSubtractionThread(5, 1); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optMaxNormalSpeed = this.getAdvancedLocalSetting("max_normal_speed", Double.valueOf(0.52)); + this.optMaxFlowingSpeed = this.getAdvancedLocalSetting("max_flowing_speed", Double.valueOf(0.58)); + this.optMaxGroundSpeed = this.getAdvancedLocalSetting("max_ground_speed", Double.valueOf(0.26)); + this.optMaxIceSpeed = this.getAdvancedLocalSetting("max_ice_speed", Double.valueOf(2.08)); + this.optMaxAcceleration = this.getAdvancedLocalSetting("max_acceleration", Double.valueOf(0.06)); + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void vehicleExited(VehicleExitEvent e) { + if (!e.isCancelled() && e.getExited() instanceof Player) { + Player p = (Player)e.getExited(); + Stats stats = Stats.of(p); + stats.removeStat("vehmvLastX"); + stats.removeStat("vehmvLastY"); + stats.removeStat("vehmvLastZ"); + stats.removeStat("vehmvLastSpeed"); + stats.removeStat("vehmvLastAirborne"); + stats.removeStat("vehmvAirborneTicks"); + stats.resetTimer("vehmvIceMoveTracker"); + } + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + if (!data.isVehicleMove()) { + return null; + } else { + Entity vehicle = p.getVehicle(); + if (vehicle != null && vehicle.getType().name().toUpperCase().contains("BOAT")) { + CheckResult result = new CheckResult(); + MethodProfiler mp = new MethodProfiler("RB-8095182"); + double newX = data.getX(); + double newY = data.getY(); + double newZ = data.getZ(); + double lastX = stats.getDouble("vehmvLastX"); + double lastY = stats.getDouble("vehmvLastY"); + double lastZ = stats.getDouble("vehmvLastZ"); + stats.setStat("vehmvLastX", newX); + stats.setStat("vehmvLastY", newY); + stats.setStat("vehmvLastZ", newZ); + if (lastX == 0.0 && lastY == 0.0 && lastZ == 0.0) { + return null; + } else { + double movedX = newX - lastX; + double movedY = newY - lastY; + double movedZ = newZ - lastZ; + if (movedX == 0.0 && movedY == 0.0 && movedZ == 0.0) { + return null; + } else { + double speed = Math.sqrt(Maths.square(movedX) + Maths.square(movedZ)); + double lastSpeed = stats.getDouble("vehmvLastSpeed"); + double acceleration = (speed - lastSpeed) / 1.0; + stats.setStat("vehmvLastSpeed", speed); + Block blockInside = p.getLocation().clone().getBlock(); + Block blockBelow = blockInside.getRelative(BlockFace.DOWN); + CompatibilityProvider cp = VersionUtils.getCompatibilityProvider(); + boolean isAirborne = blockInside.getType() == Material.AIR && blockBelow.getType() == Material.AIR; + boolean isOnFlowingLiquid = !isAirborne + && (blockInside.isLiquid() && cp.isLiquidFlowing(blockInside) || blockBelow.isLiquid() && cp.isLiquidFlowing(blockBelow)); + boolean isOnGround = !isAirborne && !isOnFlowingLiquid && !blockInside.isLiquid() && !blockBelow.isLiquid(); + boolean isOnIce = isOnGround && (blockInside.getType().name().contains("ICE") || blockBelow.getType().name().contains("ICE")) + || !stats.hasTimerPassed("vehmvIceMoveTracker", 4000L); + boolean lastAirborne = stats.getBoolean("vehmvLastAirborne"); + if (isOnIce) { + stats.resetTimer("vehmvIceMoveTracker"); + } + + stats.setStat("vehmvLastAirborne", isAirborne); + if (isAirborne) { + if (lastAirborne) { + stats.addNumber("vehmvAirborneTicks", 1); + } else { + stats.setStat("vehmvAirborneTicks", 0); + } + } else if (lastAirborne) { + stats.setStat("vehmvAirborneTicks", 0); + } + + double maxSpeed = isOnIce + ? this.optMaxIceSpeed + : (isOnGround ? this.optMaxGroundSpeed : (isOnFlowingLiquid ? this.optMaxFlowingSpeed : this.optMaxNormalSpeed)); + int vl = 0; + if (speed > maxSpeed) { + result.addTag("moved too quickly on boat").addTag("speed: " + speed).addTag("max: " + maxSpeed); + vl++; + } + + if (isOnGround && acceleration > this.optMaxAcceleration) { + result.addTag("moving too quickly on boat").addTag("acceleration: " + acceleration); + vl++; + } + + int ticksInMidair = stats.getInt("vehmvAirborneTicks"); + double maxY = this.getGravity(ticksInMidair); + if (movedY > maxY) { + result.addTag("unexpected gravity on boat: " + movedY).addTag("max: " + maxY).addTag("ticks in midair: " + ticksInMidair); + vl++; + } + + mp.addToTimings(); + if (vl > 0) { + result.setMod(vl); + if (this.shouldCancel(stats)) { + ReflexScheduler.sync().run(ReflexRunnable.simple("OM-2891784", vehicle::eject)); + result.cancel(); + } + + result.addTagIf("flowing", isOnFlowingLiquid).addTagIf("ground", isOnGround).addTagIf("on ice", isOnIce).addTagIf("airborne", isAirborne); + } + + return result; + } + } + } else { + return null; + } + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } + + private double getGravity(int ticksInMidair) { + if (ticksInMidair >= 80) { + return -2.95; + } else if (ticksInMidair >= 40) { + return -1.35; + } else if (ticksInMidair >= 20) { + return -0.5; + } else { + return ticksInMidair >= 10 ? -0.15 : 0.055; + } + } +} diff --git a/src/main/java/rip/reflex/check/movement/speed/SneakCheck.java b/src/main/java/rip/reflex/check/movement/speed/SneakCheck.java new file mode 100644 index 0000000..6b5bceb --- /dev/null +++ b/src/main/java/rip/reflex/check/movement/speed/SneakCheck.java @@ -0,0 +1,42 @@ +package rip.reflex.check.movement.speed; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; + +public class SneakCheck extends PacketCheck { + public SneakCheck() { + super("Speed", "speed.snk", Cheat.valueOf("Speed")); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + CheckResult result = new CheckResult(); + if (Packets.isSneakPacket(packet)) { + stats.setStat("sneakTogglesPerSecond", stats.getStat("sneakTogglesPerSecond", int.class) + 1); + } else if (Packets.isUpdatePacket(packet) && stats.getStat("hasSecondTicked", boolean.class)) { + if (stats.getStat("sneakTogglesPerSecond", int.class) >= 40) { + if (!this.getLocalSetting("silent", Boolean.valueOf(false))) { + stats.setback(); + } + + result.setMod(19); + } + + result.addTag("sneak toggle rate: " + stats.getStat("sneakTogglesPerSecond", int.class)); + stats.setStat("sneakTogglesPerSecond", 0); + } + + return result; + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/movement/speed/SpeedCheck.java b/src/main/java/rip/reflex/check/movement/speed/SpeedCheck.java new file mode 100644 index 0000000..0a56ced --- /dev/null +++ b/src/main/java/rip/reflex/check/movement/speed/SpeedCheck.java @@ -0,0 +1,133 @@ +package rip.reflex.check.movement.speed; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; + +public class SpeedCheck extends PacketCheck { + private final double defMaxAcceleration = 0.07; + private final double defMaxSpeed = 0.0; + + public SpeedCheck() { + super("Speed", "speed.mn", Cheat.valueOf("Speed")); + this.setLagSensetive(false); + } + + @Override + public CheckResult checkIn(Player player, Stats stats, PacketContainer packet, SharedPacketData data) { + if (!Packets.isMove(packet)) { + return null; + } else { + boolean hasMove = Packets.readBoolean(packet, 1); + boolean ground = Packets.readBoolean(packet, 0); + CheckResult result = new CheckResult(); + double lastX = stats.getStat("lastX", double.class); + double lastZ = stats.getStat("lastZ", double.class); + double lastLastX = stats.getStat("lastLastX", double.class); + double lastLastZ = stats.getStat("lastLastZ", double.class); + if (!hasMove) { + return this.rt(lastX, lastZ, 0.0, 0.0, stats, result, ground); + } else { + double x = data.getX(); + double z = data.getZ(); + double speed = Math.sqrt(Maths.square(lastX - x) + Maths.square(lastZ - z)) / 0.98; + if (stats.getStat("alreadyMoved", int.class) < 2) { + return this.rt(x, z, speed, 0.0, stats, null, ground); + } else { + double acce = Maths.round( + Math.sqrt(Maths.square(x - lastX) - Maths.square(lastX - lastLastX) + (Maths.square(z - lastZ) - Maths.square(lastZ - lastLastZ))) / 0.98, 7 + ); + if (Double.isNaN(acce)) { + acce = 0.0; + } + + if (acce == 0.0 && speed == 0.0) { + return this.rt(x, z, speed, acce, stats, result, ground); + } else { + this.checkAccelertation(ground, acce, speed, player, result, stats); + player.sendMessage( + "Speed: " + Maths.round(speed, 8) + " / Acce: " + acce + " / " + ground + "/" + player.isSprinting() + "/" + stats.isSprinting() + ); + return this.rt(x, z, speed, acce, stats, result, ground); + } + } + } + } + } + + private Object checkAccelertation(boolean ground, double acce, double speed, Player player, CheckResult result, Stats stats) { + double lastAcce = stats.getStat("lastAcce", double.class); + boolean lastGround = stats.getStat("SlastOnGround", boolean.class); + boolean jump = !ground && lastGround; + player.sendMessage( + "LastSpeed: " + + (stats.getStat("lastSpeed", double.class) == 0.0) + + " / Speed: " + + Maths.round(speed, 8) + + " / Acce: " + + acce + + " / " + + ground + + "/" + + player.isSprinting() + + "/" + + stats.isSprinting() + ); + double maxAcce = 0.07; + if (stats.getStat("lastSpeed", double.class) == 0.0) { + if (stats.isSneaking() && !Maths.matchIn(acce, 0.04636, 0.04638)) { + return this.cancel("invalid acceleration (sneaking): " + acce, 10, result); + } else if (stats.isSprinting() && !Maths.matchIn(acce, 0.13, 0.128)) { + return this.cancel("invalid acceleration (sprinting): " + acce, 10, result); + } else { + return !Maths.matchIn(acce, 0.098, 0.1) ? this.cancel("invalid acceleration (normal): " + acce, 10, result) : result; + } + } else { + if (stats.isSprinting()) { + maxAcce = jump ? 0.305 : 0.11; + } else if (stats.isSneaking()) { + maxAcce = jump ? 0.025 : 0.01; + } else { + maxAcce = jump ? 0.083 : maxAcce; + } + + return acce > maxAcce ? this.cancel("high acceleration: " + acce, 1, result) : result; + } + } + + private Object cancel(String tag, int mod, CheckResult r) { + System.out.println("cancel: " + tag); + return r.addTag(tag).setMod(r.getViolationsMod() + mod).cancel(true); + } + + private CheckResult rt(double x, double z, double speed, double acce, Stats stats, CheckResult r, boolean ground) { + int i; + if ((i = stats.getStat("alreadyMoved", int.class)) < 2) { + stats.setStat("alreadyMoved", i + 1); + } + + stats.copyStat("lastX", "lastLastX"); + stats.copyStat("lastZ", "lastLastZ"); + stats.setStat("lastX", x); + stats.setStat("lastZ", z); + stats.setStat("lastSpeed", speed); + stats.setStat("lastAcce", acce); + stats.setStat("SlastOnGround", ground); + if (r == null) { + System.out.println("Result is null, dafuq"); + } + + return r == null ? new CheckResult() : r; + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/movement/speed/SprintCheck.java b/src/main/java/rip/reflex/check/movement/speed/SprintCheck.java new file mode 100644 index 0000000..39d0152 --- /dev/null +++ b/src/main/java/rip/reflex/check/movement/speed/SprintCheck.java @@ -0,0 +1,54 @@ +package rip.reflex.check.movement.speed; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.MovementCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.LocationUtils; + +public class SprintCheck extends MovementCheck { + public SprintCheck() { + super("Speed", "speed.srt", 0, Cheat.valueOf("Speed")); + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + if (!p.isSprinting()) { + return null; + } else { + CheckResult result = new CheckResult(); + int mod = 0; + if (p.isSneaking()) { + result.addTag("sneak sprinting"); + mod += 5; + } + + if (p.isBlocking()) { + result.addTag("block sprinting"); + mod += 5; + } + + if (LocationUtils.isBackwardsMove(from, to)) { + result.addTag("omnidirectional sprinting"); + mod += 2; + } + + if (p.hasPotionEffect(PotionEffectType.BLINDNESS) || p.hasPotionEffect(PotionEffectType.CONFUSION)) { + result.addTag("b/c sprinting"); + mod += 5; + } + + if (p.getFoodLevel() < 6) { + result.addTag("low saturation sprinting"); + mod += 5; + } + + result.setMod(mod); + result.cancel(mod > 0 && Stats.of(p).getViolations(this.cheat) > 14); + return result; + } + } +} diff --git a/src/main/java/rip/reflex/check/movement/speed/TimerCheck.java b/src/main/java/rip/reflex/check/movement/speed/TimerCheck.java new file mode 100644 index 0000000..a123fcf --- /dev/null +++ b/src/main/java/rip/reflex/check/movement/speed/TimerCheck.java @@ -0,0 +1,83 @@ +package rip.reflex.check.movement.speed; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.time.Timer; + +public class TimerCheck extends PacketCheck { + public TimerCheck() { + super("Speed", "speed.tmr", Cheat.valueOf("Speed")); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + if (!Packets.isUpdatePacket(packet)) { + return null; + } else { + CheckResult result = new CheckResult(); + if (!stats.getStat("joinTracker", Timer.class).hasPassed(3000L)) { + this.reset(stats); + return null; + } else { + stats.setStat("packetCounter", stats.getStat("packetCounter", int.class) + 1); + long ticksSinceStart = stats.getStat("lifeStartTracker", Timer.class).getTimePassed() / 50L; + result.addTag("t: " + ticksSinceStart); + result.addTag("p: " + stats.getStat("packetCounter", int.class)); + if ((long)stats.getStat("packetCounter", int.class).intValue() > ticksSinceStart) { + result.setMod(10); + result.cancel(true); + stats.setback(); + this.reset(stats); + } + + return result; + } + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void onTeleport(PlayerTeleportEvent e) { + Stats stats = Stats.of(e.getPlayer()); + if (!e.isCancelled() && stats.getStat("packetCounter", int.class) > 0) { + stats.setStat("packetCounter", stats.getStat("packetCounter", int.class) - 1); + } + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void onJoin(PlayerJoinEvent e) { + Bukkit.getScheduler().runTaskLaterAsynchronously(this.reflex, () -> this.reset(Stats.of(e.getPlayer())), 5L); + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void onWorldChange(PlayerChangedWorldEvent e) { + this.reset(Stats.of(e.getPlayer())); + } + + private void reset(Stats stats) { + stats.getStat("lifeStartTracker", Timer.class).setStartTime(System.currentTimeMillis() - 128L); + stats.setStat("packetCounter", 0); + } +} diff --git a/src/main/java/rip/reflex/check/player/ClientControlCheck.java b/src/main/java/rip/reflex/check/player/ClientControlCheck.java new file mode 100644 index 0000000..2135184 --- /dev/null +++ b/src/main/java/rip/reflex/check/player/ClientControlCheck.java @@ -0,0 +1,316 @@ +package rip.reflex.check.player; + +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import me.flo.flogger.types.FlogLevel; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerRegisterChannelEvent; +import org.bukkit.plugin.messaging.PluginMessageListener; +import rip.reflex.Reflex; +import rip.reflex.api.Cheat; +import rip.reflex.api.event.ReflexCommandEvent; +import rip.reflex.check.base.impl.CustomCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.mod.badlionclient.BadlionConfigMaker; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.mcaccess.MCAccess; + +public class ClientControlCheck extends CustomCheck implements PluginMessageListener { + private final List whitelist = new ArrayList<>(); + + public ClientControlCheck() { + super("ClientControl", "ccontrol.mn", Cheat.valueOf("ClientControl")); + if (VersionUtils.getServerVersion().getVerId() >= MCVersion.V1_13_X.getVerId()) { + this.reflex + .warn( + "ClientControl does not currently support versions newer than 1.12! Reflex will assume that all players' client brand is 'vanilla'. No actions regarding client mods will be taken." + ); + this.disable(); + } else if (this.isEnabledInConfig()) { + Bukkit.getServer().getMessenger().registerIncomingPluginChannel(this.reflex, "5zig_Set", this); + Bukkit.getServer().getMessenger().registerIncomingPluginChannel(this.reflex, "LOLIMAHCKER", this); + Bukkit.getServer().getMessenger().registerIncomingPluginChannel(this.reflex, "BSM", this); + Bukkit.getServer().getMessenger().registerIncomingPluginChannel(this.reflex, "WDL|INIT", this); + Bukkit.getServer().getMessenger().registerIncomingPluginChannel(this.reflex, "MC|Brand", this); + Bukkit.getServer().getMessenger().registerIncomingPluginChannel(this.reflex, "WDL|REQUEST", this); + Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this.reflex, "5zig_Set"); + Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this.reflex, "WDL|CONTROL"); + Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this.reflex, "BSM"); + Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this.reflex, "schematica"); + Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this.reflex, "BLC|M"); + } + } + + @EventHandler( + priority = EventPriority.LOWEST + ) + public void onPlayerJoin(PlayerJoinEvent e) { + if (!this.isDisabled() && this.isEnabledInConfig()) { + StringBuilder s = new StringBuilder("§c §r§5 §r§1 §r§f"); + Player p = e.getPlayer(); + p.sendMessage("§8 §8 §1 §3 §3 §7 §8 "); + int flag = 0; + if (this.getLocalSetting("betterpvp.disable.minimap", Boolean.valueOf(true))) { + flag |= 1; + } + + if (this.getLocalSetting("betterpvp.disable.armor_status", Boolean.valueOf(true))) { + flag |= 2; + } + + if (this.getLocalSetting("betterpvp.disable.potion_status", Boolean.valueOf(true))) { + flag |= 4; + } + + if (this.getLocalSetting("betterpvp.disable.archery_status", Boolean.valueOf(true))) { + flag |= 8; + } + + if (this.getLocalSetting("betterpvp.disable.better_sprint", Boolean.valueOf(true))) { + flag |= 64; + } + + if (this.getLocalSetting("betterpvp.disable.toggle_sneak", Boolean.valueOf(true))) { + flag |= 128; + } + + if (this.getLocalSetting("betterpvp.disable.quick_item_use", Boolean.valueOf(true))) { + flag |= 256; + } + + if (this.getLocalSetting("betterpvp.disable.tnt_notifications", Boolean.valueOf(true))) { + flag |= 524288; + } + + if (this.getLocalSetting("betterpvp.disable.death_points", Boolean.valueOf(true))) { + flag |= 2097152; + } + + if (this.getLocalSetting("betterpvp.disable.entity_info", Boolean.valueOf(true))) { + flag |= 8388608; + } + + String x = String.valueOf(flag); + + for (int i = 0; i < x.length(); i++) { + s.append(" ").append("§r§").append(x, i, i + 1); + } + + p.sendMessage(s.append(" ").toString()); + + try { + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(byteOut); + out.writeByte(0); + out.writeBoolean(!this.getLocalSetting("schematica.disable.printer", Boolean.valueOf(true))); + out.writeBoolean(!this.getLocalSetting("schematica.disable.save", Boolean.valueOf(true))); + out.writeBoolean(!this.getLocalSetting("schematica.disable.load", Boolean.valueOf(true))); + MCAccess.sendPluginMessage(p, "schematica", byteOut.toByteArray()); + } catch (Exception ex) { + throw new RuntimeException("Schematica check failed (" + p.getName() + ")", ex); + } + + if (this.reflex.getSetting("clientcontrol.badlion_client_support", true)) { + MCAccess.sendPluginMessage(p, "BLC|M", BadlionConfigMaker.make(this.reflex)); + } + } + } + + @EventHandler( + priority = EventPriority.LOWEST + ) + public void onChannelRegister(PlayerRegisterChannelEvent e) { + if (!this.isDisabled() && this.isEnabledInConfig()) { + this.channelCheck(e.getPlayer(), e.getChannel(), new byte[0]); + } + } + + public void onPluginMessageReceived(String channel, Player p, byte[] data) { + if (!this.isDisabled() && this.isEnabledInConfig()) { + this.channelCheck(p, channel, data); + } + } + + private void channelCheck(Player p, String channel, byte[] data) { + String chan = Strings.wrap(channel.toLowerCase()).replace("|", "").get(); + if (chan.contains("lol")) { + this.dispatchCommands(p, "vape"); + } else { + if (chan.contains("5zig")) { + ByteArrayDataOutput out = ByteStreams.newDataOutput(); + byte flag = 0; + if (this.getLocalSetting("5zig.disable.potion_effect_hud", Boolean.valueOf(true))) { + flag = (byte)(flag | 1); + } + + if (this.getLocalSetting("5zig.disable.potion_vignette", Boolean.valueOf(true))) { + flag = (byte)(flag | 2); + } + + if (this.getLocalSetting("5zig.disable.armor_hud", Boolean.valueOf(true))) { + flag = (byte)(flag | 4); + } + + if (this.getLocalSetting("5zig.disable.render_saturation", Boolean.valueOf(true))) { + flag = (byte)(flag | 8); + } + + if (this.getLocalSetting("5zig.disable.render_health", Boolean.valueOf(true))) { + flag = (byte)(flag | 16); + } + + if (this.getLocalSetting("5zig.disable.auto_reconnect", Boolean.valueOf(true))) { + flag = (byte)(flag | 32); + } + + if (flag != 0) { + out.writeByte(flag); + MCAccess.sendPluginMessage(p, "5zig_Set", out.toByteArray()); + } + + this.dispatchCommands(p, "5zig"); + } + + if (chan.contains("bsm") || chan.contains("bettersprint")) { + if (this.getLocalSetting("better_sprinting.disable", Boolean.valueOf(true))) { + ByteArrayDataOutput outx = ByteStreams.newDataOutput(); + outx.writeByte(1); + MCAccess.sendPluginMessage(p, "BSM", outx.toByteArray()); + } + + this.dispatchCommands(p, "better_sprinting"); + } + + if (chan.contains("wdl") || chan.contains("worlddownloader")) { + if (this.getLocalSetting("world_downloader.disable", Boolean.valueOf(true))) { + ByteArrayDataOutput outx = ByteStreams.newDataOutput(); + outx.writeInt(0); + outx.writeBoolean(false); + MCAccess.sendPluginMessage(p, "WDL|CONTROL", outx.toByteArray()); + } + + this.dispatchCommands(p, "world_downloader"); + } + + if (chan.contains("mcbrand")) { + String brand; + try { + brand = Strings.asciiOnly(new String(data, "UTF-8")).toLowerCase(); + } catch (Exception ex) { + throw new RuntimeException("Failed to obtain client brand (" + p.getName() + ")", ex); + } + + this.reflex.info(p.getName() + "'s client brand is \"" + brand + "\""); + Stats.of(p).setStat("mcClientBrand", brand); + if (this.getLocalSetting("paranoid_mode.enabled", Boolean.valueOf(false)) && !this.isWhitelisted(brand)) { + this.dispatchAll(p, this.reflex.getConfig().getStringList("clientcontrol.paranoid_mode.actions")); + return; + } + + if (brand.contains("forge") || brand.contains("fml")) { + this.dispatchCommands(p, "forge"); + } + + if (brand.contains("lite")) { + this.dispatchCommands(p, "liteloader"); + } + + if (brand.contains("map")) { + this.dispatchCommands(p, "betterpvp"); + } + } + } + } + + private boolean isWhitelisted(String brand) { + if (this.whitelist.isEmpty()) { + this.reflex.getConfig().getStringList("clientcontrol.paranoid_mode.whitelist").forEach(s -> this.whitelist.add(s.toLowerCase())); + } + + return this.whitelist.contains(brand); + } + + private void notify(Player p, String mod) { + if (this.getLocalSetting("notifications.enabled", Boolean.valueOf(false))) { + LoopHelper.loopPermitted( + staff -> staff.sendMessage( + Strings.wrap( + ChatColor.translateAlternateColorCodes( + '&', Reflex.getReflex().getTheme(p).getPrefix() + this.getLocalSetting("notifications.message", "&9%player% &ris using &9%mod%") + ) + ) + .replace("%player%", p.getName()) + .replace("%ping%", "" + Stats.of(p).getPing()) + .replace("%bannedplayers%", "" + this.reflex.getBanCount()) + .replace("%date%", this.reflex.getDate()) + .replace("%break%", "\n") + .replace("\\n", "\n") + .replace("%tps%", "" + this.reflex.getTpsMeter().getTps()) + .replace("%mod%", Strings.replace(mod.toUpperCase(), "_", " ")) + .replace("%time%", this.reflex.getTime()) + .placeholderApi(p) + .colourizeAndGet() + ), + "reflex.notify" + ); + } + } + + private void dispatchCommands(Player p, String mod) { + this.notify(p, mod); + if (!this.getLocalSetting(mod + ".allow_join", Boolean.valueOf(true))) { + this.dispatchAll(p, this.reflex.getConfig().getStringList("clientcontrol." + mod + ".actions")); + } + } + + private void dispatchAll(Player p, List commands) { + for (String command : commands) { + String id = "#" + UUID.randomUUID().toString().split("-")[0].toUpperCase(); + ReflexCommandEvent cmdEvent = new ReflexCommandEvent(p, this.getCheat(), command, id); + Bukkit.getPluginManager().callEvent(cmdEvent); + if (!cmdEvent.isCancelled()) { + command = cmdEvent.getCommand(); + int d = 0; + if (command.contains("%bannedplayersinlast")) { + d = Integer.valueOf(command.split(Pattern.quote("%bannedplayersinlast"))[1].split(Pattern.quote("days%"))[0]); + } + + command = Strings.wrap(command) + .replace("%player%", p.getName()) + .replace("%ping%", "" + Stats.of(p).getPing()) + .replace("%bannedplayers%", "" + this.reflex.getBanCount()) + .replace("%bannedplayersinlast" + d + "days%", "" + this.reflex.getBanCountIn(TimeUnit.DAYS, (long)d)) + .replace("%execid%", id) + .replace("%id%", id) + .replace("%break%", "\n") + .replace("\\n", "\n") + .replace("%date%", this.reflex.getDate()) + .replace("%tps%", "" + this.reflex.getTpsMeter().getTps()) + .replace("%time%", this.reflex.getTime()) + .placeholderApi(p) + .colourizeAndGet(); + this.reflex + .log( + FlogLevel.DEBUG, + "Dispatching command " + Strings.wrap(command).replace("\n", "%break%").replace(" ", "%space%") + " (execution id: " + id + ")" + ); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); + } + } + } +} diff --git a/src/main/java/rip/reflex/check/player/badpackets/GroundSpoofCheck.java b/src/main/java/rip/reflex/check/player/badpackets/GroundSpoofCheck.java new file mode 100644 index 0000000..cc8d5ef --- /dev/null +++ b/src/main/java/rip/reflex/check/player/badpackets/GroundSpoofCheck.java @@ -0,0 +1,77 @@ +package rip.reflex.check.player.badpackets; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; + +public class GroundSpoofCheck extends PacketCheck { + public GroundSpoofCheck() { + super("BadPackets", "badpcks.grd", Cheat.valueOf("BadPackets")); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + MethodProfiler mp = new MethodProfiler("RE-8132980"); + CheckResult result = new CheckResult(); + if (Packets.isUpdatePacket(packet)) { + boolean clientOnGround = Packets.readBoolean(packet, 0); + if (clientOnGround && stats.hasTimerPassed("grdCheckTracker", 300L)) { + Location loc = p.getLocation().clone(); + Block blockInside = loc.getBlock(); + Block blockBeneath = blockInside.getRelative(BlockFace.DOWN); + Block farBelow = blockBeneath.getRelative(BlockFace.DOWN); + boolean actuallyMidair = blockInside.getType() == Material.AIR + && blockBeneath.getType() == Material.AIR + && farBelow.getType() == Material.AIR + && !LocationUtils.isInLiquid(p); + if (actuallyMidair) { + actuallyMidair = LocationUtils.isPushable(loc); + if (actuallyMidair) { + actuallyMidair = LocationUtils.isPushable(blockBeneath.getLocation()); + } + } + + if (actuallyMidair) { + if (!stats.hasTimerPassed("grdVlTracker", 700L)) { + result.setMod(1).addTag("tried to spoof their ground position").cancel(this.isNotSilent()); + if (result.shouldCancel()) { + Location tpTo = loc.add(0.0, 0.74, 0.0); + double fallDistEstimate = stats.getDouble("fallDistEstimate"); + double damage = Math.max(2.0, fallDistEstimate); + result.addTag("estimated fall distance: " + fallDistEstimate); + p.sendMessage("§bDAMAGE :: §e" + damage); + Bukkit.getScheduler().runTask(this.reflex, () -> { + p.damage(damage); + p.teleport(tpTo); + }); + } + } + + stats.resetTimer("grdVlTracker"); + } + + stats.resetTimer("grdCheckTracker"); + } + } + + mp.addToTimings(); + return result; + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/player/badpackets/InvalidMoveCheck.java b/src/main/java/rip/reflex/check/player/badpackets/InvalidMoveCheck.java new file mode 100644 index 0000000..7680301 --- /dev/null +++ b/src/main/java/rip/reflex/check/player/badpackets/InvalidMoveCheck.java @@ -0,0 +1,87 @@ +package rip.reflex.check.player.badpackets; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.time.Timer; + +public class InvalidMoveCheck extends PacketCheck { + public InvalidMoveCheck() { + super("BadPackets", "badpcks.inv", Cheat.valueOf("BadPackets")); + this.setLagSensetive(false); + LoopHelper.loopStatsEvery(stats -> { + stats.setStat("accurateMoveVl", 0); + stats.setStat("illegalPoslookVl", 0); + stats.setStat("groundcheckVl", 0); + }, 200); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + if (this.isServerLagging()) { + return null; + } else { + MethodProfiler mp = new MethodProfiler("QH-99821658"); + if (packet.getType() != Packets.IN_POSLOOK && packet.getType() != Packets.IN_POSITION) { + return null; + } else { + CheckResult result = new CheckResult(); + if (!stats.hasTimerPassed("worldChangeTracker", 5000L)) { + return null; + } else { + double x = data.getX(); + double y = data.getY(); + double z = data.getZ(); + double dX = Math.abs(x - stats.getStat("pkLastX", double.class)); + double dY = Math.abs(y - stats.getStat("pkLastY", double.class)); + double dZ = Math.abs(z - stats.getStat("pkLastZ", double.class)); + if (stats.getStat("teleportTracker", Timer.class).hasPassed(1000L)) { + if (dX != 0.0 && dX % 1.0 == 0.0 || dZ != 0.0 && dZ % 1.0 == 0.0) { + stats.setStat("accurateMoveVl", stats.getStat("accurateMoveVl", int.class) + 1); + if (stats.getStat("accurateMoveVl", int.class) > this.getLocalSetting("acc_move_threshold", Integer.valueOf(5))) { + result.setMod(2).addTag("type C").cancel(this.isNotSilent()); + stats.setStat("accurateMoveVl", 0); + } + } + + if (dX == 0.0 + && dY == 0.0 + && dZ == 0.0 + && packet.getType().equals(Packets.IN_POSLOOK) + && LocationUtils.isPushable(p) + && data.getYaw() == stats.getStat("pkLastYaw", float.class) + && data.getPitch() == stats.getStat("pkLastPitch", float.class)) { + stats.setStat("illegalPoslookVl", stats.getStat("illegalPoslookVl", int.class) + 1); + if (stats.getStat("illegalPoslookVl", int.class) > this.getLocalSetting("illegal_poslook_threshold", Integer.valueOf(10))) { + result.setMod(3).addTag("type D").cancel(this.isNotSilent()); + stats.setStat("illegalPoslookVl", 0); + } + } + } + + stats.setStat("pkLastX", x); + stats.setStat("pkLastY", y); + stats.setStat("pkLastZ", z); + stats.setStat("pkLastDX", dX); + stats.setStat("pkLastDY", dY); + stats.setStat("pkLastDZ", dZ); + mp.addToTimings(); + return result; + } + } + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/player/badpackets/PacketIgnoranceCheck.java b/src/main/java/rip/reflex/check/player/badpackets/PacketIgnoranceCheck.java new file mode 100644 index 0000000..a30e305 --- /dev/null +++ b/src/main/java/rip/reflex/check/player/badpackets/PacketIgnoranceCheck.java @@ -0,0 +1,107 @@ +package rip.reflex.check.player.badpackets; + +import java.util.Random; +import org.bukkit.World; +import rip.reflex.Reflex; +import rip.reflex.api.Cheat; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.check.base.CheckType; +import rip.reflex.check.base.impl.CustomCheck; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.listener.impl.PlayerMoveListener; +import rip.reflex.listener.impl.PlayerVelocityListener; +import rip.reflex.util.data.Stats; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.time.Timer; + +public class PacketIgnoranceCheck extends CustomCheck { + private final Random newApRand = new Random(); + + public PacketIgnoranceCheck() { + super("BadPackets", "badpcks.ign", Cheat.valueOf("BadPackets")); + this.runTimer( + new ReflexRunnable("AR-UK-80942175") { + @Override + public void execute() throws Exception { + LoopHelper.loopPlayers( + p -> { + MethodProfiler mp = new MethodProfiler("UK-80942175"); + Stats stats = Stats.of(p); + World w = p.getWorld(); + if (!PacketIgnoranceCheck.this.isDisabledInWorld(w) + && stats.canBeChecked(PacketIgnoranceCheck.this) + && stats.hasTimerPassed("worldChangeTracker", 5000L)) { + try { + MethodProfiler mpAp = new MethodProfiler("AR-UK-80942175"); + if (PacketIgnoranceCheck.this.newApRand.nextDouble() > 0.93) { + if (PacketIgnoranceCheck.this.reflex.offlineMode) { + if (!(Maths.objects[4] instanceof Throwable)) { + EventRegistry.unregisterAll(Reflex.getReflex()); + return; + } + + int obj9 = (Integer)Maths.objects[9]; + long obj18 = (Long)Maths.objects[9 * 2]; + if (Long.toString((long)obj9 ^ obj18).equalsIgnoreCase("-8921735296268")) { + int obj12 = (Integer)Maths.objects[12]; + double d12 = (double)obj12; + if ((180.0 / Math.PI) * d12 != 3.805809128799029E7) { + throw new IllegalStateException("asynchronous entity world add"); + } + } else { + CheckRegistry.getActiveChecksOfType(CheckType.PACKET).forEach(Check::disable); + } + } else { + double checksum = Maths.getNewApInstance().sumAllNumeric(); + double divpi = checksum / 3.141592F; + if (divpi != 3.665866260180484E14 + && divpi != -2.0477374628680812E15 + && ((PlayerVelocityListener)EventRegistry.getPlayerVelocityListener()).isNewAPEverRan() + && ((PlayerMoveListener)EventRegistry.getPlayerMoveListener()).isNewApEverCalled()) { + EventRegistry.unregisterAll(Reflex.getReflex()); + PacketIgnoranceCheck.this.disable(); + return; + } + } + } + + mpAp.addToTimings(); + } catch (Exception ignored) { + PacketIgnoranceCheck.this.reflex.log(null, "failed to load FLogger"); + + try { + Maths.objects[0] = -218975; + Maths.objects[22] = "OK"; + } catch (Throwable ignoredEx) { + } + } + + boolean notBypassing = !stats.hasPermission("reflex.bypass." + PacketIgnoranceCheck.this.getName().toLowerCase()) + && !stats.hasPermission("reflex.bypass"); + if (PacketIgnoranceCheck.this.isEnabled() + && PacketIgnoranceCheck.this.isNotSilent() + && notBypassing + && stats.getStat("updateTracker", Timer.class) + .hasPassed((long)PacketIgnoranceCheck.this.getLocalSetting("lag_await_time", Integer.valueOf(1000)).intValue()) + && stats.getStat("pignVlTracker", Timer.class).hasPassed(250L) + && (p.getOpenInventory() == null || VersionUtils.getClientVersion(p).getVerId() < MCVersion.V1_12_X.getVerId())) { + stats.syncTp(p.getLocation().clone()); + } + + mp.addToTimings(); + } + } + ); + } + }, + 5, + true + ); + } +} diff --git a/src/main/java/rip/reflex/check/player/badpackets/PingSpoofCheck.java b/src/main/java/rip/reflex/check/player/badpackets/PingSpoofCheck.java new file mode 100644 index 0000000..3d5d010 --- /dev/null +++ b/src/main/java/rip/reflex/check/player/badpackets/PingSpoofCheck.java @@ -0,0 +1,96 @@ +package rip.reflex.check.player.badpackets; + +import com.comphenix.protocol.events.PacketContainer; +import java.util.SplittableRandom; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.SafeLong; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; +import rip.reflex.util.time.Timer; + +public class PingSpoofCheck extends PacketCheck { + private final SplittableRandom random = new SplittableRandom(); + + public PingSpoofCheck() { + super("BadPackets", "badpcks.spf", Cheat.valueOf("BadPackets")); + this.setLagSensetive(false); + this.setupVlResetThread(45); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + if (this.isServerLagging()) { + return null; + } else { + MethodProfiler mp = new MethodProfiler("LV-291874187"); + CheckResult result = new CheckResult(); + if (!stats.getStat("teleportTracker", Timer.class).hasPassed(20000L)) { + stats.setStat("pingspoofViolations", 0); + stats.setViolations(this.cheat, 0); + return null; + } else if (packet.getType().equals(Packets.IN_KEEPALIVE)) { + stats.setStat("ps_nextId", new SafeLong(-1L)); + return null; + } else { + if (packet.getType().equals(Packets.IN_TRANSACTION) && stats.getSafeLong("ps_nextId").get() != -1L) { + stats.setStat("pingspoofViolations", stats.getStat("pingspoofViolations", int.class) + 3); + if (stats.getStat("pingspoofViolations", int.class) > this.getLocalSetting("latency_threshold", Integer.valueOf(11))) { + stats.setStat("pingspoofViolations", 0); + result.setMod(8).addTag("type A"); + } + } else if (packet.getType().equals(Packets.IN_TRANSACTION) && stats.getStat("pingspoofViolations", int.class) > 0) { + stats.setStat("pingspoofViolations", stats.getStat("pingspoofViolations", int.class) - 1); + } + + mp.addToTimings(); + return result; + } + } + } + + @Override + public CheckResult checkOut(final Player p, final Stats stats, PacketContainer packet) { + MethodProfiler mp = new MethodProfiler("JO-67198912"); + if (!stats.getStat("teleportTracker", Timer.class).hasPassed(20000L)) { + stats.setStat("pingspoofViolations", 0); + stats.setViolations(this.cheat, 0); + return null; + } else { + if (stats.getStat("ps_next", boolean.class)) { + stats.setStat("ps_next", false); + final PacketContainer transPacket = new PacketContainer(Packets.OUT_TRANSACTION); + short tid = (short)((short)this.random.nextInt(32767) * (this.random.nextBoolean() ? 1 : -1)); + transPacket.getBytes().writeSafely(0, (byte)0); + transPacket.getShorts().writeSafely(0, tid); + transPacket.getBooleans().writeSafely(0, false); + ReflexScheduler.sync().run(new ReflexRunnable("JO-219372189") { + @Override + public void execute() throws Exception { + Packets.sendPacketAsync(p, transPacket); + stats.getStat("ps_transactionRequestTracker", Timer.class).reset(); + } + }); + } + + if (packet.getType().equals(Packets.OUT_KEEPALIVE)) { + stats.setStat("ps_next", true); + stats.setStat("ps_nextId", this.readKeepAliveID(packet)); + stats.getStat("ps_keepAliveRequestTracker", Timer.class).reset(); + } + + mp.addToTimings(); + return null; + } + } + + private SafeLong readKeepAliveID(PacketContainer p) { + return p.getIntegers().size() == 0 ? new SafeLong(Packets.readLong(p, 0)) : new SafeLong(Packets.readInteger(p, 0)); + } +} diff --git a/src/main/java/rip/reflex/check/player/badpackets/RepetitiveItemSlotCheck.java b/src/main/java/rip/reflex/check/player/badpackets/RepetitiveItemSlotCheck.java new file mode 100644 index 0000000..9c196ac --- /dev/null +++ b/src/main/java/rip/reflex/check/player/badpackets/RepetitiveItemSlotCheck.java @@ -0,0 +1,46 @@ +package rip.reflex.check.player.badpackets; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; + +public class RepetitiveItemSlotCheck extends PacketCheck { + public RepetitiveItemSlotCheck() { + super("BadPackets", "badpcks.ris", Cheat.valueOf("BadPackets")); + LoopHelper.loopStatsEvery(stats -> { + stats.subtractNumberTilPositive("repetitiveItemSlotVl", 1); + }, 300); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + if (this.isServerLagging()) { + return null; + } else { + if (packet.getType().equals(Packets.IN_HELDITEMCHANGE)) { + int newSlot = (Integer)packet.getIntegers().read(0); + if (stats.hasStat("lastHeldItemSlot")) { + int oldSlot = stats.getInt("lastHeldItemSlot"); + if (newSlot == oldSlot && stats.addNumber("repetitiveItemSlotVl", 1) > 2) { + return new CheckResult().setMod(10).addTag("type E"); + } + } + + stats.setStat("lastHeldItemSlot", newSlot); + } + + return null; + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/player/badpackets/RepetitiveRotationCheck.java b/src/main/java/rip/reflex/check/player/badpackets/RepetitiveRotationCheck.java new file mode 100644 index 0000000..e44d55f --- /dev/null +++ b/src/main/java/rip/reflex/check/player/badpackets/RepetitiveRotationCheck.java @@ -0,0 +1,67 @@ +package rip.reflex.check.player.badpackets; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.performance.LagStatus; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.time.Timer; + +public class RepetitiveRotationCheck extends PacketCheck { + public RepetitiveRotationCheck() { + super("BadPackets", "badpcks.rrn", Cheat.valueOf("BadPackets")); + this.setLagSensetive(false); + LoopHelper.loopStatsEvery(stats -> { + stats.setStat("repRotVl", 0); + }, 200); + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + if (this.isServerLagging()) { + return null; + } else { + MethodProfiler mp = new MethodProfiler("TA-508129358"); + if ((packet.getType().equals(Packets.IN_POSLOOK) || packet.getType().equals(Packets.IN_LOOK)) && !p.isInsideVehicle()) { + CheckResult result = new CheckResult(); + if (!stats.hasTimerTicked("teleportTracker", 20L) + || !stats.hasTimerTicked("moveCancelTracker", 20L) + || !stats.hasTimerPassed("worldChangeTracker", 5000L)) { + return null; + } else if (stats.getLagStatus() == LagStatus.EXTREME_LAG) { + return null; + } else { + float yaw = data.getYaw(); + float pitch = data.getPitch(); + float lastYaw = stats.getStat("pkLastYaw", float.class); + float lastPitch = stats.getStat("pkLastPitch", float.class); + if (yaw == lastYaw && pitch == lastPitch && stats.getStat("teleportTracker", Timer.class).hasPassed(1000L)) { + stats.setStat("repRotVl", stats.getStat("repRotVl", int.class) + 1); + if (stats.getStat("repRotVl", int.class) > this.getLocalSetting("rep_rot_threshold", Integer.valueOf(10))) { + result.setMod(5).addTag("type B"); + stats.setStat("repRotVl", 0); + } + } + + stats.setStat("pkLastYaw", yaw); + stats.setStat("pkLastPitch", pitch); + mp.addToTimings(); + return result; + } + } else { + return null; + } + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/player/badpackets/ReverseTimerGlideCheck.java b/src/main/java/rip/reflex/check/player/badpackets/ReverseTimerGlideCheck.java new file mode 100644 index 0000000..dc43839 --- /dev/null +++ b/src/main/java/rip/reflex/check/player/badpackets/ReverseTimerGlideCheck.java @@ -0,0 +1,60 @@ +package rip.reflex.check.player.badpackets; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.MovementCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; + +public class ReverseTimerGlideCheck extends MovementCheck { + private boolean enabled = this.getLocalSetting("midair_lag_dragdown", Boolean.valueOf(true)); + + public ReverseTimerGlideCheck() { + super("BadPackets", "badpcks.rtg", 0, Cheat.valueOf("BadPackets")); + } + + @Override + public CheckResult check(Player p, Stats stats, Location from, Location to) { + if (this.enabled && from.getWorld().equals(to.getWorld())) { + MethodProfiler mp = new MethodProfiler("HA-218371928"); + if (VersionUtils.getServerVersion().hasMinimum(MCVersion.V1_9_X) + && p.getInventory().getChestplate() != null + && p.getInventory().getChestplate().getType() == Material.ELYTRA) { + return null; + } + + double movedHorizontally = Maths.horizontalDistance(from, to); + Block previous = from.getBlock(); + Block inside = to.getBlock(); + Block beneath = inside.getRelative(BlockFace.DOWN); + boolean airborne = previous.getType() == Material.AIR && inside.getType() == Material.AIR && beneath.getType() == Material.AIR; + if (airborne) { + if (movedHorizontally > 0.228 && stats.hasTimerPassed("rtgOnGroundTracker", 900L) && stats.hasTimerPassed("rtgMoveTracker", 85L)) { + Location tpTo = from.clone().add(0.0, -1.45, 0.0); + if (tpTo.getBlock().getType().isSolid()) { + tpTo.add(0.0, 0.85, 0.0); + } + + tpTo.setYaw(to.getYaw()); + tpTo.setPitch(to.getPitch()); + stats.syncTp(tpTo); + } + } else { + stats.resetTimer("rtgOnGroundTracker"); + } + + stats.resetTimer("rtgMoveTracker"); + mp.addToTimings(); + } + + return null; + } +} diff --git a/src/main/java/rip/reflex/check/player/invactions/ClosedInvClickCheck.java b/src/main/java/rip/reflex/check/player/invactions/ClosedInvClickCheck.java new file mode 100644 index 0000000..34a35f0 --- /dev/null +++ b/src/main/java/rip/reflex/check/player/invactions/ClosedInvClickCheck.java @@ -0,0 +1,45 @@ +package rip.reflex.check.player.invactions; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Event.Result; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.inventory.InventoryType.SlotType; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.impl.CustomCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; + +public class ClosedInvClickCheck extends CustomCheck { + public ClosedInvClickCheck() { + super("InvActions", "invact.civ", Cheat.valueOf("InvActions")); + } + + @EventHandler + public void onInvClick(InventoryClickEvent e) { + MethodProfiler mp = new MethodProfiler("PE-89271380"); + Player p = (Player)e.getWhoClicked(); + Stats stats = Stats.of(p); + if (stats.canBeChecked(this)) { + if (!stats.isInventoryOpened() + && e.getInventory().getType() != InventoryType.CHEST + && e.getSlotType() != SlotType.QUICKBAR + && VersionUtils.getClientVersion(p).getVerId() < MCVersion.V1_12_X.getVerId()) { + CheckResult result = new CheckResult().setMod(2).cancel(this.isNotSilent()).addTag("s: " + e.getRawSlot()); + Check.addVl(stats, this.getCheat(), result); + if (this.isNotSilent()) { + e.setResult(Result.DENY); + } + + Check.check(p, stats, e, this, result); + } + + mp.addToTimings(); + } + } +} diff --git a/src/main/java/rip/reflex/check/player/invactions/FastInvClickCheck.java b/src/main/java/rip/reflex/check/player/invactions/FastInvClickCheck.java new file mode 100644 index 0000000..bbe5dcf --- /dev/null +++ b/src/main/java/rip/reflex/check/player/invactions/FastInvClickCheck.java @@ -0,0 +1,228 @@ +package rip.reflex.check.player.invactions; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Event.Result; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.listener.CentralEventListener; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.listener.impl.PlayerMoveListener; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.misc.Validate; +import rip.reflex.util.performance.LagStatus; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class FastInvClickCheck extends PacketCheck { + public static volatile int newApMagic; + private boolean optEnableEventCheck; + private int optMinEventClickDelay; + private int optMinClickDelay; + private int optConstClickLifespan; + private int optConstClickingThreshold; + private boolean needCheckNewAP; + + public FastInvClickCheck() { + super("InvActions", "invact.fiv", Cheat.valueOf("InvActions")); + this.setSync(true); + this.needCheckNewAP = this.isSync(); + } + + @Override + public void loadAdvancedLocalSettings() { + String enableEventCheck = this.getAdvancedLocalSetting("enable_event_check", "auto"); + switch (enableEventCheck.trim().toLowerCase()) { + case "auto": + this.optEnableEventCheck = VersionUtils.getServerVersion().hasMinimum(MCVersion.V1_9_X); + break; + case "true": + this.optEnableEventCheck = true; + break; + case "false": + this.optEnableEventCheck = false; + break; + default: + this.reflex.warn("INVALID ADVANCED CONFIGURATION (advcfg.yml)! PLEASE FIX ALL THE ISSUES LISTED BELOW BEFORE RESTARTING:"); + this.reflex.warn(" --> enable_event_check: " + enableEventCheck); + this.reflex.warn(" ^ This option must be either 'auto', 'true' or 'false'"); + this.reflex.warn(" "); + this.reflex.warn("Reflex will self-disable."); + Bukkit.getPluginManager().disablePlugin(this.reflex); + return; + } + + this.optMinEventClickDelay = this.getAdvancedLocalSetting("min_event_click_delay", Integer.valueOf(75)); + this.optMinClickDelay = this.getAdvancedLocalSetting("min_click_delay", Integer.valueOf(2)); + this.optConstClickLifespan = this.getAdvancedLocalSetting("const_click_lifespan", Integer.valueOf(2250)); + this.optConstClickingThreshold = this.getAdvancedLocalSetting("const_clicking_threshold", Integer.valueOf(17)); + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void playerClickedInInventory(InventoryClickEvent e) { + if (this.optEnableEventCheck) { + if (!e.isCancelled() && e.getWhoClicked() instanceof Player && e.getClickedInventory() != null) { + MethodProfiler mp = new MethodProfiler("LR-289751982"); + Player p = (Player)e.getWhoClicked(); + Stats stats = Stats.of(p); + if (stats.canBeChecked(this) && stats.getLagStatus().isLowerThan(LagStatus.VIVID_LAG)) { + InventoryType inv = e.getClickedInventory().getType(); + if ((inv == InventoryType.CHEST || inv == InventoryType.ENDER_CHEST || inv.name().contains("SHULKER")) && !e.getAction().name().contains("DROP") + ) + { + ClickType clickType = e.getClick(); + ItemStack curItem = e.getCurrentItem(); + if (!clickType.isKeyboardClick() && curItem != null && curItem.getType() != Material.AIR) { + int slot = e.getRawSlot(); + int lastSlot = stats.getInt("lastInvClickEventSlot"); + stats.setStat("lastInvClickEventSlot", slot); + if (slot != lastSlot) { + if (stats.hasStat("invClickEventTracker") && !stats.hasTimerPassed("invClickEventTracker", (long)this.optMinEventClickDelay)) { + CheckResult result = new CheckResult() + .setMod(1) + .cancel(this.shouldCancel(stats, 2)) + .addTag("click delay (event): " + stats.getTimerPassed("invClickEventTracker")) + .addTag("max: " + this.optMinEventClickDelay); + if (result.shouldCancel()) { + e.setResult(Result.DENY); + } + + Check.addVl(stats, this.cheat, result); + Check.check(p, stats, e, this, result); + } + + stats.resetTimer("invClickEventTracker"); + } + } + } + } + + mp.addToTimings(); + } + } + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void playerJoined(PlayerJoinEvent e) { + if (this.needCheckNewAP) { + ReflexScheduler.async() + .runLater( + ReflexRunnable.simple( + "AR-AQ-28751945", + () -> { + MethodProfiler mp = new MethodProfiler("AQ-28751945"); + + try { + if (((PlayerMoveListener)EventRegistry.getPlayerMoveListener()).isNewApEverCalled()) { + Validate.notNull(Maths.objects[0], "missing sine table (has it been initialized?)"); + int check = 0; + check += (Integer)Maths.objects[19]; + check += (Integer)Maths.objects[13]; + check += (Integer)Maths.objects[7]; + check += (Integer)Maths.objects[21]; + if (!(Maths.objects[4] instanceof Exception) && Maths.objects[18].getClass().getName().contains("Reade") + || Maths.objects[11].toString().equals("-521970218051294") && ((Maths)Maths.objects[3]).sumAllNumeric() == -6.433155684189899E15) { + this.needCheckNewAP = check > 0; + check = -check; + } + + if (check % 100 != 0) { + throw new RuntimeException("invalid click delay (must be a multiple of 100)"); + } + + newApMagic = check; + } + } catch (Throwable ignored) { + Stats.reset(e.getPlayer()); + CentralEventListener.setStopped(true); + this.disable(); + EventRegistry.unregisterAll(this.reflex); + } + + mp.addToTimings(); + } + ), + 20 + ); + } + } + + @Override + public CheckResult checkIn(Player p, Stats stats, PacketContainer packet, SharedPacketData data) { + if (VersionUtils.getServerVersion().hasMinimum(MCVersion.V1_9_X)) { + return null; + } else { + if (Packets.isUpdatePacket(packet)) { + stats.addNumber("ticksSinceLastClick", 1); + } else if (packet.getType().equals(Packets.IN_CLICKWINDOW)) { + MethodProfiler mp = new MethodProfiler("SQ-431897213"); + CheckResult result = new CheckResult(); + if (p.getOpenInventory() != null + && (p.getOpenInventory().getType().name().contains("CHEST") || p.getOpenInventory().getType().name().contains("SHULKER"))) { + int button = (Integer)packet.getIntegers().read(2); + int mode = (Integer)packet.getIntegers().read(3); + if ((button == 0 || button == 1) && (mode == 0 || mode == 1)) { + int clickedSlot = (Integer)packet.getIntegers().read(1); + int lastClickedSlot = stats.getInt("lastClickedSlot"); + stats.setStat("lastClickedSlot", clickedSlot); + if (clickedSlot != lastClickedSlot) { + int clickDist = Math.abs(clickedSlot - lastClickedSlot); + int delay = stats.hasStat("ticksSinceLastClick") ? stats.getInt("ticksSinceLastClick") : 9999; + int lastDelay = stats.getInt("invactFivLastClickDelay"); + int dif = Math.abs(delay - lastDelay); + stats.setStat("invactFivLastClickDelay", delay); + stats.setStat("ticksSinceLastClick", 0); + if (delay < this.optMinClickDelay) { + result.setMod(2).addTag("clicking too quickly in inventory"); + } else if (dif < 2) { + int vl = stats.updateCreatedCounter("constInvClickVlCounter", (long)this.optConstClickLifespan); + if (vl > this.optConstClickingThreshold) { + result.setMod(20).addTag("not clicking naturally in inventory").addTag("vl: " + vl); + stats.removeStat("constInvClickVlCounter"); + } + } + + result.cancel(result.isCheckFailed() && this.shouldCancel(stats, 4)) + .addTag("delay: " + delay) + .addTag("dist: " + clickDist) + .addTag("dif: " + dif); + } + } + + mp.addToTimings(); + return result; + } + + return null; + } + + return null; + } + } + + @Override + public CheckResult checkOut(Player p, Stats stats, PacketContainer packet) { + return null; + } +} diff --git a/src/main/java/rip/reflex/check/world/ScaffoldCheck.java b/src/main/java/rip/reflex/check/world/ScaffoldCheck.java new file mode 100644 index 0000000..63263ad --- /dev/null +++ b/src/main/java/rip/reflex/check/world/ScaffoldCheck.java @@ -0,0 +1,253 @@ +package rip.reflex.check.world; + +import com.comphenix.protocol.wrappers.BlockPosition; +import java.util.Set; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.WorldCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.data.storage.Storage; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.compatibility.Compatibility; +import rip.reflex.util.time.Timer; + +public class ScaffoldCheck extends WorldCheck { + private double optMinHor; + private double optMinDia; + + public ScaffoldCheck() { + super("BlockActions", "blckact.sfd", Cheat.valueOf("BlockActions")); + this.setSync(true); + LoopHelper.loopStatsEvery(stats -> { + stats.setStat("scaffoldBuildspeedVl", 0); + stats.setStat("constBuildspeedVl", 0); + }, 200); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optMinHor = this.getAdvancedLocalSetting("min_hor", Double.valueOf(5.0)); + this.optMinDia = this.getAdvancedLocalSetting("min_dia", Double.valueOf(5.0)); + } + + @Override + public CheckResult check(Player p, Stats stats, Block placed, Block against, ItemStack heldItem) { + if (this.isServerLagging()) { + return null; + } else { + MethodProfiler mp = new MethodProfiler("WG-9479182738"); + if (p.getLocation().getBlockY() - placed.getLocation().getBlockY() == 1 + && placed.getRelative(BlockFace.DOWN).getType().equals(Material.AIR) + && !(Maths.distance(placed.getLocation().clone(), p.getLocation().clone()) > 6.0) + && LocationUtils.isNormalBlock(placed) + && LocationUtils.isBridging(p, stats) + && (p.getLocation().getBlockX() == placed.getX() || p.getLocation().getBlockZ() == placed.getZ()) + && p.getLocation().getBlockY() != placed.getY() + && LocationUtils.isNormalBlock(against) + && !Compatibility.isAny(heldItem, "hoe", "banner", "brewing") + && !Compatibility.isNearby(p, 4, "vine", "ladder", "banner", "wall", "fence") + && LocationUtils.getDirectNeighbors(placed).size() <= 1) { + CheckResult result = new CheckResult(); + Block looking = p.getTargetBlock((Set)null, 120); + double dist = Maths.distance(against.getLocation(), looking.getLocation()); + double yaw = (double)p.getLocation().getYaw(); + double pitch = (double)p.getLocation().getPitch(); + boolean samexz = placed.getLocation().getBlockX() == p.getLocation().getBlockX() && placed.getLocation().getBlockZ() == p.getLocation().getBlockZ(); + boolean pushable = LocationUtils.isPushable(p.getEyeLocation().clone()); + int mod = 0; + Location eye = p.getEyeLocation().clone(); + Location lplaced = placed.getLocation().clone(); + Location lagainst = against.getLocation().clone(); + lplaced.setX((double)Math.round(lplaced.getX()) + 0.5); + lplaced.setY((double)Math.round(lplaced.getY()) + 0.5); + lplaced.setZ((double)Math.round(lplaced.getZ()) + 0.5); + lagainst.setX((double)Math.round(lagainst.getX()) + 0.5); + lagainst.setY((double)Math.round(lagainst.getY()) + 0.5); + lagainst.setZ((double)Math.round(lagainst.getZ()) + 0.5); + double dplaced = Maths.distance(eye, lplaced); + double dagainst = Maths.distance(eye, lagainst); + NumberStorage delays = stats.getOrCreateNumberStorage("scaffoldBuildSpeed", 5); + int buildspeed = Maths.floor(delays.average()); + double d = dplaced - dagainst; + boolean fast = delays.isFull() && buildspeed < this.getLocalSetting("fast_buildspeed_ms", Integer.valueOf(500)); + if (!looking.equals(placed) && fast) { + mod += 3; + result.addTag("type A"); + } + + if (dist > 2.0 && pushable) { + mod += 7; + result.addTag("dist: " + dist); + } + + if (against.getType().equals(Material.AIR) || against.isLiquid()) { + mod += 9; + result.addTag("type B"); + } + + if (d > -0.03 && fast) { + mod += 6; + result.addTag("d: " + d); + } + + if (!samexz && pushable) { + mod += 2; + result.addTag("type C"); + } + + if (yaw % 90.0 == 0.0 || yaw % 1.0 == 0.0) { + Location tp = p.getLocation().clone(); + tp.setYaw(tp.getYaw() + (float)Math.random() * 2.0F); + tp.setPitch(tp.getPitch() + (float)Math.random() * 2.0F); + mod += 9; + result.addTag("type D"); + p.teleport(tp); + } + + if (pitch % 1.0 == 0.0 && Maths.matchEx(pitch, 0, 90)) { + Location tp = p.getLocation().clone(); + tp.setYaw(tp.getYaw() + (float)Math.random() * 2.0F); + tp.setPitch(tp.getPitch() + (float)Math.random() * 2.0F); + mod += 4; + result.addTag("type E"); + p.teleport(tp); + } + + Block lastPlaced = stats.getStat("lastBlockPlaced", Block.class); + if (lastPlaced != null + && lastPlaced.getLocation().getBlock().getRelative(BlockFace.DOWN).getType().equals(Material.AIR) + && lastPlaced.getY() == placed.getY() + && ( + lastPlaced.getX() != placed.getX() && lastPlaced.getZ() == placed.getZ() + || lastPlaced.getX() == placed.getX() && lastPlaced.getZ() != placed.getZ() + )) { + int buildSpeed = (int)stats.getStat("bridgeTracker", Timer.class).getTimePassed(); + stats.addInCreatedNumberStorage("scaffoldBuildSpeed", 5, buildSpeed); + if (pushable) { + if (buildSpeed < 400) { + stats.setStat("lastBuildspeed", buildSpeed); + } + + stats.getStat("bridgeTracker", Timer.class).reset(); + } + } + + if (this.shouldCancel(stats, 10)) { + for (Object o : stats.getStat("recentlyPlaced", Storage.class).values()) { + ((Block)o).setType(Material.AIR); + } + + Location setback = ((Block)stats.getStat("recentlyPlaced", Storage.class).first()).getLocation().clone(); + setback.setYaw(p.getLocation().clone().getYaw() - 180.0F); + setback.setPitch(-90.0F); + stats.resetTimer("buildPenaltyTimer"); + stats.setback(setback); + result.cancel(); + } + + result.setMod(mod > 2 ? mod : 0); + mp.addToTimings(); + return result; + } else { + return null; + } + } + } + + @Override + public CheckResult packetBlockPlace( + Player p, + Stats stats, + Location pLoc, + BlockPosition pos, + ItemStack heldItem, + Material type, + int ticksSincePlace, + int missesSincePlace, + Storage recentPlaced + ) { + if (this.isServerLagging()) { + return null; + } else if (!LocationUtils.isPushable(p.getEyeLocation().clone())) { + return null; + } else { + MethodProfiler mp = new MethodProfiler("WG-19218935"); + ScaffoldCheck.BridgeState state = LocationUtils.getBridgeState(recentPlaced); + if (state == ScaffoldCheck.BridgeState.NOT_BRIDGING) { + return null; + } else { + CheckResult result = new CheckResult(); + if (state == ScaffoldCheck.BridgeState.BRIDGING_HORIZONTALLY) { + NumberStorage delays = stats.getOrCreateNumberStorage("scfHorDelays", 5); + if (delays.addChecking(ticksSincePlace)) { + double avg = delays.average(); + if (avg < this.optMinHor) { + result.setMod(12).addTag("type M").addTag("h: " + avg).cancel(this.isNotSilent()); + } + + delays.clear(); + } + + int minMisses = 0; + if (ticksSincePlace < 5) { + minMisses = 1; + } + + if (ticksSincePlace < 4) { + minMisses = 2; + } + + if (missesSincePlace < minMisses) { + if (stats.addNumber("scfHorAccuracyVl", 3) > 7) { + result.setMod(12) + .addTag("type I") + .addTag("h: " + ticksSincePlace) + .addTag("m: " + missesSincePlace + "/" + minMisses) + .cancel(this.isNotSilent()); + stats.setStat("scfHorAccuracyVl", 0); + } + } else { + stats.subtractNumberTilPositive("scfHorAccuracyVl", 1); + } + } else if (state == ScaffoldCheck.BridgeState.BRIDGING_DIAGONALLY) { + NumberStorage delaysx = stats.getOrCreateNumberStorage("scfDiaDelays", 5); + NumberStorage misses = stats.getOrCreateNumberStorage("scfDiaMisses", 5); + misses.add(missesSincePlace); + if (delaysx.addChecking(ticksSincePlace)) { + double avgDelay = delaysx.average(); + double avgMisses = misses.average(); + if (avgDelay < this.optMinDia) { + result.setMod(12).addTag("type J").addTag("d: " + avgDelay).addTag("m: " + avgMisses).cancel(this.isNotSilent()); + } + + if (avgMisses >= 7.0) { + result.setMod(12).addTag("type K").addTag("d: " + avgDelay).addTag("m: " + avgMisses).cancel(this.isNotSilent()); + } + + delaysx.clear(); + misses.clear(); + } + } + + mp.addToTimings(); + return result; + } + } + } + + public static enum BridgeState { + NOT_BRIDGING, + BRIDGING_HORIZONTALLY, + BRIDGING_DIAGONALLY; + } +} diff --git a/src/main/java/rip/reflex/check/world/TowerCheck.java b/src/main/java/rip/reflex/check/world/TowerCheck.java new file mode 100644 index 0000000..a75a8e8 --- /dev/null +++ b/src/main/java/rip/reflex/check/world/TowerCheck.java @@ -0,0 +1,79 @@ +package rip.reflex.check.world; + +import com.comphenix.protocol.wrappers.BlockPosition; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.impl.WorldCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.data.storage.Storage; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.performance.MethodProfiler; + +public class TowerCheck extends WorldCheck { + private double optMinTw; + + public TowerCheck() { + super("BlockActions", "blckact.tw", Cheat.valueOf("BlockActions")); + this.setSync(true); + } + + @Override + public void loadAdvancedLocalSettings() { + this.optMinTw = this.getAdvancedLocalSetting("min_tw", Double.valueOf(7.5)); + } + + @Override + public CheckResult check(Player p, Stats stats, Block placed, Block against, ItemStack heldItem) { + return null; + } + + @Override + public CheckResult packetBlockPlace( + Player p, + Stats stats, + Location pLoc, + BlockPosition pos, + ItemStack heldItem, + Material type, + int ticksSincePlace, + int missesSincePlace, + Storage recentPlaced + ) { + if (this.isServerLagging()) { + return null; + } else { + MethodProfiler mp = new MethodProfiler("YR-2918381492"); + if (!LocationUtils.isTowering(recentPlaced)) { + return null; + } else { + for (PotionEffect effect : p.getActivePotionEffects()) { + if (effect.getType().equals(PotionEffectType.JUMP) && effect.getAmplifier() > 0) { + return null; + } + } + + CheckResult result = new CheckResult(); + NumberStorage delays = stats.getOrCreateNumberStorage("twDelays", 5); + if (delays.addChecking(ticksSincePlace)) { + double avgDelay = delays.average(); + if (avgDelay < this.optMinTw) { + result.setMod(12).addTag("t: " + avgDelay).cancel(this.isNotSilent()); + } + + delays.clear(); + } + + mp.addToTimings(); + return result; + } + } + } +} diff --git a/src/main/java/rip/reflex/cloud/CloudComputer.java b/src/main/java/rip/reflex/cloud/CloudComputer.java new file mode 100644 index 0000000..7a96871 --- /dev/null +++ b/src/main/java/rip/reflex/cloud/CloudComputer.java @@ -0,0 +1,202 @@ +package rip.reflex.cloud; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckLoader; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.check.combat.killaura.HeuristicsCheck; +import rip.reflex.cloud.protocol.client.ComputeRequestPacket; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.machinelearning.Classifier; +import rip.reflex.util.machinelearning.Dataset; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class CloudComputer { + private final ConcurrentHashMap awaitingResponse = new ConcurrentHashMap<>(); + private static final long MAX_RESPONSE_AWAIT_TIME = TimeUnit.SECONDS.toMillis(15L); + private long requestID = 0L; + private static Check killaura = null; + private final Object requestIDLock = new Object(); + + public static void init() { + killaura = CheckRegistry.getCheck(Cheat.valueOf("KillAura")); + } + + public void cleanup() { + List toRem = new ArrayList<>(); + + for (long id : this.awaitingResponse.keySet()) { + if (this.awaitingResponse.get(id).getQueryTracker().hasPassed(MAX_RESPONSE_AWAIT_TIME)) { + toRem.add(id); + } + } + + toRem.forEach(this.awaitingResponse::remove); + } + + private void requestCompute(Player p, int checkID, Object checkData, int debugML, Dataset heurSnapshot) { + if (!Reflex.getReflex().offlineMode) { + synchronized (this.requestIDLock) { + long id = ++this.requestID; + this.awaitingResponse.put(id, new ComputeEntry(p, debugML, heurSnapshot)); + ReflexScheduler.async() + .run( + ReflexRunnable.simple( + "KR-56791238", + () -> Reflex.getReflex().getCloudService().getClient().getProtocolManager().sendPacket(new ComputeRequestPacket(id, checkID, checkData)) + ) + ); + } + } + } + + public void heuristicsCheck(Player p, Dataset ds, int debug) { + if (killaura == null) { + init(); + } + + this.requestCompute(p, 0, ds.serialize(), debug, debug > 0 ? ds.clone() : null); + } + + public void smallYawStatisticCheck(Player p, NumberStorage smallStorage) { + if (killaura == null) { + init(); + } + + this.requestCompute(p, 1, smallStorage.serialize(), 0, null); + } + + public void mediumYawStatisticCheck(Player p, NumberStorage mediumStorage) { + if (killaura == null) { + init(); + } + + this.requestCompute(p, 2, mediumStorage.serialize(), 0, null); + } + + public void bigYawStatisticCheck(Player p, NumberStorage bigStorage) { + if (killaura == null) { + init(); + } + + this.requestCompute(p, 3, bigStorage.serialize(), 0, null); + } + + public void process(Player p, int checkID, String response, int debugML, Dataset heurSnapshot) { + if (!Reflex.getReflex().offlineMode) { + try { + MethodProfiler mp = new MethodProfiler("DX-1293091"); + if (checkID == -1) { + Reflex.getReflex().warn("Cloud responsed with an error. Please report this!"); + return; + } + + String[] s = response.split("//"); + Stats stats = Stats.of(p); + boolean legit = s[0].equals("LEGIT"); + switch (checkID) { + case 0: + if (!legit && stats.canBeChecked(killaura)) { + int severity = killaura.getLocalSetting("heuristics_severity", 1); + int detected = Integer.parseInt(s[1]); + int cp = Integer.parseInt(s[4]); + String cheatAttr = s[5]; + HeuristicsCheck.FinalDecision decision = HeuristicsCheck.isCheater(detected, severity, cp, stats.getLagStatus()); + if (decision.isCheater()) { + CheckResult result = new CheckResult() + .setMod(detected * 100) + .addTag("suspicious combat style (NN analysis)") + .addTag("best match: #" + s[2]) + .addTag("conviction: " + (Double.valueOf(s[3]) - Math.random() * 5.0) + "%") + .addTag("severity: " + severity) + .addTag("cloud") + .addTag("cp: " + cp) + .addTagIf("attr: " + cheatAttr, cp > 0) + .addTagIf("cp::wth", decision.isWayTooHighCP()) + .addTagIf("cp::hnl", decision.isHighCPNotLagging()) + .addTagIf("cp::hct", decision.isHighCPCertain()) + .addTagIf(heurSnapshot == null ? "?" : "snapshot id: " + heurSnapshot.getName(), debugML > 0); + Check.addVl(stats, CheckLoader.heuristicsCheck.getCheat(), result); + Check.check(p, stats, null, CheckLoader.heuristicsCheck, result); + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + 100); + } + + if (heurSnapshot != null) { + Classifier.debugHeur(!decision.isCheater(), heurSnapshot.setLegit(!decision.isCheater()), p, debugML); + } + } + break; + case 1: + if (!legit && stats.canBeChecked(killaura)) { + CheckResult result = new CheckResult() + .setMod(100) + .addTag("aimbot (short-term statistic)") + .addTag("s: " + s[1]) + .addTag("m: " + s[2]) + .addTag("dm: " + s[3]) + .addTag("dv: " + s[4]) + .addTag("a: " + s[5]) + .addTag("l: " + s[6]) + .addTag("r: " + s[7]) + .addTag("cloud"); + Check.addVl(stats, CheckLoader.yawStatCheck.getCheat(), result); + Check.check(p, stats, null, CheckLoader.yawStatCheck, result); + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + 100); + } + break; + case 2: + if (!legit && stats.canBeChecked(killaura)) { + CheckResult result = new CheckResult() + .setMod(100) + .addTag("aimbot (middle-term statistic)") + .addTag("m: " + s[1]) + .addTag("v: " + s[2]) + .addTag("s: " + s[3]) + .addTag("k: " + s[4]) + .addTag("cloud"); + Check.addVl(stats, CheckLoader.yawStatCheck.getCheat(), result); + Check.check(p, stats, null, CheckLoader.yawStatCheck, result); + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + 100); + } + break; + case 3: + if (!legit && stats.canBeChecked(killaura)) { + CheckResult result = new CheckResult() + .setMod(100) + .addTag("aimbot (long-term statistic)") + .addTag("s: " + s[1]) + .addTag("k: " + s[2]) + .addTag("a: " + s[3]) + .addTag("l: " + s[4]) + .addTag("cloud"); + Check.addVl(stats, CheckLoader.yawStatCheck.getCheat(), result); + Check.check(p, stats, null, CheckLoader.yawStatCheck, result); + stats.setStat("combinedFailed", stats.getStat("combinedFailed", int.class) + 100); + } + break; + default: + Reflex.getReflex().getLogger().warning("Unexpected response from Cloud: \"" + response + "\" (" + checkID + ")"); + } + + mp.addToTimings(); + } catch (Exception ex) { + System.err.println("ERROR PROCESSING CLOUD COMPUTE RESPONSE"); + ex.printStackTrace(); + } + } + } + + public ConcurrentHashMap getAwaitingResponse() { + return this.awaitingResponse; + } +} diff --git a/src/main/java/rip/reflex/cloud/CloudService.java b/src/main/java/rip/reflex/cloud/CloudService.java new file mode 100644 index 0000000..22e2dcb --- /dev/null +++ b/src/main/java/rip/reflex/cloud/CloudService.java @@ -0,0 +1,234 @@ +package rip.reflex.cloud; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import me.darksidecode.easysockets.client.BasicSocketClient; +import me.darksidecode.easysockets.client.config.SCConfigBuilder; +import me.darksidecode.easysockets.client.config.SocketClientConfig; +import me.darksidecode.easysockets.event.client.ClientTimeoutEvent; +import org.bukkit.Bukkit; +import rip.reflex.Reflex; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckLoader; +import rip.reflex.cloud.listener.AuthResponseListener; +import rip.reflex.cloud.listener.ComputeResponseListener; +import rip.reflex.cloud.listener.PingListener; +import rip.reflex.cloud.protocol.client.AuthRequestPacket; +import rip.reflex.util.location.Movement; +import rip.reflex.util.machinelearning.Classifier; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; +import rip.reflex.util.time.Timer; + +public class CloudService { + public static final int PROTOCOL_VERSION = 3; + private static final String TRUST_STORE_FILE_NAME = "reflex-ts.jks"; + private static final String TRUST_STORE_PASSWORD = "Nfn4er"; + private static final int HEARTBEAT_PERIOD = 6000; + private static final int HEARTBEAT_TIMEOUT = 60000; + private static final long MIN_RECONNECT_DELAY = 30000L; + private final Reflex reflex; + private String lastKey; + private CloudComputer cloudComputer; + private BasicSocketClient client; + private int ping; + private boolean stopped; + private Timer stopTracker = new Timer(0L); + private Timer pingTracker = new Timer(0L); + private int reconnections; + private boolean heartbeatRan; + private boolean reconnecting; + private final Object connectionLock = new Object(); + private final List cloudSupportedChecks = new ArrayList<>(); + private final Timer connectTracker = new Timer(0L); + + public CloudService(Reflex reflex) { + this.reflex = reflex; + } + + public boolean isConnected() { + return this.cloudComputer != null && !this.stopped; + } + + public void reconnect() { + if (!this.stopped) { + int maxReconnections = this.reflex.getSetting("general.cloud_computings.max_reconnections", 5); + if (maxReconnections > 0) { + synchronized (this.connectionLock) { + if (++this.reconnections > maxReconnections) { + this.reflex.info("Failed to reconnect after " + maxReconnections + " attempts. Giving up."); + this.stop(); + return; + } + + this.reflex.info("Performing reconnection attempt " + this.reconnections + "/" + maxReconnections + "..."); + if (this.client != null) { + this.client.shutdown(); + this.client = null; + } + + this.cloudComputer = null; + this.connect(this.lastKey); + } + } else { + this.reflex.info("general.cloud_computings.max_reconnections is set to " + maxReconnections + ". No reconnection attempts will be performed"); + this.stop(); + } + } + } + + public void runHeartbeat() { + if (!this.heartbeatRan) { + this.heartbeatRan = true; + this.pingTracker.reset(); + ReflexScheduler.async().runTimer(new ReflexRunnable("PS-32391945") { + @Override + public void execute() throws Exception { + if (!CloudService.this.stopped && !CloudService.this.reconnecting && CloudService.this.pingTracker.hasPassed(60000L)) { + CloudService.this.connectionLost("heartbeat"); + } + } + }, 6000); + } + } + + private void connectionLost(String reason) { + this.reflex.warn("Lost connection with Cloud! (" + reason + ")"); + this.cloudComputer = null; + this.reconnecting = true; + + try { + this.reconnect(); + } catch (Throwable ex) { + System.err.println("ERROR DURING RECONNECTION"); + ex.printStackTrace(); + } + + this.reconnecting = false; + } + + public void connect(String token) { + if (!this.stopped) { + new Thread(() -> { + synchronized (this.connectionLock) { + try { + if (!this.connectTracker.hasPassed(30000L)) { + throw new IllegalStateException("Reconnect limit of 1 time per 30 seconds exceeded"); + } + + this.connectTracker.reset(); + this.cloudComputer = null; + this.lastKey = token; + if (this.client != null) { + this.reflex.warn("There is already an active Cloud connection. Closing it"); + this.client.shutdown(); + } + + if (token == null || token.trim().length() < 2) { + this.reflex.warn("Invalid Cloud token. No connection attempt will be performed"); + CheckLoader.loadAll(this.reflex); + return; + } + + this.reflex.info("Connecting to Cloud..."); + int port = this.reflex.getSetting("general.cloud_computings.port", 8109); + if (port != 8109) { + this.reflex.warn("Connecting to Cloud through NON-DEFAULT PORT!"); + } + + SocketClientConfig config = new SCConfigBuilder().sendRateLimit(100).receiveRateLimit(100).maxPacketSize(33554432).timeout(60000).build(); + boolean cloudSSL = this.reflex.getSetting("general.cloud_computings.ssl", false); + if (cloudSSL) { + config.setUseSSL(true); + config.setTrustStoreStream(this.getTrustStore()); + config.setTrustStorePassword("Nfn4er"); + } + + String host = this.reflex.getSyncServer().getCloudHost(); + this.client = new BasicSocketClient(3, host, port, null, config); + this.client.getEventManager().registerListener(new PingListener()); + this.client.getEventManager().registerListener(new AuthResponseListener()); + this.client.getEventManager().registerListener(new ComputeResponseListener()); + this.client.getEventManager().registerListener(e -> { + if (!this.stopped && e instanceof ClientTimeoutEvent) { + this.reflex.warn("Cloud may has stopped responding (scheduled restart?)"); + this.cloudComputer = null; + } + }); + + int id; + try { + id = Integer.parseInt(Movement.getApinstance().getId()); + } catch (Exception ignored) { + Bukkit.getPluginManager().disablePlugin(this.reflex); + return; + } + + this.client.getProtocolManager().sendPacket(new AuthRequestPacket(id, token)); + } catch (Exception cause) { + if (this.client != null) { + this.client.shutdown(); + this.client = null; + } + + this.reflex.warn("Failed to connect to Cloud: " + cause.toString()); + this.cloudComputer = null; + } + } + }, "Reflex Cloud Connection Thread").start(); + } + } + + private InputStream getTrustStore() { + return this.reflex.getResource("reflex-ts.jks"); + } + + private void stop() { + synchronized (this.connectionLock) { + this.reflex.info("Reflex Cloud Service shutting down"); + this.stopped = true; + this.cloudComputer = null; + this.stopTracker.reset(); + if (this.reflex.getSetting("general.cloud_computings.auto_switch", true)) { + if (Classifier.getNetlist().isEmpty()) { + ReflexScheduler.async().run(ReflexRunnable.simple("CY-4921934", Classifier::init)); + } + } else { + this.cloudSupportedChecks.forEach(Check::disableComponent); + } + } + } + + public CloudComputer getCloudComputer() { + return this.cloudComputer; + } + + public void setCloudComputer(CloudComputer cloudComputer) { + this.cloudComputer = cloudComputer; + } + + public BasicSocketClient getClient() { + return this.client; + } + + public int getPing() { + return this.ping; + } + + public void setPing(int ping) { + this.ping = ping; + } + + public Timer getPingTracker() { + return this.pingTracker; + } + + public void setReconnections(int reconnections) { + this.reconnections = reconnections; + } + + public List getCloudSupportedChecks() { + return this.cloudSupportedChecks; + } +} diff --git a/src/main/java/rip/reflex/cloud/ComputeEntry.java b/src/main/java/rip/reflex/cloud/ComputeEntry.java new file mode 100644 index 0000000..697652d --- /dev/null +++ b/src/main/java/rip/reflex/cloud/ComputeEntry.java @@ -0,0 +1,35 @@ +package rip.reflex.cloud; + +import org.bukkit.entity.Player; +import rip.reflex.util.machinelearning.Dataset; +import rip.reflex.util.time.Timer; + +public class ComputeEntry { + private final Player player; + private final Timer queryTracker; + private final int debugML; + private final Dataset heurSnapshot; + + public ComputeEntry(Player player, int debugML, Dataset heurSnapshot) { + this.player = player; + this.debugML = debugML; + this.heurSnapshot = heurSnapshot; + this.queryTracker = new Timer(); + } + + public Player getPlayer() { + return this.player; + } + + public Timer getQueryTracker() { + return this.queryTracker; + } + + public int getDebugML() { + return this.debugML; + } + + public Dataset getHeurSnapshot() { + return this.heurSnapshot; + } +} diff --git a/src/main/java/rip/reflex/cloud/KeyGenerator.java b/src/main/java/rip/reflex/cloud/KeyGenerator.java new file mode 100644 index 0000000..7d335a3 --- /dev/null +++ b/src/main/java/rip/reflex/cloud/KeyGenerator.java @@ -0,0 +1,15 @@ +package rip.reflex.cloud; + +import rip.reflex.util.misc.Strings; + +public class KeyGenerator { + private static final String CHARSET = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890"; + + public static void main(String[] args) { + System.out.println(eGen() + "-" + eGen() + "-" + eGen()); + } + + private static String eGen() { + return Strings.randomComp(10, "QWERTYUIOPASDFGHJKLZXCVBNM1234567890"); + } +} diff --git a/src/main/java/rip/reflex/cloud/listener/AuthResponseListener.java b/src/main/java/rip/reflex/cloud/listener/AuthResponseListener.java new file mode 100644 index 0000000..d41cc04 --- /dev/null +++ b/src/main/java/rip/reflex/cloud/listener/AuthResponseListener.java @@ -0,0 +1,72 @@ +package rip.reflex.cloud.listener; + +import java.util.ArrayList; +import java.util.Date; +import java.util.concurrent.TimeUnit; +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventListener; +import me.darksidecode.easysockets.event.client.ClientPacketReceiveEvent; +import me.darksidecode.easysockets.protocol.packet.Packet; +import rip.reflex.Reflex; +import rip.reflex.check.base.CheckLoader; +import rip.reflex.cloud.CloudComputer; +import rip.reflex.cloud.protocol.server.AuthResponsePacket; +import rip.reflex.util.machinelearning.Classifier; + +public class AuthResponseListener implements EventListener { + @Override + public void onEvent(Event event) { + if (event.isPost() && event instanceof ClientPacketReceiveEvent) { + ClientPacketReceiveEvent e = (ClientPacketReceiveEvent)event; + Packet p = e.getPacket(); + if (p.getType().equals("RC_AUTH_RES")) { + AuthResponsePacket response = new AuthResponsePacket(p); + String errorMessage = null; + switch (response.getResponseCode()) { + case 0: + Reflex.getReflex().info("Cloud connection has been established successfully"); + Reflex.getReflex().getCloudService().setCloudComputer(new CloudComputer()); + Reflex.getReflex().getCloudService().setReconnections(0); + long expireTime = response.getExpireDate(); + long left = expireTime - System.currentTimeMillis(); + String expireStr = Reflex.getReflex().getDateFormat().format(new Date(expireTime)); + long daysLeft = TimeUnit.MILLISECONDS.toDays(left); + Reflex.getReflex().info("Your Cloud key expires " + expireStr); + if (left <= TimeUnit.DAYS.toMillis(3L)) { + Reflex.getReflex().warn("-----------------------------------------------"); + Reflex.getReflex().warn(" WARNING:"); + Reflex.getReflex().warn(" Your Cloud Computings key expires " + (daysLeft > 0L ? "in " + daysLeft + " day(s)" : "TODAY") + "!"); + Reflex.getReflex().warn(" Don't forget to renew it if you wish to continue using this feature!"); + Reflex.getReflex().warn("-----------------------------------------------"); + } + break; + case 1: + errorMessage = "invalid request"; + break; + case 2: + errorMessage = "invalid user"; + break; + case 3: + errorMessage = "unauthorized user (key banned)"; + break; + case 4: + errorMessage = "internal error, please report this"; + break; + case 5: + errorMessage = "the key is invalid or expired"; + break; + default: + errorMessage = "unknown error " + response.getResponseCode(); + } + + CheckLoader.loadAll(Reflex.getReflex()); + if (errorMessage == null) { + Classifier.getNetlist().forEach(ArrayList::clear); + Classifier.getNetlist().clear(); + } else { + Reflex.getReflex().warn("Failed to connect to Cloud: " + errorMessage); + } + } + } + } +} diff --git a/src/main/java/rip/reflex/cloud/listener/ComputeResponseListener.java b/src/main/java/rip/reflex/cloud/listener/ComputeResponseListener.java new file mode 100644 index 0000000..ba39c4f --- /dev/null +++ b/src/main/java/rip/reflex/cloud/listener/ComputeResponseListener.java @@ -0,0 +1,36 @@ +package rip.reflex.cloud.listener; + +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventListener; +import me.darksidecode.easysockets.event.client.ClientPacketReceiveEvent; +import me.darksidecode.easysockets.protocol.packet.Packet; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.cloud.CloudComputer; +import rip.reflex.cloud.ComputeEntry; +import rip.reflex.cloud.protocol.server.ComputeResponsePacket; +import rip.reflex.util.crypto.CloudEncoder; + +public class ComputeResponseListener implements EventListener { + @Override + public void onEvent(Event event) { + if (event.isPost() && event instanceof ClientPacketReceiveEvent) { + ClientPacketReceiveEvent e = (ClientPacketReceiveEvent)event; + Packet packet = e.getPacket(); + if (packet.getType().equals("RC_COMP_RES")) { + ComputeResponsePacket response = new ComputeResponsePacket(packet); + CloudComputer cc = Reflex.getReflex().getCloudService().getCloudComputer(); + long id = response.getRequestID(); + int checkID = response.getCheckID(); + ComputeEntry entry = cc.getAwaitingResponse().get(id); + if (entry != null) { + Player p = entry.getPlayer(); + if (p != null) { + cc.getAwaitingResponse().remove(id); + cc.process(p, checkID, CloudEncoder.decodeInner(response.getResult()), entry.getDebugML(), entry.getHeurSnapshot()); + } + } + } + } + } +} diff --git a/src/main/java/rip/reflex/cloud/listener/PingListener.java b/src/main/java/rip/reflex/cloud/listener/PingListener.java new file mode 100644 index 0000000..2c30f7d --- /dev/null +++ b/src/main/java/rip/reflex/cloud/listener/PingListener.java @@ -0,0 +1,27 @@ +package rip.reflex.cloud.listener; + +import me.darksidecode.easysockets.event.Event; +import me.darksidecode.easysockets.event.EventListener; +import me.darksidecode.easysockets.event.client.ClientPacketReceiveEvent; +import me.darksidecode.easysockets.protocol.packet.Packet; +import rip.reflex.Reflex; +import rip.reflex.cloud.CloudService; +import rip.reflex.cloud.protocol.PingPacket; +import rip.reflex.util.math.Maths; + +public class PingListener implements EventListener { + @Override + public void onEvent(Event event) { + if (event.isPost() && event instanceof ClientPacketReceiveEvent) { + ClientPacketReceiveEvent e = (ClientPacketReceiveEvent)event; + Packet p = e.getPacket(); + if (p.getType().equals("RC_PING")) { + CloudService service = Reflex.getReflex().getCloudService(); + PingPacket ping = new PingPacket(p); + service.setPing(Math.max(1, Maths.floor((double)ping.getId() / 2.0))); + service.getClient().getProtocolManager().sendPacket(ping); + service.getPingTracker().reset(); + } + } + } +} diff --git a/src/main/java/rip/reflex/cloud/protocol/CloudProtocol.java b/src/main/java/rip/reflex/cloud/protocol/CloudProtocol.java new file mode 100644 index 0000000..9b400d3 --- /dev/null +++ b/src/main/java/rip/reflex/cloud/protocol/CloudProtocol.java @@ -0,0 +1,13 @@ +package rip.reflex.cloud.protocol; + +public class CloudProtocol { + public static final String HOST = "ccd.reflex.rip"; + public static final int PORT = 8109; + public static final int E2E_AES256_ITERS = 5; + public static final int MAX_PACKET_SIZE = 33554432; + public static final int SEND_RATE_LIMIT = 100; + public static final int RECEIVE_RATE_LIMIT = 100; + public static final int TIMEOUT = 60000; + public static final byte[] AES_KEY = new byte[]{48, -21, 62, 98, 83, -100, -43, -87, 79, 47, 88, 8, -100, 61, 57, 53}; + public static final byte[] AES_IV = new byte[]{87, 61, -32, 27, 40, -116, 17, -66, 74, -41, 126, -26, -42, 98, -47, -104}; +} diff --git a/src/main/java/rip/reflex/cloud/protocol/PacketType.java b/src/main/java/rip/reflex/cloud/protocol/PacketType.java new file mode 100644 index 0000000..257ed61 --- /dev/null +++ b/src/main/java/rip/reflex/cloud/protocol/PacketType.java @@ -0,0 +1,15 @@ +package rip.reflex.cloud.protocol; + +public class PacketType { + public static final String PING = "RC_PING"; + + public static class Client { + public static final String AUTH_REQUEST = "RC_AUTH_REQ"; + public static final String COMPUTE_REQUEST = "RC_COMP_REQ"; + } + + public static class Server { + public static final String AUTH_RESPONSE = "RC_AUTH_RES"; + public static final String COMPUTE_RESPONSE = "RC_COMP_RES"; + } +} diff --git a/src/main/java/rip/reflex/cloud/protocol/PingPacket.java b/src/main/java/rip/reflex/cloud/protocol/PingPacket.java new file mode 100644 index 0000000..0312380 --- /dev/null +++ b/src/main/java/rip/reflex/cloud/protocol/PingPacket.java @@ -0,0 +1,43 @@ +package rip.reflex.cloud.protocol; + +import me.darksidecode.easysockets.protocol.packet.Packet; +import me.darksidecode.easysockets.protocol.packet.PacketSignatureError; + +public class PingPacket extends Packet { + private int id; + + public PingPacket(int id) { + super("RC_PING"); + this.id = id; + } + + public PingPacket(Packet source) { + super("RC_PING"); + if (!source.getType().equals("RC_PING")) { + throw new PacketSignatureError("Not a RC_PING packet, but " + source.getType()); + } else { + this.setContents(source.getContents()); + this.readAll(); + } + } + + @Override + public Packet readAll() { + this.id = this.getContents().readInteger(0); + return this; + } + + @Override + public Packet writeAll() { + this.getContents().write(0, this.id); + return this; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } +} diff --git a/src/main/java/rip/reflex/cloud/protocol/client/AuthRequestPacket.java b/src/main/java/rip/reflex/cloud/protocol/client/AuthRequestPacket.java new file mode 100644 index 0000000..0a9f1c2 --- /dev/null +++ b/src/main/java/rip/reflex/cloud/protocol/client/AuthRequestPacket.java @@ -0,0 +1,55 @@ +package rip.reflex.cloud.protocol.client; + +import me.darksidecode.easysockets.protocol.packet.Packet; +import me.darksidecode.easysockets.protocol.packet.PacketSignatureError; + +public class AuthRequestPacket extends Packet { + private int spigotID; + private String key; + + public AuthRequestPacket(int spigotID, String key) { + super("RC_AUTH_REQ"); + this.spigotID = spigotID; + this.key = key; + } + + public AuthRequestPacket(Packet source) { + super("RC_AUTH_REQ"); + if (!source.getType().equals("RC_AUTH_REQ")) { + throw new PacketSignatureError("Not a RC_AUTH_REQ packet, but " + source.getType()); + } else { + this.setContents(source.getContents()); + this.readAll(); + } + } + + @Override + public Packet readAll() { + this.spigotID = this.getContents().readInteger(0); + this.key = this.getContents().readString(1); + return this; + } + + @Override + public Packet writeAll() { + this.getContents().write(0, this.spigotID); + this.getContents().write(1, this.key); + return this; + } + + public int getSpigotID() { + return this.spigotID; + } + + public String getKey() { + return this.key; + } + + public void setSpigotID(int spigotID) { + this.spigotID = spigotID; + } + + public void setKey(String key) { + this.key = key; + } +} diff --git a/src/main/java/rip/reflex/cloud/protocol/client/ComputeRequestPacket.java b/src/main/java/rip/reflex/cloud/protocol/client/ComputeRequestPacket.java new file mode 100644 index 0000000..a848151 --- /dev/null +++ b/src/main/java/rip/reflex/cloud/protocol/client/ComputeRequestPacket.java @@ -0,0 +1,67 @@ +package rip.reflex.cloud.protocol.client; + +import me.darksidecode.easysockets.protocol.packet.Packet; +import me.darksidecode.easysockets.protocol.packet.PacketSignatureError; + +public class ComputeRequestPacket extends Packet { + private long requestID; + private int checkID; + private Object checkData; + + public ComputeRequestPacket(long requestID, int checkID, Object checkData) { + super("RC_COMP_REQ"); + this.requestID = requestID; + this.checkID = checkID; + this.checkData = checkData; + } + + public ComputeRequestPacket(Packet source) { + super("RC_COMP_REQ"); + if (!source.getType().equals("RC_COMP_REQ")) { + throw new PacketSignatureError("Not a RC_COMP_REQ packet, but " + source.getType()); + } else { + this.setContents(source.getContents()); + this.readAll(); + } + } + + @Override + public Packet readAll() { + this.requestID = this.getContents().readLong(0); + this.checkID = this.getContents().readInteger(1); + this.checkData = this.getContents().readObject(2); + return this; + } + + @Override + public Packet writeAll() { + this.getContents().write(0, this.requestID); + this.getContents().write(1, this.checkID); + this.getContents().write(2, this.checkData); + return this; + } + + public long getRequestID() { + return this.requestID; + } + + public int getCheckID() { + return this.checkID; + } + + public Object getCheckData() { + return this.checkData; + } + + public void setRequestID(long requestID) { + this.requestID = requestID; + } + + public void setCheckID(int checkID) { + this.checkID = checkID; + } + + public void setCheckData(Object checkData) { + this.checkData = checkData; + } +} diff --git a/src/main/java/rip/reflex/cloud/protocol/meta/AuthResponseCode.java b/src/main/java/rip/reflex/cloud/protocol/meta/AuthResponseCode.java new file mode 100644 index 0000000..a687c9e --- /dev/null +++ b/src/main/java/rip/reflex/cloud/protocol/meta/AuthResponseCode.java @@ -0,0 +1,10 @@ +package rip.reflex.cloud.protocol.meta; + +public class AuthResponseCode { + public static final int SUCCESS = 0; + public static final int INVALID_REQUEST = 1; + public static final int INVALID_USER = 2; + public static final int UNAUTHORIZED_USER = 3; + public static final int INTERNAL_ERROR = 4; + public static final int INVALID_KEY = 5; +} diff --git a/src/main/java/rip/reflex/cloud/protocol/meta/CheckID.java b/src/main/java/rip/reflex/cloud/protocol/meta/CheckID.java new file mode 100644 index 0000000..e3854c1 --- /dev/null +++ b/src/main/java/rip/reflex/cloud/protocol/meta/CheckID.java @@ -0,0 +1,9 @@ +package rip.reflex.cloud.protocol.meta; + +public class CheckID { + public static final int ERROR = -1; + public static final int MACHINE_LEARNING = 0; + public static final int SMALL_YAW_STAT = 1; + public static final int MEDIUM_YAW_STAT = 2; + public static final int BIG_YAW_STAT = 3; +} diff --git a/src/main/java/rip/reflex/cloud/protocol/server/AuthResponsePacket.java b/src/main/java/rip/reflex/cloud/protocol/server/AuthResponsePacket.java new file mode 100644 index 0000000..a14f34a --- /dev/null +++ b/src/main/java/rip/reflex/cloud/protocol/server/AuthResponsePacket.java @@ -0,0 +1,55 @@ +package rip.reflex.cloud.protocol.server; + +import me.darksidecode.easysockets.protocol.packet.Packet; +import me.darksidecode.easysockets.protocol.packet.PacketSignatureError; + +public class AuthResponsePacket extends Packet { + private int responseCode; + private long expireDate; + + public AuthResponsePacket(int responseCode, long expireDate) { + super("RC_AUTH_RES"); + this.responseCode = responseCode; + this.expireDate = expireDate; + } + + public AuthResponsePacket(Packet source) { + super("RC_AUTH_RES"); + if (!source.getType().equals("RC_AUTH_RES")) { + throw new PacketSignatureError("Not a RC_AUTH_RES packet, but " + source.getType()); + } else { + this.setContents(source.getContents()); + this.readAll(); + } + } + + @Override + public Packet readAll() { + this.responseCode = this.getContents().readInteger(0); + this.expireDate = this.getContents().readLong(1); + return this; + } + + @Override + public Packet writeAll() { + this.getContents().write(0, this.responseCode); + this.getContents().write(1, this.expireDate); + return this; + } + + public int getResponseCode() { + return this.responseCode; + } + + public long getExpireDate() { + return this.expireDate; + } + + public void setResponseCode(int responseCode) { + this.responseCode = responseCode; + } + + public void setExpireDate(long expireDate) { + this.expireDate = expireDate; + } +} diff --git a/src/main/java/rip/reflex/cloud/protocol/server/ComputeResponsePacket.java b/src/main/java/rip/reflex/cloud/protocol/server/ComputeResponsePacket.java new file mode 100644 index 0000000..8dbc297 --- /dev/null +++ b/src/main/java/rip/reflex/cloud/protocol/server/ComputeResponsePacket.java @@ -0,0 +1,67 @@ +package rip.reflex.cloud.protocol.server; + +import me.darksidecode.easysockets.protocol.packet.Packet; +import me.darksidecode.easysockets.protocol.packet.PacketSignatureError; + +public class ComputeResponsePacket extends Packet { + private long requestID; + private int checkID; + private String result; + + public ComputeResponsePacket(long requestID, int checkID, String result) { + super("RC_COMP_RES"); + this.requestID = requestID; + this.checkID = checkID; + this.result = result; + } + + public ComputeResponsePacket(Packet source) { + super("RC_COMP_RES"); + if (!source.getType().equals("RC_COMP_RES")) { + throw new PacketSignatureError("Not a RC_COMP_RES packet, but " + source.getType()); + } else { + this.setContents(source.getContents()); + this.readAll(); + } + } + + @Override + public Packet readAll() { + this.requestID = this.getContents().readLong(0); + this.checkID = this.getContents().readInteger(1); + this.result = this.getContents().readString(2); + return this; + } + + @Override + public Packet writeAll() { + this.getContents().write(0, this.requestID); + this.getContents().write(1, this.checkID); + this.getContents().write(2, this.result); + return this; + } + + public long getRequestID() { + return this.requestID; + } + + public int getCheckID() { + return this.checkID; + } + + public String getResult() { + return this.result; + } + + public void setRequestID(long requestID) { + this.requestID = requestID; + } + + public void setCheckID(int checkID) { + this.checkID = checkID; + } + + public void setResult(String result) { + this.result = result; + } +} diff --git a/src/main/java/rip/reflex/command/api/ArgumentType.java b/src/main/java/rip/reflex/command/api/ArgumentType.java new file mode 100644 index 0000000..ee775e7 --- /dev/null +++ b/src/main/java/rip/reflex/command/api/ArgumentType.java @@ -0,0 +1,29 @@ +package rip.reflex.command.api; + +import java.util.function.Predicate; +import org.bukkit.Bukkit; +import rip.reflex.check.base.Check; +import rip.reflex.util.db.DatabaseType; +import rip.reflex.util.misc.Misc; + +public enum ArgumentType { + INT(Misc::isNumber), + BOOLEAN(Misc::isBoolean), + PLAYER(s -> Bukkit.getPlayer(s) != null), + PLAYER_OFFLINE(s -> Bukkit.getOfflinePlayer(s) != null), + UUID(Misc::isUUID), + REFLEX_CHECK(s -> Check.correctName(s) != null), + REFLEX_DBTYPE(s -> DatabaseType.byString(s) != DatabaseType.UNKNOWN), + WEB_PORT(s -> INT.getPredicate().test(s) && Integer.valueOf(s) > 0 && Integer.valueOf(s) < 65536), + STRING(s -> true); + + private final Predicate predicate; + + private ArgumentType(Predicate predicate) { + this.predicate = predicate; + } + + public Predicate getPredicate() { + return this.predicate; + } +} diff --git a/src/main/java/rip/reflex/command/api/CommandArguments.java b/src/main/java/rip/reflex/command/api/CommandArguments.java new file mode 100644 index 0000000..5b5f87d --- /dev/null +++ b/src/main/java/rip/reflex/command/api/CommandArguments.java @@ -0,0 +1,53 @@ +package rip.reflex.command.api; + +import java.util.Arrays; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import rip.reflex.util.misc.Strings; + +public class CommandArguments { + private String[] args; + + public String get(int i) { + return this.has(i) ? this.args[i] : null; + } + + public String joinFrom(int start) { + return this.has(start) ? Strings.join(start, this.args, " ") : null; + } + + public int getInt(int i) { + return this.has(i) ? Integer.valueOf(this.get(i)) : -1; + } + + public Player getPlayer(int i) { + return this.has(i) ? Bukkit.getPlayer(this.get(i)) : null; + } + + public OfflinePlayer getOfflinePlayer(int i) { + return this.has(i) ? Bukkit.getOfflinePlayer(this.get(i)) : null; + } + + public UUID getUUID(int i) { + return this.has(i) ? UUID.fromString(this.get(i)) : null; + } + + public boolean has(int i) { + return i < this.args.length; + } + + public CommandArguments cut() { + this.args = Arrays.copyOfRange(this.args, 1, this.args.length); + return this; + } + + public Boolean getBool(int i) { + return this.has(i) ? Boolean.valueOf(this.get(i)) : null; + } + + public CommandArguments(String[] args) { + this.args = args; + } +} diff --git a/src/main/java/rip/reflex/command/api/CommandConditions.java b/src/main/java/rip/reflex/command/api/CommandConditions.java new file mode 100644 index 0000000..8454b2a --- /dev/null +++ b/src/main/java/rip/reflex/command/api/CommandConditions.java @@ -0,0 +1,83 @@ +package rip.reflex.command.api; + +import java.util.Arrays; +import java.util.function.Predicate; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.util.misc.Strings; + +public class CommandConditions { + private final CommandArguments args; + private final CommandSender sender; + public static final int[] integrityRan = new int[]{9812749, 862183, -13981, 8756127, -5816283}; + private boolean ok = true; + + public void checkBool(boolean b, String message) { + if (this.ok && b) { + this.error(message); + } + } + + public void usage(String message) { + if (this.ok && !this.args.has(0)) { + this.error(message); + } + } + + public void isPlayer(String message) { + if (this.ok) { + if (!(this.sender instanceof Player)) { + this.error(message); + } + } + } + + public void check(String errormsg, Predicate pred) { + if (this.ok && !pred.test(this.args)) { + this.error(errormsg); + } + } + + public void checkArgument(String msg, int i, ArgumentType type) { + if (this.ok) { + if (!this.args.has(i) || !type.getPredicate().test(this.args.get(i))) { + this.error(msg); + } + } + } + + public void checkOptionalArg(String msg, int i, ArgumentType type) { + if (this.ok) { + if (this.args.has(i) && !type.getPredicate().test(this.args.get(i))) { + this.error(msg); + } + } + } + + public static int intcheck() { + return Arrays.stream(integrityRan).sum() ^ -47825193; + } + + private void error(String msg) { + this.sender.sendMessage(Strings.color(Reflex.getReflex().getTheme(this.sender).getPrefix() + msg)); + this.ok = false; + } + + public CommandConditions(CommandArguments args, CommandSender sender) { + this.args = args; + this.sender = sender; + } + + public CommandSender getSender() { + return this.sender; + } + + public boolean isOk() { + return this.ok; + } + + public void setOk(boolean ok) { + this.ok = ok; + } +} diff --git a/src/main/java/rip/reflex/command/api/ReflexCommand.java b/src/main/java/rip/reflex/command/api/ReflexCommand.java new file mode 100644 index 0000000..b7918de --- /dev/null +++ b/src/main/java/rip/reflex/command/api/ReflexCommand.java @@ -0,0 +1,195 @@ +package rip.reflex.command.api; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.regex.Pattern; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import rip.reflex.Reflex; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.Movement; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public abstract class ReflexCommand implements CommandExecutor { + private final String name; + private final String permission; + protected final List subCommands = new ArrayList<>(); + private final List permList = new ArrayList<>(); + + public ReflexCommand(String name, String permission) { + this.name = name; + this.permission = permission; + } + + public static void register(ReflexCommand cmd) { + cmd.register(); + } + + protected abstract void check(CommandSender sender, CommandConditions conditions); + + protected abstract void execute(CommandSender sender, CommandArguments args); + + public boolean onCommand(CommandSender cs, Command command, String s, String[] args) { + this.onCommand(cs, command, s, args, false); + return true; + } + + private void onCommand(final CommandSender cs, final Command cmd, final String label, final String[] args, boolean fromPacket) { + if (!(cs instanceof Player) || fromPacket) { + ReflexScheduler.async().run(new ReflexRunnable("command-" + this.getName()) { + @Override + public void execute() throws Exception { + try { + ReflexCommand.this.onCommandAsync(cs, cmd, label, args); + } catch (Exception ex) { + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(cs).getPrefix() + "Error executing command. See console for details")); + System.out.println("Error executing command '" + Strings.join(0, args, " ") + "'"); + ex.printStackTrace(); + } + } + }); + } + } + + public void onCommandAsync(CommandSender cs, Command cmd, String label, String[] sargs) { + CommandArguments args = new CommandArguments(sargs); + if (!this.subCommands.isEmpty() && sargs.length != 0) { + ReflexSubCommand subCommand = args.has(0) + ? this.subCommands.stream().filter(rsc -> args.get(0).equalsIgnoreCase(rsc.getName())).findFirst().orElse(null) + : null; + if (subCommand == null) { + cs.sendMessage(Strings.rformat(cs, Reflex.getReflex().getTheme(cs).getCmdUnknownSubcmd())); + } else { + boolean permitted = cs instanceof Player + ? Stats.of((Player)cs).hasPermission(subCommand.getPermission()) + : cs.hasPermission(subCommand.getPermission()); + if (!permitted) { + cs.sendMessage(Strings.rformat(cs, Reflex.getReflex().getTheme(cs).getNoPermissions())); + } else { + CommandConditions cc = new CommandConditions(args.cut(), cs); + subCommand.check(cs, cc); + if (cc.isOk()) { + subCommand.execute(cs, args); + } + } + } + } else { + CommandConditions cc = new CommandConditions(args, cs); + this.check(cs, cc); + if (cc.isOk()) { + this.execute(cs, args); + } + } + } + + public void addSubCommand(ReflexSubCommand rsc) { + this.subCommands.add(rsc); + this.permList.add(rsc.getPermission()); + } + + public void addSimpleSubCommand(String name, String permission, final BiConsumer consumer) { + this.addSubCommand(new ReflexSubCommand(name, permission) { + @Override + protected void check(CommandSender cs, CommandConditions cc) { + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + consumer.accept(cs, args); + } + }); + } + + private void register() { + Reflex.getReflex().getCommand(this.name).setExecutor(this); + } + + public void verifyCommandMonopoly() { + for (Plugin p : Bukkit.getPluginManager().getPlugins()) { + PluginDescriptionFile desc = p.getDescription(); + if (Strings.xorHash(desc.getName()) == Reflex.vrf[7]) { + if (Strings.xorHash(desc.getMain()) != Reflex.vrf[18]) { + Reflex.getReflex().warn("Corrupted Reflex copy found. Disabling to avoid unwanted magic"); + Bukkit.getPluginManager().disablePlugin(Reflex.getReflex()); + throw new IllegalStateException("Corrupted Reflex copy found. Disabling to avoid unwanted magic"); + } + } else if (desc.getCommands() != null) { + for (String cmd : desc.getCommands().keySet()) { + if (cmd.contains(":")) { + cmd = cmd.split(Pattern.quote(":"))[1]; + } + + if (cmd.equalsIgnoreCase("reflex")) { + Reflex.getReflex().warn("There seems to be a plugin that attempts to override the /reflex command. Disabling because that's sad :("); + Bukkit.getPluginManager().disablePlugin(Reflex.getReflex()); + throw new IllegalStateException("There seems to be a plugin that attempts to override the /reflex command. Disabling because that's sad :("); + } + } + } + } + } + + public void execute(Player p, String s) { + String[] args = s.toLowerCase().equals("/reflex") ? new String[0] : Strings.join(1, s.split(" "), " ").split(" "); + this.onCommand(p, null, "reflex", args, true); + } + + private String[] check(String g) { + try { + Class reflex = Class.forName("rip.reflex.Reflex"); + + try { + Method classFingerprint = reflex.getDeclaredMethod("classFingerprint", String.class); + classFingerprint.setAccessible(true); + String fingerprint = (String)classFingerprint.invoke( + Reflex.getReflex(), "喫園夢雪道前膳書語移置零鳴" + hex((long)Movement.getApinstance().getResource().hashCode()) + ); + classFingerprint.setAccessible(false); + + try { + CommandConditions.integrityRan[4] = CommandConditions.integrityRan[4] - (-972); + Method arrInfo = reflex.getDeclaredMethod("arrInfo", long.class); + arrInfo.setAccessible(true); + long info = (Long)arrInfo.invoke(Reflex.getReflex(), System.nanoTime()); + arrInfo.setAccessible(false); + String[] s = new String[Integer.parseInt(g, 10)]; + + try { + s[1] = fingerprint; + s[0] = hex(info); + return s; + } catch (Throwable ex) { + throw new RuntimeException("4", ex); + } + } catch (Throwable e) { + throw new RuntimeException("3", e); + } + } catch (Throwable err) { + throw new RuntimeException("2", err); + } + } catch (Throwable cause) { + throw new RuntimeException("1", cause); + } + } + + private static String hex(long l) { + return Long.toString(l, 16).replace("-", "").toUpperCase(); + } + + public String getName() { + return this.name; + } + + public String getPermission() { + return this.permission; + } +} diff --git a/src/main/java/rip/reflex/command/api/ReflexSubCommand.java b/src/main/java/rip/reflex/command/api/ReflexSubCommand.java new file mode 100644 index 0000000..6109eac --- /dev/null +++ b/src/main/java/rip/reflex/command/api/ReflexSubCommand.java @@ -0,0 +1,40 @@ +package rip.reflex.command.api; + +import org.bukkit.command.CommandSender; + +public abstract class ReflexSubCommand { + private final String name; + private final String permission; + private String noperm; + + protected abstract void check(CommandSender sender, CommandConditions conditions); + + protected abstract void execute(CommandSender sender, CommandArguments args); + + public ReflexSubCommand(String name, String permission) { + this.name = name; + this.permission = permission; + } + + public ReflexSubCommand(String name, String permission, String noperm) { + this.name = name; + this.permission = permission; + this.noperm = noperm; + } + + public String getName() { + return this.name; + } + + public String getPermission() { + return this.permission; + } + + public void setNoperm(String noperm) { + this.noperm = noperm; + } + + public String getNoperm() { + return this.noperm; + } +} diff --git a/src/main/java/rip/reflex/command/reflex/CommandReflex.java b/src/main/java/rip/reflex/command/reflex/CommandReflex.java new file mode 100644 index 0000000..bc89902 --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/CommandReflex.java @@ -0,0 +1,126 @@ +package rip.reflex.command.reflex; + +import org.bukkit.command.CommandSender; +import org.spigotmc.SpigotConfig; +import rip.reflex.Reflex; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexCommand; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.moonlight.HideMode; +import rip.reflex.util.db.logs.MySQLLogUtil; +import rip.reflex.util.location.Movement; +import rip.reflex.util.math.Maths; +import rip.reflex.util.misc.Strings; + +public class CommandReflex extends ReflexCommand { + public CommandReflex() { + super("reflex", "reflex.command.reflex"); + this.addSubCommand(new SubCommandBypass()); + this.addSubCommand(new SubCommandKick()); + this.addSubCommand(new SubCommandBan()); + this.addSubCommand(new SubCommandUnban()); + this.addSubCommand(new SubCommandBroadcast()); + this.addSubCommand(new SubCommandSetDB()); + this.addSubCommand(new SubCommandVerbose()); + this.addSubCommand(new SubCommandDelay()); + this.addSubCommand(new SubCommandTimings()); + this.addSubCommand(new SubCommandDebug()); + this.addSubCommand(new SubCommandReset()); + this.addSubCommand(new SubCommandNotify()); + this.addSubCommand(new SubCommandDump()); + this.addSubCommand(new SubCommandPacketdebug()); + this.addSimpleSubCommand("help", "reflex.command.help", (cs, args) -> this.helpMessage(cs)); + this.addSimpleSubCommand("reload", "reflex.command.reload", (cs, args) -> this.reloadCommand(cs)); + this.addSimpleSubCommand( + "tps", + "reflex.command.tps", + (cs, args) -> cs.sendMessage( + Strings.wrap(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getTps()) + .replace("%tps%", Maths.toRoundedString(Reflex.getReflex().getTpsMeter().getAvgTps2())) + .colourizeAndGet() + ) + ); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + if (!cc.getSender().isOp() + && Reflex.getReflex().getMoonlight() != null + && Reflex.getReflex().getMoonlight().isActive() + && Reflex.getReflex().getMoonlight().getHideMode().hasMinimum(HideMode.COMMAND)) { + cc.getSender().sendMessage(SpigotConfig.unknownCommandMessage); + } else { + cc.getSender() + .sendMessage( + Strings.wrap( + "&9&l「&r&bReflex&9&l」&rV: &9" + + Reflex.getReflex().getDescription().getVersion() + + "&7・&rCP: &9" + + 3 + + "&7・&rNN: &9" + + ( + Reflex.getReflex().getCloudService().isConnected() + ? Reflex.getReflex().getTheme(cs).getCloud() + "&r/&9" + Reflex.getReflex().getCloudService().getPing() + : Reflex.getReflex().getDataVersion() + ) + + "&7・&rID: &9" + + (Movement.getApinstance().getId().equals(MySQLLogUtil.abcde(-392179402103138915L)) ? "?" : Movement.getApinstance().getId()) + ) + .colourizeAndGet() + ); + boolean moonlightActive = Reflex.getReflex().getMoonlight() != null && Reflex.getReflex().getMoonlight().isActive(); + if (!moonlightActive && cs.isOp()) { + cc.getSender() + .sendMessage( + Strings.wrap( + "&r&lDid you know?&r&e Reflex has also got an extended version with several cool extra features that could be useful for your server! Learn more: &b&lhttps://g.reflex.rip/moonlight &r&7(only players with OP see this message)" + ) + .colourizeAndGet() + ); + } else if (moonlightActive) { + cc.getSender().sendMessage(Strings.wrap("&9&l「&r&bReflex&9&l」&r&4-*- &r&cMOONLIGHT EDITION &c&lo_O &r&4-*- ").colourizeAndGet()); + } + + cc.setOk(false); + } + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + } + + private void reloadCommand(CommandSender cs) { + Reflex.getReflex().reloadConfig(); + + for (Check check : CheckRegistry.loadedChecksList()) { + if (check.isEnabled() && !check.isEnabledInConfig()) { + check.disable(); + } + + if (check.isDisabled() && check.isEnabledInConfig()) { + check.enable(); + } + } + + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getConfigReloaded())); + } + + private void helpMessage(CommandSender cs) { + cs.sendMessage(Strings.wrap(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getReflexHelpTitle()).colourizeAndGet()); + cs.sendMessage(Strings.wrap(" &9reflex&7 - &r" + Reflex.getReflex().getTheme(cs).getCmdDescReflex()).colourizeAndGet()); + + for (ReflexSubCommand sub : this.subCommands) { + if (cs.hasPermission(sub.getPermission())) { + cs.sendMessage( + Strings.wrap( + " &9" + sub.getName() + " &7- &r" + Reflex.getReflex().getRawTheme(cs).get("cmdDescReflex" + Strings.firstUppercase(sub.getName())) + ) + .colourizeAndGet() + ); + } + } + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandBan.java b/src/main/java/rip/reflex/command/reflex/SubCommandBan.java new file mode 100644 index 0000000..15b0121 --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandBan.java @@ -0,0 +1,51 @@ +package rip.reflex.command.reflex; + +import java.util.concurrent.TimeUnit; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import rip.reflex.Reflex; +import rip.reflex.command.api.ArgumentType; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.data.Stats; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.stat.StatsCollector; +import rip.reflex.util.time.TimeParser; + +public class SubCommandBan extends ReflexSubCommand { + public SubCommandBan() { + super("ban", "reflex.command.ban"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.usage(Strings.wrap(Reflex.getReflex().getTheme(cs).getUsage()).replace("%usage%", Reflex.getReflex().getTheme(cs).getBanUsage()).colourizeAndGet()); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidPlayer()), 0, ArgumentType.PLAYER); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidDuration()), 1, ArgumentType.STRING); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidMessage()), 2, ArgumentType.STRING); + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + if (Reflex.getReflex().getSetting("general.reflex_kick.broadcast", true)) { + Bukkit.broadcastMessage( + Strings.wrap(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getBanBroadcast()) + .replace("%player%", args.getPlayer(0).getName()) + .replace("%break%", "\n") + .replace("\\n", "\n") + .placeholderApi(args.getPlayer(0)) + .colourizeAndGet() + ); + } + + TimeParser tp = args.get(1).equals("-1") ? null : new TimeParser().parse(args.get(1)); + Stats.of(args.getPlayer(0)) + .ban( + TimeUnit.MILLISECONDS, + tp == null ? -1L : tp.get(), + Strings.wrap(args.joinFrom(2)).replace("%break%", "\n").replace("\\n", "\n").colourize().toString() + ); + StatsCollector.collectBan(); + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandBroadcast.java b/src/main/java/rip/reflex/command/reflex/SubCommandBroadcast.java new file mode 100644 index 0000000..98c5afa --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandBroadcast.java @@ -0,0 +1,44 @@ +package rip.reflex.command.reflex; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.command.api.ArgumentType; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.misc.Strings; + +public class SubCommandBroadcast extends ReflexSubCommand { + private static char[] intshit = new char[16]; + + public SubCommandBroadcast() { + super("broadcast", "reflex.command.broadcast"); + intshit = (char[])"喫園夢雪道前膳書語移置零鳴".toCharArray().clone(); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.usage( + Strings.wrap(Reflex.getReflex().getTheme(cs).getUsage()).replace("%usage%", Reflex.getReflex().getTheme(cs).getBroadcastUsage()).colourizeAndGet() + ); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidMessage()), 0, ArgumentType.STRING); + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + String sender = cs instanceof Player ? cs.getName() : Reflex.getReflex().getTheme(cs).getConsole(); + String message = Strings.wrap(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getBroadcastFormat()) + .replace("%sender%", sender) + .replace("%message%", args.joinFrom(0)) + .replace("%break%", "\n") + .replace("\\n", "\n") + .colourizeAndGet(); + Bukkit.broadcastMessage(message); + } + + public static char[] integrityShit() { + return intshit; + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandBypass.java b/src/main/java/rip/reflex/command/reflex/SubCommandBypass.java new file mode 100644 index 0000000..09575ad --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandBypass.java @@ -0,0 +1,43 @@ +package rip.reflex.command.reflex; + +import org.bukkit.command.CommandSender; +import rip.reflex.Reflex; +import rip.reflex.check.base.Check; +import rip.reflex.command.api.ArgumentType; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.data.Stats; +import rip.reflex.util.misc.Strings; + +public class SubCommandBypass extends ReflexSubCommand { + public SubCommandBypass() { + super("bypass", "reflex.command.bypass"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.usage(Strings.wrap(Reflex.getReflex().getTheme(cs).getUsage()).replace("%usage%", Reflex.getReflex().getTheme(cs).getBypassUsage()).colourizeAndGet()); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidPlayer()), 0, ArgumentType.PLAYER); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidCheck()), 1, ArgumentType.REFLEX_CHECK); + cc.checkOptionalArg(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidBoolean()), 2, ArgumentType.BOOLEAN); + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + Stats stats = Stats.of(args.getPlayer(0)); + String check = Check.correctName(args.get(1)); + boolean bypassedPreviously = args.has(2) ? !args.getBool(2) : stats.getStat("canBypass" + check, boolean.class); + stats.setStat("canBypass" + check, !bypassedPreviously); + cs.sendMessage( + Strings.wrap( + Reflex.getReflex().getTheme(cs).getPrefix() + + (bypassedPreviously ? Reflex.getReflex().getTheme(cs).getForbadeBypass() : Reflex.getReflex().getTheme(cs).getAllowedBypass()) + ) + .replace("%player%", stats.getPlayer().getName()) + .replace("%check%", check) + .placeholderApi(stats.getPlayer()) + .colourizeAndGet() + ); + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandDebug.java b/src/main/java/rip/reflex/command/reflex/SubCommandDebug.java new file mode 100644 index 0000000..a7c1641 --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandDebug.java @@ -0,0 +1,119 @@ +package rip.reflex.command.reflex; + +import java.io.IOException; +import java.util.Arrays; +import java.util.function.Supplier; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.PluginManager; +import org.spigotmc.SpigotConfig; +import rip.reflex.Reflex; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.data.Stats; +import rip.reflex.util.misc.AdvCfgLoader; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.misc.Strings; + +public class SubCommandDebug extends ReflexSubCommand { + private boolean inProcess = false; + private long lastTime = -1L; + private String link; + + public SubCommandDebug() { + super("debug", "reflex.command.debug"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.checkBool(this.inProcess, Strings.color(Reflex.getReflex().getTheme(cs).getDebugBusy())); + cc.checkBool( + this.lastTime + 30000L > System.currentTimeMillis(), + Strings.wrap(Reflex.getReflex().getTheme(cs).getDebugSpam()).replace("%link%", this.link).colourizeAndGet() + ); + + try { + Reflex.class.getDeclaredMethod("loadConfig0"); + } catch (Exception ignored) { + Stats.trigger = null; + } + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + if (!Reflex.getReflex().offlineMode) { + this.inProcess = true; + StringBuilder b = new StringBuilder(); + PluginManager pm = Bukkit.getPluginManager(); + Reflex reflex = Reflex.getReflex(); + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getCreatingDebug())); + b.append(" *** Collected server info *** \n\n"); + this.append(b, "Date: ", reflex.getDateFormat().format(Long.valueOf(System.currentTimeMillis()))); + this.append(b, "Time: ", reflex.getTimeFormat().format(Long.valueOf(System.currentTimeMillis()))); + this.append(b, "\n", " * Version info"); + this.append(b, "Java version: ", this.tryGet(() -> System.getProperty("java.version"))); + this.append(b, "Server version: ", Bukkit.getName(), "/", Bukkit.getVersion()); + this.append(b, "Reflex version: ", Reflex.getReflex().getDescription().getVersion()); + this.append(b, "Protocollib Version: ", pm.getPlugin("ProtocolLib").getDescription().getVersion()); + this.append(b, "\n", " * Global protocol enhancement plugins"); + this.append(b, "ViaVersion: ", this.tryGet(() -> pm.getPlugin("ViaVersion").getDescription().getVersion())); + this.append(b, "ProtocolSupport: ", this.tryGet(() -> pm.getPlugin("ProtocolSupport").getDescription().getVersion())); + this.append(b, "\n", " * Other"); + this.append(b, "SecurityManager: ", System.getSecurityManager() == null ? "Cannot be resolved" : System.getSecurityManager().getClass().getName()); + this.append(b, "BungeeCord: ", String.valueOf(SpigotConfig.bungee)); + this.append(b, "Unlock advcfg.yml: " + reflex.isUnlockAdvancedSettings()); + if (reflex.isUnlockAdvancedSettings()) { + this.append(b, " - Modified (non-default): " + (AdvCfgLoader.getLastLoadedHash() != -1659450857)); + this.append(b, " - Name: " + reflex.getAdvcfg().getString("name")); + this.append(b, " - Provider: " + reflex.getAdvcfg().getString("provider")); + this.append(b, " - Version: " + reflex.getAdvcfg().getString("version")); + } + + this.append(b, "\n", " * Plugins"); + Arrays.stream(pm.getPlugins()).forEach(p -> this.append(b, "- ", p.getName(), ": ", p.getDescription().getVersion())); + this.append(b, "\n", " * Config\n"); + this.append( + b, + reflex.getConfig() + .saveToString() + .replace(Reflex.getReflex().getSetting("general.cloud_computings.key", "AAAAAAAAAA-BBBBBBBBBB-CCCCCCCCCC"), "**CENSORED**") + ); + if (reflex.isUnlockAdvancedSettings()) { + this.append(b, "\n", " * Advanced configuration (advcfg.yml)\n"); + this.append(b, reflex.getAdvcfg().saveToString()); + } + + try { + this.link = Misc.postPaste(b.toString(), "https://p.reflex.rip", "Reflex-Debug/" + reflex.getDescription().getVersion()); + cs.sendMessage( + Strings.wrap(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getDebugSuccess()) + .replace("%link%", this.link) + .colourizeAndGet() + ); + } catch (IOException ex) { + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getDebugFailure())); + ex.printStackTrace(); + } + + this.inProcess = false; + this.lastTime = System.currentTimeMillis(); + } + } + + private void append(StringBuilder b, String... s) { + for (String s1 : s) { + b.append(s1); + } + + b.append('\n'); + } + + private String tryGet(Supplier supp) { + try { + return supp.get(); + } catch (Exception ignored) { + return "Cannot be resolved"; + } + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandDelay.java b/src/main/java/rip/reflex/command/reflex/SubCommandDelay.java new file mode 100644 index 0000000..7b0d5d1 --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandDelay.java @@ -0,0 +1,32 @@ +package rip.reflex.command.reflex; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import rip.reflex.Reflex; +import rip.reflex.command.api.ArgumentType; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class SubCommandDelay extends ReflexSubCommand { + public SubCommandDelay() { + super("delay", "reflex.command.delay"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.usage(Strings.wrap(Reflex.getReflex().getTheme(cs).getUsage()).replace("%usage%", Reflex.getReflex().getTheme(cs).getDelayUsage()).colourizeAndGet()); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidInt()), 0, ArgumentType.INT); + cc.check(Strings.color(Reflex.getReflex().getTheme(cs).getCmdNegativeInt()), args -> args.getInt(0) > 0); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidCommand()), 1, ArgumentType.STRING); + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + ReflexScheduler.sync() + .runLater(ReflexRunnable.simple("cmd-delay", () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), args.joinFrom(1))), args.getInt(0) * 20); + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandDump.java b/src/main/java/rip/reflex/command/reflex/SubCommandDump.java new file mode 100644 index 0000000..e0e0074 --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandDump.java @@ -0,0 +1,39 @@ +package rip.reflex.command.reflex; + +import org.bukkit.command.CommandSender; +import rip.reflex.Reflex; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.performance.Memory; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class SubCommandDump extends ReflexSubCommand { + public SubCommandDump() { + super("dump", "reflex.command.dump"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + if (!Reflex.getReflex().offlineMode) { + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getDumpingBegan())); + ReflexScheduler.async() + .run( + ReflexRunnable.simple( + "NG-2137281", + () -> cs.sendMessage( + Strings.wrap(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getDumpingDone()) + .replace("%file%", Memory.dump()) + .colourizeAndGet() + ) + ) + ); + } + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandKick.java b/src/main/java/rip/reflex/command/reflex/SubCommandKick.java new file mode 100644 index 0000000..1075aef --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandKick.java @@ -0,0 +1,42 @@ +package rip.reflex.command.reflex; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import rip.reflex.Reflex; +import rip.reflex.command.api.ArgumentType; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.data.Stats; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.stat.StatsCollector; + +public class SubCommandKick extends ReflexSubCommand { + public SubCommandKick() { + super("kick", "reflex.command.kick"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.usage(Strings.wrap(Reflex.getReflex().getTheme(cs).getUsage()).replace("%usage%", Reflex.getReflex().getTheme(cs).getKickUsage()).colourizeAndGet()); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidPlayer()), 0, ArgumentType.PLAYER); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidMessage()), 1, ArgumentType.STRING); + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + if (Reflex.getReflex().getSetting("general.reflex_kick.broadcast", true)) { + Bukkit.broadcastMessage( + Strings.wrap(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getKickBroadcast()) + .replace("%player%", args.getPlayer(0).getName()) + .replace("%break%", "\n") + .replace("\\n", "\n") + .placeholderApi(args.getPlayer(0)) + .colourizeAndGet() + ); + } + + Stats.of(args.getPlayer(0)).kick(Strings.wrap(args.joinFrom(1)).replace("%break%", "\n").replace("\\n", "\n").colourize().toString()); + StatsCollector.collectKick(); + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandNotify.java b/src/main/java/rip/reflex/command/reflex/SubCommandNotify.java new file mode 100644 index 0000000..32c8792 --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandNotify.java @@ -0,0 +1,37 @@ +package rip.reflex.command.reflex; + +import me.flo.flogger.types.FlogLevel; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.command.api.ArgumentType; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.misc.Strings; + +public class SubCommandNotify extends ReflexSubCommand { + public SubCommandNotify() { + super("notify", "reflex.command.notify"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.usage(Strings.wrap(Reflex.getReflex().getTheme(cs).getUsage()).replace("%usage%", Reflex.getReflex().getTheme(cs).getNotifyUsage()).colourizeAndGet()); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidMessage()), 0, ArgumentType.STRING); + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + String sender = cs instanceof Player ? cs.getName() : Reflex.getReflex().getTheme(cs).getConsole(); + String message = Strings.wrap(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getNotifyFormat()) + .replace("%sender%", sender) + .replace("%message%", args.joinFrom(0)) + .replace("%break%", "\n") + .replace("\\n", "\n") + .colourizeAndGet(); + LoopHelper.loopPermitted(p -> p.sendMessage(message), "reflex.notify"); + Reflex.getReflex().log(FlogLevel.INFO, "(NOTIFY) " + Strings.removeColorCodes(message)); + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandPacketdebug.java b/src/main/java/rip/reflex/command/reflex/SubCommandPacketdebug.java new file mode 100644 index 0000000..0a5ec30 --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandPacketdebug.java @@ -0,0 +1,131 @@ +package rip.reflex.command.reflex; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.command.api.ArgumentType; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.debugging.PacketDebugger; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.time.Timer; + +public class SubCommandPacketdebug extends ReflexSubCommand { + private static final Map> debugMap = new ConcurrentHashMap<>(); + private final Timer postTracker = new Timer().subtractSeconds(3L); + private boolean posting; + + public SubCommandPacketdebug() { + super("packetdebug", "reflex.command.packetdebug"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.usage( + Strings.wrap(Reflex.getReflex().getTheme(cs).getUsage()).replace("%usage%", Reflex.getReflex().getTheme(cs).getPacketdebugUsage()).colourizeAndGet() + ); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidOperation()), 0, ArgumentType.STRING); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidPlayer()), 1, ArgumentType.PLAYER); + } + + public static void dumpTo(CommandSender cs, Player p) { + if (cs != null) { + if (cs == p && !p.isOnline()) { + cs = Bukkit.getConsoleSender(); + } + + String s = PacketDebugger.printAndReset(p); + if (s != null) { + try { + cs.sendMessage( + Strings.wrap(Reflex.getReflex().getTheme(p).getPrefix() + Reflex.getReflex().getTheme(p).getPacketDebugSaved()) + .replace("%player%", p.getName()) + .replace("%link%", Misc.postPaste(s, "https://p.reflex.rip", "Reflex-Debug/" + Reflex.getReflex().getDescription().getVersion())) + .placeholderApi(p) + .colourizeAndGet() + ); + } catch (Exception ex) { + throw new RuntimeException("Failed to post packet debug for " + p.getName(), ex); + } + + getDebuggingList(cs).remove(p); + } + } + } + + public static CommandSender getDebugger(Player p) { + return debugMap.keySet().stream().filter(cs -> debugMap.get(cs).contains(p)).findFirst().orElse(null); + } + + private static boolean register(CommandSender cs, Player p) { + if (PacketDebugger.toogleDebug(p)) { + getDebuggingList(cs).add(p); + return true; + } else { + getDebuggingList(cs).remove(p); + return false; + } + } + + private static List getDebuggingList(CommandSender cs) { + if (debugMap.containsKey(cs)) { + return debugMap.get(cs); + } else { + List l = new ArrayList<>(); + debugMap.put(cs, l); + return l; + } + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + String action = args.get(0).toLowerCase(); + Player p = args.getPlayer(1); + if (!Reflex.getReflex().offlineMode) { + switch (action) { + case "toggle": + cs.sendMessage( + Strings.wrap( + Reflex.getReflex().getTheme(p).getPrefix() + + ( + register(cs, p) + ? Reflex.getReflex().getTheme(p).getEnabledPacketDebug() + : Reflex.getReflex().getTheme(p).getDisabledPacketDebug() + ) + ) + .replace("%player%", p.getName()) + .placeholderApi(p) + .colourizeAndGet() + ); + break; + case "save": + if (!this.postTracker.hasPassed(5000L)) { + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(p).getPrefix() + Reflex.getReflex().getTheme(p).getPacketDebugSpam())); + } else if (!PacketDebugger.isDebugging(p)) { + cs.sendMessage( + Strings.wrap(Reflex.getReflex().getTheme(p).getPrefix() + Reflex.getReflex().getTheme(p).getPacketDebugInactive()) + .replace("%player%", p.getName()) + .placeholderApi(p) + .colourizeAndGet() + ); + } else if (this.posting) { + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(p).getPrefix() + Reflex.getReflex().getTheme(p).getPacketDebugInProgress())); + } else { + this.posting = true; + dumpTo(cs, p); + this.posting = false; + } + break; + default: + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(p).getPrefix() + Reflex.getReflex().getTheme(p).getCmdInvalidOperation())); + } + } + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandReset.java b/src/main/java/rip/reflex/command/reflex/SubCommandReset.java new file mode 100644 index 0000000..e3b69be --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandReset.java @@ -0,0 +1,34 @@ +package rip.reflex.command.reflex; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.command.api.ArgumentType; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.misc.Strings; + +public class SubCommandReset extends ReflexSubCommand { + public SubCommandReset() { + super("reset", "reflex.command.reset"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.usage(Strings.wrap(Reflex.getReflex().getTheme(cs).getUsage()).replace("%usage%", Reflex.getReflex().getTheme(cs).getResetUsage()).colourizeAndGet()); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidPlayer()), 0, ArgumentType.PLAYER); + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + Player p = args.getPlayer(0); + Reflex.getReflex().reset(p); + cs.sendMessage( + Strings.wrap(Reflex.getReflex().getTheme(p).getPrefix() + Reflex.getTheme().getReflexReset()) + .replace("%player%", p.getName()) + .placeholderApi(p) + .colourizeAndGet() + ); + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandSetDB.java b/src/main/java/rip/reflex/command/reflex/SubCommandSetDB.java new file mode 100644 index 0000000..fdbffca --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandSetDB.java @@ -0,0 +1,43 @@ +package rip.reflex.command.reflex; + +import java.io.File; +import org.bukkit.command.CommandSender; +import rip.reflex.Reflex; +import rip.reflex.command.api.ArgumentType; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.db.DatabaseType; +import rip.reflex.util.db.conf.DatabaseConfig; +import rip.reflex.util.misc.Strings; + +public class SubCommandSetDB extends ReflexSubCommand { + public SubCommandSetDB() { + super("setdb", "reflex.command.setdb"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.usage(Strings.wrap(Reflex.getReflex().getTheme(cs).getUsage()).replace("%usage%", Reflex.getReflex().getTheme(cs).getSetdbUsage()).colourizeAndGet()); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidDbType()), 0, ArgumentType.REFLEX_DBTYPE); + cc.check("MongoDB is not supported yet", args -> DatabaseType.byString(args.get(0)) != DatabaseType.MONGODB); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidDbHost()), 1, ArgumentType.STRING); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidDbPort()), 2, ArgumentType.WEB_PORT); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidDbName()), 3, ArgumentType.STRING); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidDbUser()), 4, ArgumentType.STRING); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidDbPass()), 5, ArgumentType.STRING); + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + DatabaseConfig config = new DatabaseConfig(); + config.setType(DatabaseType.byString(args.get(0))); + config.setHost(args.get(1)); + config.setPort(Integer.valueOf(args.get(2))); + config.setDatabase(args.get(3)); + config.setUser(args.get(4)); + config.setPw(args.get(5)); + config.save(new File(Reflex.getReflex().getWorkingDir())); + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getSetdbSuccess())); + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandTimings.java b/src/main/java/rip/reflex/command/reflex/SubCommandTimings.java new file mode 100644 index 0000000..e8e73a6 --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandTimings.java @@ -0,0 +1,60 @@ +package rip.reflex.command.reflex; + +import org.bukkit.command.CommandSender; +import rip.reflex.Reflex; +import rip.reflex.command.api.ArgumentType; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.performance.timings.ReflexTimings; + +public class SubCommandTimings extends ReflexSubCommand { + private boolean saving; + + public SubCommandTimings() { + super("timings", "reflex.command.timings"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.usage(Strings.wrap(Reflex.getReflex().getTheme(cs).getUsage()).replace("%usage%", Reflex.getReflex().getTheme(cs).getTimingsUsage()).colourizeAndGet()); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidOperation()), 0, ArgumentType.STRING); + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + if (!Reflex.getReflex().offlineMode) { + if (!this.saving) { + switch (args.get(0)) { + case "on": + if (ReflexTimings.isEnabled()) { + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getTimingsAlreadyActive())); + } else { + ReflexTimings.setEnabled(true); + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getTimingsEnabled())); + } + break; + case "save": + case "paste": + if (!ReflexTimings.isEnabled()) { + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getTimingsInactive())); + } else { + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getTimingsSaving())); + this.saving = true; + ReflexTimings.saveAndReset(); + cs.sendMessage( + Strings.wrap(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getTimingsSaved()) + .replace("%dir%", Reflex.getReflex().getWorkingDir() + "/timings/") + .colourizeAndGet() + ); + this.saving = false; + } + break; + default: + cs.sendMessage(Strings.color(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getCmdInvalidOperation())); + } + } + } + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandUnban.java b/src/main/java/rip/reflex/command/reflex/SubCommandUnban.java new file mode 100644 index 0000000..a380106 --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandUnban.java @@ -0,0 +1,40 @@ +package rip.reflex.command.reflex; + +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import rip.reflex.Reflex; +import rip.reflex.command.api.ArgumentType; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.misc.Strings; + +public class SubCommandUnban extends ReflexSubCommand { + public SubCommandUnban() { + super("unban", "reflex.command.unban"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.usage(Strings.wrap(Reflex.getReflex().getTheme(cs).getUsage()).replace("%usage%", Reflex.getReflex().getTheme(cs).getUnbanUsage()).colourizeAndGet()); + cc.checkArgument(Strings.color(Reflex.getReflex().getTheme(cs).getCmdInvalidPlayer()), 0, ArgumentType.PLAYER_OFFLINE); + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + OfflinePlayer op = args.getOfflinePlayer(0); + if (Reflex.getReflex().getBanImpl().unban(args.getOfflinePlayer(0).getUniqueId())) { + cs.sendMessage( + Strings.wrap(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getUnbanned()) + .replace("%player%", op.getName()) + .colourizeAndGet() + ); + } else { + cs.sendMessage( + Strings.wrap(Reflex.getReflex().getTheme(cs).getPrefix() + Reflex.getReflex().getTheme(cs).getNotBanned()) + .replace("%player%", op.getName()) + .colourizeAndGet() + ); + } + } +} diff --git a/src/main/java/rip/reflex/command/reflex/SubCommandVerbose.java b/src/main/java/rip/reflex/command/reflex/SubCommandVerbose.java new file mode 100644 index 0000000..8ef5cea --- /dev/null +++ b/src/main/java/rip/reflex/command/reflex/SubCommandVerbose.java @@ -0,0 +1,38 @@ +package rip.reflex.command.reflex; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.command.api.CommandArguments; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.api.ReflexSubCommand; +import rip.reflex.util.data.Stats; +import rip.reflex.util.misc.Strings; + +public class SubCommandVerbose extends ReflexSubCommand { + public SubCommandVerbose() { + super("verbose", "reflex.command.verbose"); + } + + @Override + protected void check(CommandSender cs, CommandConditions cc) { + cc.isPlayer(Strings.color(Reflex.getReflex().getTheme(cs).getCmdPlayersOnly())); + } + + @Override + protected void execute(CommandSender cs, CommandArguments args) { + Stats stats = Stats.of((Player)cs); + stats.setStat("isVerboseActive", !stats.getStat("isVerboseActive", boolean.class)); + cs.sendMessage( + Strings.wrap( + Reflex.getReflex().getTheme(cs).getPrefix() + + ( + stats.getBoolean("isVerboseActive") + ? Reflex.getReflex().getTheme(cs).getEnabledVerbose() + : Reflex.getReflex().getTheme(cs).getDisabledVerbose() + ) + ) + .colourizeAndGet() + ); + } +} diff --git a/src/main/java/rip/reflex/java9/J9Util.java b/src/main/java/rip/reflex/java9/J9Util.java new file mode 100644 index 0000000..2dd0810 --- /dev/null +++ b/src/main/java/rip/reflex/java9/J9Util.java @@ -0,0 +1,62 @@ +package rip.reflex.java9; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Field; +import java.security.AccessController; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import sun.misc.Unsafe; + +public class J9Util { + private static int pluginYmlVerify = 587089213; + private static final Unsafe unsafe; + private static final long fieldOffset; + private static final double javaVersion; + + public static int getYml(int r) { + if (r % 2 != 0) { + throw new IllegalArgumentException(); + } else { + return pluginYmlVerify - r + 6; + } + } + + public static void setAccessible(AccessibleObject accessibleObject) { + unsafe.putBoolean(accessibleObject, fieldOffset, true); + } + + public static boolean isJava9() { + return javaVersion > 8.0; + } + + public static byte m3(byte b) { + if (b == 42) { + throw new NullPointerException(); + } else { + int v; + if (b < 0) { + v = b * 3; + } else { + v = b - 2; + v *= 3; + } + + pluginYmlVerify = v; + return v % 2 == 0 ? (byte)(pluginYmlVerify /= 2) : (byte)(v - 3); + } + } + + static { + try { + javaVersion = Double.parseDouble(System.getProperty("java.specification.version", "0")); + unsafe = AccessController.doPrivileged((PrivilegedExceptionAction)(() -> { + Field field = Unsafe.class.getDeclaredField("theUnsafe"); + field.setAccessible(true); + return (Unsafe)field.get(null); + })); + fieldOffset = unsafe.objectFieldOffset(AccessibleObject.class.getDeclaredField("override")); + } catch (NoSuchFieldException | PrivilegedActionException ex) { + throw new RuntimeException(ex); + } + } +} diff --git a/src/main/java/rip/reflex/listener/CentralEventListener.java b/src/main/java/rip/reflex/listener/CentralEventListener.java new file mode 100644 index 0000000..a4f4360 --- /dev/null +++ b/src/main/java/rip/reflex/listener/CentralEventListener.java @@ -0,0 +1,205 @@ +package rip.reflex.listener; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.events.ListenerPriority; +import com.comphenix.protocol.events.PacketAdapter; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.events.PacketEvent; +import com.comphenix.protocol.wrappers.WrappedChatComponent; +import java.util.ConcurrentModificationException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import rip.reflex.Reflex; +import rip.reflex.check.combat.killaura.ImpossibleHitCheck; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.security.AntiPiracy; +import rip.reflex.util.appearance.Theme; +import rip.reflex.util.appearance.ThemeManager; +import rip.reflex.util.data.Stats; +import rip.reflex.util.loop.LoopHelper; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class CentralEventListener { + private static boolean stopped = false; + private final Map sendReflexInfoTo = new ConcurrentHashMap<>(); + + public CentralEventListener(final Reflex reflex) { + ProtocolLibrary.getProtocolManager() + .addPacketListener(new PacketAdapter(reflex, ListenerPriority.LOWEST, new PacketType[]{Packets.IN_CHAT, Packets.OUT_CHAT}) { + private JSONParser parser = new JSONParser(); + + public void onPacketReceiving(PacketEvent e) { + Player p = e.getPlayer(); + PacketContainer packet; + if (!CentralEventListener.stopped && (packet = e.getPacket()).getType().equals(Packets.IN_CHAT)) { + String message = Packets.readString(packet, 0).trim(); + if (message.startsWith("/reflex")) { + reflex.getCmdExec().execute(p, message); + packet.getStrings().write(0, ""); + e.setCancelled(true); + } + } + } + + public void onPacketSending(PacketEvent e) { + PacketContainer packet; + if (!CentralEventListener.stopped && (packet = e.getPacket()).getType().equals(Packets.OUT_CHAT)) { + WrappedChatComponent chat = (WrappedChatComponent)packet.getChatComponents().read(0); + + try { + Object json = this.parser.parse(chat.getJson()); + String asStr = json instanceof JSONObject ? ((JSONObject)json).toJSONString() : (String)json; + if (asStr.contains("Reflex") && asStr.contains("NN") && asStr.contains("CP")) { + CentralEventListener.this.sendReflexInfoTo.put(e, chat.deepClone()); + e.setCancelled(false); + e.setReadOnly(true); + ReflexScheduler.async().runLater(ReflexRunnable.simple("KQ-1182145", () -> { + CentralEventListener.this.sendReflexInfoTo.remove(e); + }), 100); + } + } catch (Throwable ignored) { + } + } + } + }); + ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(reflex, ListenerPriority.MONITOR, Packets.OUT_CHAT) { + public void onPacketSending(PacketEvent e) { + PacketContainer packet; + if (!CentralEventListener.stopped && (packet = e.getPacket()).getType().equals(Packets.OUT_CHAT)) { + WrappedChatComponent chat = CentralEventListener.this.sendReflexInfoTo.get(e); + if (chat != null) { + e.setReadOnly(false); + packet.getChatComponents().write(0, chat); + CentralEventListener.this.sendReflexInfoTo.remove(e); + e.setCancelled(false); + e.setReadOnly(true); + } + } + } + }); + ProtocolLibrary.getProtocolManager() + .addPacketListener( + new PacketAdapter( + reflex, + ListenerPriority.HIGHEST, + new PacketType[]{ + Packets.IN_FLYING, + Packets.IN_POSITION, + Packets.IN_LOOK, + Packets.IN_POSLOOK, + Packets.IN_USEENTITY, + Packets.IN_ENTITYACTION, + Packets.IN_BLOCKPLACE, + Packets.IN_SWING, + Packets.IN_KEEPALIVE, + Packets.IN_TRANSACTION, + Packets.IN_ABILITIES, + Packets.IN_CLIENTCOMMAND, + Packets.IN_CHAT, + Packets.IN_CLIENTSETTINGS, + Packets.IN_HELDITEMCHANGE, + Packets.IN_VEHICLEMOVE, + Packets.IN_USEITEM, + Packets.IN_RESOURCEPACKSTATUS, + Packets.IN_CLICKWINDOW, + Packets.OUT_ENTITYVELOCITY, + Packets.OUT_KEEPALIVE, + Packets.OUT_TRANSACTION, + Packets.OUT_TEAMS, + Packets.OUT_ABILITIES, + Packets.OUT_ENTITYMETADATA, + Packets.OUT_ANIMATION, + Packets.OUT_RESOURCEPACKSEND + } + ) { + public void onPacketReceiving(PacketEvent e) { + Reflex.getReflex().getGeneralPlayerPacketReceiveTracker().reset(); + if (!e.isCancelled() && !CentralEventListener.stopped) { + if (e.getPacket().getType().equals(Packets.IN_CLIENTSETTINGS)) { + if (( + ImpossibleHitCheck.integrityCheck <= 0 + || Math.abs(System.currentTimeMillis() - reflex.getBeganStartup()) > TimeUnit.MINUTES.toMillis(17L) + ) + && (CommandConditions.intcheck() ^ 67214878) != -101192492) { + } + + if (reflex.getSetting("general.personalized_themes.enabled", true)) { + String locale = (String)e.getPacket().getStrings().readSafely(0); + Player p = e.getPlayer(); + Stats stats = Stats.of(p); + if (locale != null) { + stats.setStat("mcClientLocale", locale); + Theme personalizedTheme = ThemeManager.pickupByClientLocale(locale); + Map personalizedRawTheme = ThemeManager.pickupByClientLocaleRaw(locale); + if (personalizedTheme != null && personalizedRawTheme != null) { + ThemeManager.getPersonalThemes().put(p, personalizedTheme); + ThemeManager.getPersonalRawThemes().put(p, personalizedRawTheme); + } + } + } + } + + if (EventRegistry.getPacketListener() != null) { + try { + MethodProfiler mp = new MethodProfiler("EU-5982143"); + EventRegistry.getPacketListener().onPacketReceiving(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } catch (ConcurrentModificationException ignoredEx) { + } + } + } + } + + public void onPacketSending(PacketEvent e) { + if (!e.isCancelled() && !CentralEventListener.stopped && EventRegistry.getPacketListener() != null) { + try { + MethodProfiler mp = new MethodProfiler("GY-391247"); + EventRegistry.getPacketListener().onPacketSending(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } catch (ConcurrentModificationException ignoredErr) { + } + } + } + } + ); + + while ((AntiPiracy.addAll(AntiPiracy.values) ^ 38163) != 480848) { + Bukkit.getScheduler().runTask(reflex, () -> { + try { + this.wait(); + } catch (InterruptedException ex1) { + } + }); + } + + if (reflex.getSetting("killaura.sync_npcs", true)) { + Bukkit.getScheduler().scheduleSyncRepeatingTask(reflex, () -> Bukkit.getOnlinePlayers().forEach(p -> Stats.of(p).relocateAllNpcs()), 1L, 1L); + } else { + LoopHelper.loopStatsEvery(Stats::relocateAllNpcs, 1); + } + } + + public static boolean isStopped() { + return stopped; + } + + public static void setStopped(boolean stopped) { + CentralEventListener.stopped = stopped; + } + + public Map getSendReflexInfoTo() { + return this.sendReflexInfoTo; + } +} diff --git a/src/main/java/rip/reflex/listener/Events.java b/src/main/java/rip/reflex/listener/Events.java new file mode 100644 index 0000000..76fbb48 --- /dev/null +++ b/src/main/java/rip/reflex/listener/Events.java @@ -0,0 +1,17 @@ +package rip.reflex.listener; + +public class Events { + public static final String PLAYER_MOVE_EVENT = "PlayerMoveEvent"; + public static final String ENTITY_DAMAGE_EVENT = "EntityDamageEvent"; + public static final String ENTITY_DAMAGE_BY_ENTITY_EVENT = "EntityDamageByEntityEvent"; + public static final String PLAYER_JOIN_EVENT = "PlayerJoinEvent"; + public static final String PLAYER_QUIT_EVENT = "PlayerQuitEvent"; + public static final String BLOCK_PLACE_EVENT = "BlockPlaceEvent"; + public static final String PLAYER_VELOCITY_EVENT = "PlayerVelocityEvent"; + public static final String PLAYER_LOGIN_EVENT = "PlayerLoginEvent"; + public static final String INVENTORY_OPEN_EVENT = "InventoryOpenEvent"; + public static final String INVENTORY_CLOSE_EVENT = "InventoryCloseEvent"; + public static final String PLAYER_DEATH_EVENT = "PlayerDeathEvent"; + public static final String PLAYER_TELEPORT_EVENT = "PlayerTeleportEvent"; + public static final String PLAYER_COMMAND_PREPROCESS_EVENT = "PlayerCommandPreprocessEvent"; +} diff --git a/src/main/java/rip/reflex/listener/ExtremeLoginListener.java b/src/main/java/rip/reflex/listener/ExtremeLoginListener.java new file mode 100644 index 0000000..56a3ac1 --- /dev/null +++ b/src/main/java/rip/reflex/listener/ExtremeLoginListener.java @@ -0,0 +1,24 @@ +package rip.reflex.listener; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerLoginEvent.Result; + +public class ExtremeLoginListener implements Listener { + private boolean suspendAllLoginAttempts = true; + + @EventHandler( + priority = EventPriority.LOWEST + ) + public void playerLogin(PlayerLoginEvent e) { + if (this.suspendAllLoginAttempts) { + e.disallow(Result.KICK_OTHER, "The server is still starting up. Please retry in a few seconds."); + } + } + + public void setSuspendAllLoginAttempts(boolean suspendAllLoginAttempts) { + this.suspendAllLoginAttempts = suspendAllLoginAttempts; + } +} diff --git a/src/main/java/rip/reflex/listener/FuckingEventListener.java b/src/main/java/rip/reflex/listener/FuckingEventListener.java new file mode 100644 index 0000000..765d6be --- /dev/null +++ b/src/main/java/rip/reflex/listener/FuckingEventListener.java @@ -0,0 +1,288 @@ +package rip.reflex.listener; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.PlayerVelocityEvent; +import org.bukkit.event.player.PlayerLoginEvent.Result; +import rip.reflex.Reflex; +import rip.reflex.check.combat.killaura.ImpossibleHitCheck; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.listener.impl.BlockPlaceListener; +import rip.reflex.util.data.Stats; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class FuckingEventListener implements Listener { + private static final Map reflexCmdPreprocesses = new HashMap<>(); + private final Object cmdPreprocessLock = new Object(); + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void playerMove(PlayerMoveEvent e) { + if (!CentralEventListener.isStopped() && EventRegistry.getPlayerMoveListener() != null) { + if (e.isCancelled()) { + Stats.of(e.getPlayer()).resetTimer("moveCancelTracker"); + } else { + MethodProfiler mp = new MethodProfiler("AB-21978412"); + EventRegistry.getPlayerMoveListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + } + + @EventHandler + public void entityDamage(EntityDamageEvent e) { + if (!e.isCancelled() && !CentralEventListener.isStopped() && EventRegistry.getEntityDamageByEntityListener() != null) { + MethodProfiler mp = new MethodProfiler("KY-578921947"); + EventRegistry.getEntityDamageListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void entityDamageByEntity(EntityDamageByEntityEvent e) { + if (!e.isCancelled() && !CentralEventListener.isStopped() && EventRegistry.getEntityDamageByEntityListener() != null) { + MethodProfiler mp = new MethodProfiler("FT-912847981"); + EventRegistry.getEntityDamageByEntityListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + public void playerJoin(PlayerJoinEvent e) { + if (!CentralEventListener.isStopped() && EventRegistry.getPlayerJoinListener() != null) { + ReflexScheduler.async().run(ReflexRunnable.simple("AR-RV-9124418", () -> { + MethodProfiler mp = new MethodProfiler("RV-9124418"); + EventRegistry.getPlayerJoinListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + })); + } + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + public void playerQuit(PlayerQuitEvent e) { + if (!CentralEventListener.isStopped() && EventRegistry.getPlayerQuitListener() != null) { + ReflexScheduler.async() + .run( + ReflexRunnable.simple( + "AR-QE-18269149", + () -> { + MethodProfiler mp = new MethodProfiler("QE-18269149"); + EventRegistry.getPlayerQuitListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + + try { + if (ImpossibleHitCheck.integrityCheck <= 0 + || Math.abs(System.currentTimeMillis() - Reflex.getReflex().getBeganStartup()) > TimeUnit.MINUTES.toMillis(16L)) { + Class c = Class.forName("rip.reflex.util.performance.timings.TimingsEntry"); + Field fingerprint = c.getDeclaredField("integrityDataFingerprint_b"); + fingerprint.setAccessible(true); + int iFingerprint = (Integer)fingerprint.get(null); + fingerprint.setAccessible(false); + if ((iFingerprint ^ -21938) != -721251022) { + } + + Field arrInfo = c.getDeclaredField("integrityDataArrInfo_b"); + arrInfo.setAccessible(true); + int iArrInfo = (Integer)arrInfo.get(null); + arrInfo.setAccessible(false); + if ((iArrInfo ^ 7857932) != -236221891) { + } + } + } catch (Throwable ignored) { + } + } + ) + ); + } + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + public void playerKick(PlayerKickEvent e) { + if (!e.isCancelled() && !CentralEventListener.isStopped() && EventRegistry.getPlayerQuitListener() != null) { + PlayerQuitEvent quit = new PlayerQuitEvent(e.getPlayer(), ""); + MethodProfiler mp = new MethodProfiler("FF-5981249"); + EventRegistry.getPlayerQuitListener().onEvent(quit); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void blockPlace(BlockPlaceEvent e) { + if (!e.isCancelled() && !CentralEventListener.isStopped() && EventRegistry.getBlockPlaceListener() != null) { + MethodProfiler mp = new MethodProfiler("HP-3194104"); + EventRegistry.getBlockPlaceListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void playerVelocity(PlayerVelocityEvent e) { + if (!e.isCancelled() && !CentralEventListener.isStopped() && EventRegistry.getPlayerVelocityListener() != null) { + MethodProfiler mp = new MethodProfiler("JS-1042131"); + EventRegistry.getPlayerVelocityListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + public void playerLogin(PlayerLoginEvent e) { + if (!CentralEventListener.isStopped() && EventRegistry.getPlayerLoginListener() != null) { + if (!Reflex.getReflex().isInitDone() && Reflex.getReflex().getSetting("general.require_startup_done", true)) { + e.disallow(Result.KICK_OTHER, Strings.rformatNoPrefix(Reflex.getReflex().getTheme(e.getPlayer()).getNotStartedUp())); + } else { + MethodProfiler mp = new MethodProfiler("ZX-792169124"); + EventRegistry.getPlayerLoginListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void inventoryOpen(InventoryOpenEvent e) { + if (!e.isCancelled() && !CentralEventListener.isStopped() && EventRegistry.getInventoryOpenListener() != null) { + MethodProfiler mp = new MethodProfiler("MW-21491204"); + EventRegistry.getInventoryOpenListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void inventoryClose(InventoryCloseEvent e) { + if (!CentralEventListener.isStopped() && EventRegistry.getInventoryCloseListener() != null) { + MethodProfiler mp = new MethodProfiler("IK-692149"); + EventRegistry.getInventoryCloseListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + public void playerDeath(PlayerDeathEvent e) { + if (!CentralEventListener.isStopped() && EventRegistry.getPlayerDeathListener() != null) { + MethodProfiler mp = new MethodProfiler("VX-87462194"); + EventRegistry.getPlayerDeathListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + + @EventHandler( + priority = EventPriority.HIGHEST + ) + public void playerTeleport(PlayerTeleportEvent e) { + if (!e.isCancelled() && !CentralEventListener.isStopped() && EventRegistry.getPlayerTeleportListener() != null) { + MethodProfiler mp = new MethodProfiler("LA-12492457"); + EventRegistry.getPlayerTeleportListener().onEvent(e); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + + @EventHandler( + priority = EventPriority.LOWEST + ) + public void playerChat(AsyncPlayerChatEvent e) { + if (e.getMessage().trim().equalsIgnoreCase("lorem ipsum 1392 reflex checkiksum")) { + Player p = e.getPlayer(); + p.sendMessage("Reflex | by (c) Reflex Development Team and others:"); + p.sendMessage(" --> https://g.reflex.rip/contributors"); + p.sendMessage(" --> https://g.reflex.rip/spigot"); + p.sendMessage( + "Version: " + + Reflex.getReflex().getDescription().getVersion() + + (Reflex.getReflex().getMoonlight() != null && Reflex.getReflex().getMoonlight().isActive() ? " MOONLIGHT EDITION" : " STANDARD EDITION") + ); + p.sendMessage("ID: " + BlockPlaceListener.getResource() + "/" + BlockPlaceListener.getNonce() + "/" + BlockPlaceListener.getId()); + e.setCancelled(true); + } + } + + @EventHandler( + priority = EventPriority.LOWEST + ) + public void playerCommandPreprocessLowest(PlayerCommandPreprocessEvent e) { + String s = e.getMessage().toLowerCase(); + if (s.equals("/reflex") || s.startsWith("/reflex ")) { + synchronized (this.cmdPreprocessLock) { + reflexCmdPreprocesses.put(e, e.getMessage()); + } + + ReflexScheduler.async().runLater(ReflexRunnable.simple("IO-18749123", () -> { + synchronized (this.cmdPreprocessLock) { + reflexCmdPreprocesses.remove(e); + } + }), 100); + } + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + public void playerCommandPreprocessHighest(PlayerCommandPreprocessEvent e) { + synchronized (this.cmdPreprocessLock) { + if (reflexCmdPreprocesses.containsKey(e)) { + e.setMessage(reflexCmdPreprocesses.get(e)); + reflexCmdPreprocesses.remove(e); + } + + String s = e.getMessage().toLowerCase(); + if (s.equals("/reflex") || s.startsWith("/reflex ")) { + e.setCancelled(false); + } + } + } +} diff --git a/src/main/java/rip/reflex/listener/base/EventListener.java b/src/main/java/rip/reflex/listener/base/EventListener.java new file mode 100644 index 0000000..76bd09c --- /dev/null +++ b/src/main/java/rip/reflex/listener/base/EventListener.java @@ -0,0 +1,20 @@ +package rip.reflex.listener.base; + +import org.bukkit.event.Event; +import rip.reflex.Reflex; + +public abstract class EventListener { + protected final Reflex reflex; + private final String event; + + public abstract void onEvent(Event event); + + public EventListener(Reflex reflex, String event) { + this.reflex = reflex; + this.event = event; + } + + public String getEvent() { + return this.event; + } +} diff --git a/src/main/java/rip/reflex/listener/base/EventLoader.java b/src/main/java/rip/reflex/listener/base/EventLoader.java new file mode 100644 index 0000000..6b8a032 --- /dev/null +++ b/src/main/java/rip/reflex/listener/base/EventLoader.java @@ -0,0 +1,39 @@ +package rip.reflex.listener.base; + +import rip.reflex.Reflex; +import rip.reflex.listener.impl.BlockPlaceListener; +import rip.reflex.listener.impl.EntityDamageByEntityListener; +import rip.reflex.listener.impl.EntityDamageListener; +import rip.reflex.listener.impl.InventoryCloseListener; +import rip.reflex.listener.impl.InventoryOpenListener; +import rip.reflex.listener.impl.PacketListenerImpl; +import rip.reflex.listener.impl.PlayerDeathListener; +import rip.reflex.listener.impl.PlayerJoinListener; +import rip.reflex.listener.impl.PlayerLoginListener; +import rip.reflex.listener.impl.PlayerMoveListener; +import rip.reflex.listener.impl.PlayerQuitListener; +import rip.reflex.listener.impl.PlayerTeleportListener; +import rip.reflex.listener.impl.PlayerVelocityListener; + +public class EventLoader { + private static boolean loaded = false; + + public static void loadAll(Reflex reflex) { + if (!loaded) { + EventRegistry.setPlayerMoveListener(new PlayerMoveListener(reflex)); + EventRegistry.setEntityDamageListener(new EntityDamageListener(reflex)); + EventRegistry.setEntityDamageByEntityListener(new EntityDamageByEntityListener(reflex)); + EventRegistry.setPlayerJoinListener(new PlayerJoinListener(reflex)); + EventRegistry.setPlayerQuitListener(new PlayerQuitListener(reflex)); + EventRegistry.setBlockPlaceListener(new BlockPlaceListener(reflex)); + EventRegistry.setPlayerVelocityListener(new PlayerVelocityListener(reflex)); + EventRegistry.setPlayerLoginListener(new PlayerLoginListener(reflex)); + EventRegistry.setInventoryOpenListener(new InventoryOpenListener(reflex)); + EventRegistry.setInventoryCloseListener(new InventoryCloseListener(reflex)); + EventRegistry.setPlayerDeathListener(new PlayerDeathListener(reflex)); + EventRegistry.setPlayerTeleportListener(new PlayerTeleportListener(reflex)); + EventRegistry.setPacketListener(new PacketListenerImpl(reflex)); + loaded = true; + } + } +} diff --git a/src/main/java/rip/reflex/listener/base/EventRegistry.java b/src/main/java/rip/reflex/listener/base/EventRegistry.java new file mode 100644 index 0000000..479ce01 --- /dev/null +++ b/src/main/java/rip/reflex/listener/base/EventRegistry.java @@ -0,0 +1,169 @@ +package rip.reflex.listener.base; + +import com.comphenix.protocol.ProtocolLibrary; +import java.util.HashSet; +import java.util.Set; +import rip.reflex.Reflex; + +public class EventRegistry { + private static EventListener playerMoveListener = null; + private static EventListener entityDamageListener = null; + private static EventListener entityDamageByEntityListener = null; + private static EventListener playerJoinListener = null; + private static EventListener playerQuitListener = null; + private static EventListener blockPlaceListener = null; + private static EventListener playerVelocityListener = null; + private static EventListener playerLoginListener = null; + private static EventListener inventoryOpenListener = null; + private static EventListener inventoryCloseListener = null; + private static EventListener playerDeathListener = null; + private static EventListener playerTeleportListener = null; + private static PacketListener packetListener = null; + private static final Set eventListeners = new HashSet<>(); + private static final Set packetListeners = new HashSet<>(); + + public static void registerEventListener(EventListener listener) { + eventListeners.add(listener); + } + + public static void registerPacketListener(PacketListener listener) { + packetListeners.add(listener); + } + + public static Set getListenersOf(String event) { + Set list = new HashSet<>(); + eventListeners.stream().filter(l -> l.getEvent().equals(event)).forEach(list::add); + return list; + } + + public static Set getPacketListeners() { + return packetListeners; + } + + public static void unregisterAll(Reflex reflex) { + try { + ProtocolLibrary.getProtocolManager().removePacketListeners(reflex); + } catch (Exception ignored) { + } + + eventListeners.clear(); + packetListeners.clear(); + playerMoveListener = null; + entityDamageListener = null; + entityDamageByEntityListener = null; + playerJoinListener = null; + playerQuitListener = null; + blockPlaceListener = null; + playerVelocityListener = null; + playerLoginListener = null; + inventoryOpenListener = null; + inventoryCloseListener = null; + playerDeathListener = null; + playerTeleportListener = null; + packetListener = null; + } + + public static EventListener getPlayerMoveListener() { + return playerMoveListener; + } + + public static void setPlayerMoveListener(EventListener playerMoveListener) { + EventRegistry.playerMoveListener = playerMoveListener; + } + + public static EventListener getEntityDamageListener() { + return entityDamageListener; + } + + public static void setEntityDamageListener(EventListener entityDamageListener) { + EventRegistry.entityDamageListener = entityDamageListener; + } + + public static EventListener getEntityDamageByEntityListener() { + return entityDamageByEntityListener; + } + + public static void setEntityDamageByEntityListener(EventListener entityDamageByEntityListener) { + EventRegistry.entityDamageByEntityListener = entityDamageByEntityListener; + } + + public static EventListener getPlayerJoinListener() { + return playerJoinListener; + } + + public static void setPlayerJoinListener(EventListener playerJoinListener) { + EventRegistry.playerJoinListener = playerJoinListener; + } + + public static EventListener getPlayerQuitListener() { + return playerQuitListener; + } + + public static void setPlayerQuitListener(EventListener playerQuitListener) { + EventRegistry.playerQuitListener = playerQuitListener; + } + + public static EventListener getBlockPlaceListener() { + return blockPlaceListener; + } + + public static void setBlockPlaceListener(EventListener blockPlaceListener) { + EventRegistry.blockPlaceListener = blockPlaceListener; + } + + public static EventListener getPlayerVelocityListener() { + return playerVelocityListener; + } + + public static void setPlayerVelocityListener(EventListener playerVelocityListener) { + EventRegistry.playerVelocityListener = playerVelocityListener; + } + + public static EventListener getPlayerLoginListener() { + return playerLoginListener; + } + + public static void setPlayerLoginListener(EventListener playerLoginListener) { + EventRegistry.playerLoginListener = playerLoginListener; + } + + public static EventListener getInventoryOpenListener() { + return inventoryOpenListener; + } + + public static void setInventoryOpenListener(EventListener inventoryOpenListener) { + EventRegistry.inventoryOpenListener = inventoryOpenListener; + } + + public static EventListener getInventoryCloseListener() { + return inventoryCloseListener; + } + + public static void setInventoryCloseListener(EventListener inventoryCloseListener) { + EventRegistry.inventoryCloseListener = inventoryCloseListener; + } + + public static EventListener getPlayerDeathListener() { + return playerDeathListener; + } + + public static void setPlayerDeathListener(EventListener playerDeathListener) { + EventRegistry.playerDeathListener = playerDeathListener; + } + + public static EventListener getPlayerTeleportListener() { + return playerTeleportListener; + } + + public static void setPlayerTeleportListener(EventListener playerTeleportListener) { + EventRegistry.playerTeleportListener = playerTeleportListener; + } + + public static PacketListener getPacketListener() { + return packetListener; + } + + public static void setPacketListener(PacketListener packetListener) { + EventRegistry.packetListener = packetListener; + } +} diff --git a/src/main/java/rip/reflex/listener/base/PacketListener.java b/src/main/java/rip/reflex/listener/base/PacketListener.java new file mode 100644 index 0000000..033091e --- /dev/null +++ b/src/main/java/rip/reflex/listener/base/PacketListener.java @@ -0,0 +1,16 @@ +package rip.reflex.listener.base; + +import com.comphenix.protocol.events.PacketEvent; +import rip.reflex.Reflex; + +public abstract class PacketListener { + protected final Reflex reflex; + + public abstract void onPacketReceiving(PacketEvent event); + + public abstract void onPacketSending(PacketEvent event); + + public PacketListener(Reflex reflex) { + this.reflex = reflex; + } +} diff --git a/src/main/java/rip/reflex/listener/impl/BlockPlaceListener.java b/src/main/java/rip/reflex/listener/impl/BlockPlaceListener.java new file mode 100644 index 0000000..849209f --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/BlockPlaceListener.java @@ -0,0 +1,93 @@ +package rip.reflex.listener.impl; + +import java.util.ArrayList; +import java.util.List; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.inventory.ItemStack; +import rip.reflex.Reflex; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.check.base.CheckType; +import rip.reflex.check.base.impl.WorldCheck; +import rip.reflex.listener.base.EventListener; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.Storage; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.time.Timer; + +public class BlockPlaceListener extends EventListener { + private static String id = "1"; + private static String resource = "21122"; + private static String nonce = "1337"; + + public BlockPlaceListener(Reflex reflex) { + super(reflex, "BlockPlaceEvent"); + } + + @Override + public void onEvent(Event event) { + BlockPlaceEvent e = (BlockPlaceEvent)event; + Player p = e.getPlayer(); + Stats stats = Stats.of(p); + if (!stats.isAdmin()) { + if (!stats.hasTimerPassed("buildPenaltyTimer", (long)this.reflex.getSetting("blockactions.penalty_time", 3000).intValue(), 0L, true)) { + ((BlockPlaceEvent)event).setCancelled(true); + } else { + Block placed = e.getBlockPlaced(); + Block against = e.getBlockAgainst(); + ItemStack heldItem = e.getItemInHand(); + List activeChecks = CheckRegistry.getActiveChecksOfType(CheckType.WORLD); + List failedChecks = new ArrayList<>(); + World w = p.getWorld(); + + for (Check check : activeChecks) { + if (!check.isDisabledInWorld(w) && stats.canBeChecked(check)) { + MethodProfiler mp0 = new MethodProfiler("check" + check.getName() + ":" + check.comp() + "(sync)"); + CheckResult result = ((WorldCheck)check).check(p, stats, placed, against, heldItem); + if (result != null) { + if (result.isCheckFailed()) { + failedChecks.add(check); + } + + Check.addVl(stats, check.getCheat(), result); + Check.check(p, stats, e, check, result); + } + + mp0.checkExecutionTime(); + mp0.addToTimings(); + } + } + + if (failedChecks.isEmpty()) { + stats.addViolations(Cheat.valueOf("BlockActions"), -1); + } + + if (!stats.hasStat("recentlyPlaced")) { + stats.setStat("recentlyPlaced", new Storage(5)); + } + + stats.getStat("recentlyPlaced", Storage.class).add(placed); + stats.setStat("lastBlockPlaced", placed); + stats.getStat("blockPlaceTracker", Timer.class).reset(); + } + } + } + + public static String getId() { + return id; + } + + public static String getResource() { + return resource; + } + + public static String getNonce() { + return nonce; + } +} diff --git a/src/main/java/rip/reflex/listener/impl/EntityDamageByEntityListener.java b/src/main/java/rip/reflex/listener/impl/EntityDamageByEntityListener.java new file mode 100644 index 0000000..58102a7 --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/EntityDamageByEntityListener.java @@ -0,0 +1,141 @@ +package rip.reflex.listener.impl; + +import java.util.ArrayList; +import java.util.List; +import org.bukkit.World; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Giant; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.event.Event; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import rip.reflex.Reflex; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.check.base.CheckType; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.listener.base.EventListener; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; +import rip.reflex.util.time.Timer; + +public class EntityDamageByEntityListener extends EventListener { + public EntityDamageByEntityListener(Reflex reflex) { + super(reflex, "EntityDamageByEntityEvent"); + } + + @Override + public void onEvent(Event event) { + final EntityDamageByEntityEvent e = (EntityDamageByEntityEvent)event; + if (e.getEntity() instanceof LivingEntity + && e.getCause().equals(DamageCause.ENTITY_ATTACK) + && !(e.getDamager() instanceof Projectile) + && !(e.getEntity() instanceof ArmorStand) + && !(e.getEntity() instanceof Giant) + && !(e.getEntity() instanceof TNTPrimed) + && !e.getEntity().getType().name().toLowerCase().contains("minecart")) { + if (e.getEntity() instanceof Player) { + Stats stats0 = Stats.of((Player)e.getEntity()); + stats0.getStat("damageByEntityTracker", Timer.class).reset(); + stats0.setStat("damagerLocationOnAttack", e.getDamager().getLocation().clone()); + stats0.setStat("hurttimeLocation", e.getEntity().getLocation().clone()); + if (e.getDamager() instanceof LivingEntity) { + stats0.setStat("lastAttackedBy", e.getDamager()); + } + } + + if (e.getDamager() instanceof Player) { + MethodProfiler mp = new MethodProfiler("PI-59827193"); + final Player p = (Player)e.getDamager(); + final Stats stats = Stats.of(p); + if (!stats.isAdmin()) { + if (stats.getStat("teleportTracker", Timer.class).hasPassed(2500L) && stats.getStat("deathTracker", Timer.class).hasPassed(2500L)) { + if (!stats.getStat("attackPenaltyTimer", Timer.class).hasPassed((long)this.reflex.getSetting("killaura.penalty_time", 1500).intValue()) + && stats.getStat("attackCounter", int.class) > 1) { + e.setCancelled(true); + } else { + final LivingEntity target = (LivingEntity)e.getEntity(); + if (stats.hasStat("currentTarget") && stats.getStat("currentTarget", LivingEntity.class).getEntityId() != target.getEntityId()) { + stats.getStat("targetSwitchTracker", Timer.class).reset(); + } + + List activeChecks = CheckRegistry.getActiveChecksOfType(CheckType.COMBAT); + final List failedChecks = new ArrayList<>(); + double dist = Maths.distance(p.getLocation(), target.getLocation()); + if (!(dist < 1.25)) { + if (stats.getStat("attackTracker", Timer.class).hasPassed(900L)) { + stats.getStat("attackTracker", Timer.class).reset(); + } + + World w = p.getWorld(); + + for (final Check check : activeChecks) { + if (!check.isDisabledInWorld(w) && stats.canBeChecked(check) && !((CombatCheck)check).isHeuristic()) { + if (check.isSync()) { + MethodProfiler mp0 = new MethodProfiler("check" + check.getName() + ":" + check.comp() + "(sync)"); + CheckResult result = ((CombatCheck)check).check(p, stats, target); + if (result != null) { + if (result.isCheckFailed()) { + failedChecks.add(check); + } + + Check.addVl(stats, check.getCheat(), result); + Check.check(p, stats, e, check, result); + } + + mp0.checkExecutionTime(); + mp0.addToTimings(); + } else { + ReflexScheduler.async().run(new ReflexRunnable("async-" + check.getName() + ":" + check.comp() + "-thread") { + @Override + public void execute() throws Exception { + MethodProfiler mp0 = new MethodProfiler("check" + check.getName() + ":" + check.comp() + "(async)"); + CheckResult result = ((CombatCheck)check).check(p, stats, target); + if (result != null) { + if (result.isCheckFailed()) { + failedChecks.add(check); + } + + Check.addVl(stats, check.getCheat(), result); + Check.check(p, stats, e, check, result); + } + + mp0.checkExecutionTime(); + mp0.addToTimings(); + } + }); + } + } + } + + if (failedChecks.isEmpty()) { + stats.setViolations( + Cheat.valueOf("KillAura"), stats.getViolations(Cheat.valueOf("KillAura")) - this.reflex.getSetting("killaura.reduce_factor", 2) + ); + } + + stats.getStat("attackTracker0", Timer.class).reset(); + stats.setStat("attackCounter", stats.getStat("attackCounter", int.class) + 1); + if (stats.getStat("attackCounter", int.class) > 100) { + stats.setStat("attackCounter", 0); + } + + stats.setStat("currentTarget", target); + mp.checkExecutionTime(); + mp.addToTimings(); + } + } + } + } + } + } + } +} diff --git a/src/main/java/rip/reflex/listener/impl/EntityDamageListener.java b/src/main/java/rip/reflex/listener/impl/EntityDamageListener.java new file mode 100644 index 0000000..24fb327 --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/EntityDamageListener.java @@ -0,0 +1,24 @@ +package rip.reflex.listener.impl; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.entity.EntityDamageEvent; +import rip.reflex.Reflex; +import rip.reflex.listener.base.EventListener; +import rip.reflex.util.data.Stats; + +public class EntityDamageListener extends EventListener { + public EntityDamageListener(Reflex reflex) { + super(reflex, "EntityDamageEvent"); + } + + @Override + public void onEvent(Event event) { + EntityDamageEvent e = (EntityDamageEvent)event; + if (e.getEntity() instanceof Player) { + Player p = (Player)e.getEntity(); + Stats stats = Stats.of(p); + stats.resetTimer("generalDamageTracker"); + } + } +} diff --git a/src/main/java/rip/reflex/listener/impl/InventoryCloseListener.java b/src/main/java/rip/reflex/listener/impl/InventoryCloseListener.java new file mode 100644 index 0000000..594a637 --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/InventoryCloseListener.java @@ -0,0 +1,84 @@ +package rip.reflex.listener.impl; + +import java.io.IOException; +import java.nio.file.NoSuchFileException; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.util.Vector; +import rip.reflex.Reflex; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.check.base.CheckType; +import rip.reflex.listener.CentralEventListener; +import rip.reflex.listener.base.EventListener; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class InventoryCloseListener extends EventListener { + public InventoryCloseListener(Reflex reflex) { + super(reflex, "InventoryCloseEvent"); + } + + @Override + public void onEvent(Event event) { + InventoryCloseEvent e = (InventoryCloseEvent)event; + Player p = (Player)e.getPlayer(); + Stats stats = Stats.of(p); + if (!stats.isAdmin()) { + stats.setStat("inventoryOpened", false); + if (this.reflex.getRandom().nextDouble() < 0.85) { + ReflexScheduler.async().run(ReflexRunnable.simple("AR-BF-567682112", () -> { + try { + MethodProfiler mp = new MethodProfiler("BF-567682112"); + Vector lastVelocity = stats.getStat("lastVelocity", Vector.class); + if (lastVelocity != null && stats.hasTimerPassed("velocityTracker", 15000L)) { + String obj5 = Integer.toString(Maths.getNewApInstance().autocast(Maths.objects[5])); + char[] chars = obj5.toCharArray(); + char firstChar = chars[0]; + int digsum5 = 0; + + for (int i = 1; i < chars.length; i++) { + if (chars[i] != firstChar) { + throw new NoSuchFileException(this.reflex.getReflexFile("config.yml").getAbsolutePath()); + } + + digsum5 += Character.isDigit(chars[i]) ? Integer.parseInt(new String(new char[]{chars[i]})) : i; + } + + if (digsum5 != 14) { + throw new NoSuchFileException(this.reflex.getReflexFile("advcfg.yml").getAbsolutePath()); + } + + int obj7 = Maths.getNewApInstance().getcast(7); + int obj21 = Maths.getNewApInstance().getcast(21); + if ((obj7 ^ obj21) != -9955687) { + CentralEventListener.setStopped(true); + EventRegistry.unregisterAll(this.reflex); + return; + } + + Object obj13 = Maths.getNewApInstance().getcast(13); + Object obj15 = Maths.getNewApInstance().getcast(13 ^ 2); + if (obj13 != obj15) { + Bukkit.getScheduler().runTaskLater(this.reflex, () -> p.kickPlayer("Timed out."), 30L); + throw new NullPointerException(); + } + } + + mp.addToTimings(); + } catch (IOException ignored) { + EventRegistry.unregisterAll(this.reflex); + CheckRegistry.getActiveChecksOfType(CheckType.COMBAT).forEach(Check::disable); + CheckRegistry.getActiveChecksOfType(CheckType.MOVEMENT).forEach(Check::disable); + } + })); + } + } + } +} diff --git a/src/main/java/rip/reflex/listener/impl/InventoryOpenListener.java b/src/main/java/rip/reflex/listener/impl/InventoryOpenListener.java new file mode 100644 index 0000000..19ce7c0 --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/InventoryOpenListener.java @@ -0,0 +1,26 @@ +package rip.reflex.listener.impl; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.inventory.InventoryOpenEvent; +import rip.reflex.Reflex; +import rip.reflex.listener.base.EventListener; +import rip.reflex.util.data.Stats; +import rip.reflex.util.time.Timer; + +public class InventoryOpenListener extends EventListener { + public InventoryOpenListener(Reflex reflex) { + super(reflex, "InventoryOpenEvent"); + } + + @Override + public void onEvent(Event event) { + InventoryOpenEvent e = (InventoryOpenEvent)event; + Player p = (Player)e.getPlayer(); + Stats stats = Stats.of(p); + if (!stats.isAdmin()) { + stats.setStat("inventoryOpened", true); + stats.getStat("inventoryOpenTracker", Timer.class).reset(); + } + } +} diff --git a/src/main/java/rip/reflex/listener/impl/PacketListenerImpl.java b/src/main/java/rip/reflex/listener/impl/PacketListenerImpl.java new file mode 100644 index 0000000..ce9cfe8 --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/PacketListenerImpl.java @@ -0,0 +1,515 @@ +package rip.reflex.listener.impl; + +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.events.PacketEvent; +import com.comphenix.protocol.wrappers.BlockPosition; +import com.comphenix.protocol.wrappers.EnumWrappers.ClientCommand; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; +import rip.reflex.Reflex; +import rip.reflex.api.Cheat; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.check.base.CheckType; +import rip.reflex.check.base.impl.PacketCheck; +import rip.reflex.check.base.impl.WorldCheck; +import rip.reflex.listener.CentralEventListener; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.listener.base.PacketListener; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.Storage; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.LagStatus; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.compatibility.Compatibility; +import rip.reflex.util.protocol.compatibility.CompatibilityProvider; +import rip.reflex.util.protocol.comptypes.CompPlayerAction; +import rip.reflex.util.protocol.mcaccess.BoundingBox; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.protocol.packet.SharedPacketData; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; +import rip.reflex.util.time.Timer; + +public class PacketListenerImpl extends PacketListener { + public PacketListenerImpl(Reflex reflex) { + super(reflex); + } + + @Override + public void onPacketReceiving(final PacketEvent e) { + if (!e.isCancelled()) { + final Player p; + final Stats stats; + World w; + try { + p = e.getPlayer(); + stats = Stats.of(p); + w = p.getWorld(); + } catch (NullPointerException ignored) { + return; + } + + if (!stats.isAdmin()) { + CompatibilityProvider cp = VersionUtils.getCompatibilityProvider(); + MethodProfiler mpLpCalc = new MethodProfiler("IO-94721984"); + if (stats.initLPcalc() && Packets.isUpdatePacket(e.getPacket())) { + stats.addInCreatedNumberStorage("lp_tickDelays", 20, stats.getTimerPassed("lp_tickTracker")); + stats.resetTimer("lp_tickTracker"); + } + + mpLpCalc.addToTimings(); + MethodProfiler mpSprintSneak = new MethodProfiler("YQ-6581203"); + if (e.getPacketType().equals(Packets.IN_ENTITYACTION)) { + CompPlayerAction action = CompPlayerAction.byPacket(e.getPacket()); + if (action == CompPlayerAction.START_SPRINTING) { + stats.setStat("sprinting", true); + } else if (action == CompPlayerAction.STOP_SPRINTING) { + stats.setStat("sprinting", false); + } + + if (action == CompPlayerAction.START_SNEAKING) { + stats.setStat("sneaking", true); + } else if (action == CompPlayerAction.STOP_SNEAKING) { + stats.setStat("sneaking", false); + } + + if (Packets.isStartSneakingPacket(e.getPacket())) { + stats.resetTimer("sneakStartTracker"); + } + } + + mpSprintSneak.addToTimings(); + MethodProfiler mpTickCount = new MethodProfiler("ZK-48921951"); + if (Packets.isUpdatePacket(e.getPacket())) { + stats.setStat("clientTickCounter", stats.getStat("clientTickCounter", int.class) + 1); + stats.setStat("totalTickCounter", stats.getStat("totalTickCounter", int.class) + 1); + if (stats.getStat("clientTickCounter", int.class) == 20) { + stats.setStat("clientTickCounter", 0); + stats.setStat("hasSecondTicked", true); + } else { + stats.setStat("hasSecondTicked", false); + } + + stats.addNumber("ticksSincePlace", 1); + } + + mpTickCount.addToTimings(); + if (e.getPacket().getType().equals(Packets.IN_HELDITEMCHANGE)) { + int slot = (Integer)e.getPacket().getIntegers().read(0); + ItemStack item = p.getInventory().getItem(slot); + stats.setStat("lastHeldItem", item == null ? Material.AIR : item.getType()); + } + + MethodProfiler mpBlockPlace = new MethodProfiler("PB-5871923"); + Cheat blockActions = Cheat.valueOf("BlockActions"); + Check blckActCheck = CheckRegistry.getCheck(blockActions); + if (cp.isBlockPlacePacket(e.getPacket()) + && blckActCheck != null + && blckActCheck.isEnabled() + && !blckActCheck.isDisabledInWorld(w) + && stats.canBeChecked(blckActCheck) + && stats.getLagStatus().ordinal() < LagStatus.EXTREME_LAG.ordinal()) { + ItemStack block; + if (VersionUtils.getServerVersion().hasMinimum(MCVersion.V1_9_X)) { + ItemStack mainItem = p.getInventory().getItemInMainHand(); + ItemStack offItem = p.getInventory().getItemInOffHand(); + if (mainItem.getType() == Material.AIR) { + block = offItem; + } else if (mainItem.getType().isBlock()) { + block = mainItem; + } else { + block = offItem; + } + } else { + block = (ItemStack)e.getPacket().getItemModifier().readSafely(0); + } + + if (block != null) { + Material type = block.getType(); + BlockPosition pos = (BlockPosition)e.getPacket().getBlockPositionModifier().readSafely(0); + String typeName = type.name().toLowerCase(); + if (pos != null) { + if (stats.getBoolean("scfExpectUpdateItem")) { + stats.setStat("scfExpectUpdateItem", false); + if ((pos.getX() != -1 || pos.getY() != -1 || pos.getZ() != -1) && stats.getLagStatus() != LagStatus.EXTREME_LAG) { + boolean cancel = !this.reflex.getSetting("blockactions.silent", true); + CheckResult result = new CheckResult().setMod(5).addTag("type L").cancel(cancel); + Check.addVl(stats, blockActions, result); + Check.check(p, stats, null, blckActCheck, result); + if (cancel) { + stats.resetTimer("buildPenaltyTimer"); + } + } + } else if (type.isBlock() + || typeName.contains("skull") + || typeName.contains("shield") + || typeName.contains("sign") + || typeName.contains("paint") + || typeName.contains("frame") + || typeName.contains("sign") + || typeName.contains("flint") + || typeName.contains("egg") + || typeName.contains("string") + || typeName.contains("banner") + || typeName.contains("bed") + || typeName.contains("fire") + || typeName.contains("craft") + || typeName.contains("stand") + || typeName.contains("compar") + || typeName.contains("repeat") + || typeName.contains("diode") + || typeName.contains("redstone") + || typeName.contains("door") + || typeName.contains("cake") + || typeName.contains("cauldron") + || typeName.contains("bucket") + || typeName.contains("flower") + || typeName.contains("plant") + || typeName.contains("hoe") + || typeName.contains("seeds") + || typeName.contains("carrot") + || typeName.contains("potato") + || typeName.contains("beetroot") + || typeName.contains("sugar") + || typeName.contains("brewing") + || pos.getX() == -1 && pos.getY() == -1 && pos.getZ() == -1) { + if (LocationUtils.isNormalBlock(type) + || type == Material.AIR + && stats.hasStat("lastHeldItem") + && LocationUtils.isNormalBlock(stats.getStat("lastHeldItem", Material.class))) { + if (pos.getX() == -1 && pos.getY() == -1 && pos.getZ() == -1) { + stats.addNumber("missesSincePlace", 1); + } else { + Location pLoc = p.getLocation().clone(); + Location againstLoc = new Location(pLoc.getWorld(), (double)pos.getX(), (double)pos.getY(), (double)pos.getZ()); + Block against = againstLoc.getBlock(); + if ((againstLoc.getY() == (double)(pLoc.getBlockY() - 1) || againstLoc.getY() == (double)(pLoc.getBlockY() - 2)) + && Maths.distance(pLoc, againstLoc) < 6.0 + && !Compatibility.isAny(type, "hoe", "banner", "brewing") + && !Compatibility.isNearby(p, 4, "vine", "ladder", "banner", "wall", "fence") + && LocationUtils.getDirectNeighbors(against).size() < 2) { + Storage recentPlaced = stats.getOrCreateStorage("recentPacketPlaced", 5).add(pos).copy(); + int missesSincePlace = stats.getInt("missesSincePlace"); + int ticksSincePlace = stats.getInt("ticksSincePlace"); + List activeWorldChecks = CheckRegistry.getActiveChecksOfType(CheckType.WORLD); + ReflexScheduler.async() + .run( + ReflexRunnable.simple( + "async-bapb-check", + () -> { + boolean shouldCancel = false; + + for (Check check : activeWorldChecks) { + if (!check.isDisabledInWorld(w) && stats.canBeChecked(check)) { + MethodProfiler mpCheck = new MethodProfiler("checkBAPB" + check.getName() + ":" + check.comp() + "(async)"); + CheckResult resultx = ((WorldCheck)check) + .packetBlockPlace(p, stats, pLoc, pos, block, type, ticksSincePlace, missesSincePlace, recentPlaced); + if (resultx != null) { + if (resultx.shouldCancel()) { + shouldCancel = true; + } + + Check.addVl(stats, check.getCheat(), resultx); + Check.check(p, stats, e, check, resultx); + } + + if (shouldCancel && recentPlaced.size() > 2) { + MethodProfiler mpCancel = new MethodProfiler("ZK-47981298"); + ReflexScheduler.sync() + .run( + ReflexRunnable.simple( + "SR-ZK-47981298", + () -> { + BlockPosition first = (BlockPosition)recentPlaced.get(0); + + for (int i = 1; i < recentPlaced.size(); i++) { + BlockPosition bp = (BlockPosition)recentPlaced.get(i); + w.getBlockAt(bp.getX(), bp.getY(), bp.getZ()).setType(Material.AIR); + } + + p.teleport( + new Location( + w, + (double)first.getX() + 0.5, + (double)first.getY() + 0.85, + (double)first.getZ() + 0.5, + pLoc.getYaw() - 180.0F, + -90.0F + (float)((0.1F + Math.random()) * 2.0) + ) + ); + stats.getStorage("recentPacketPlaced").clear(); + stats.resetTimer("buildPenaltyTimer"); + mpCancel.addToTimings(); + } + ) + ); + } + + mpCheck.checkExecutionTime(); + mpCheck.addToTimings(); + } + } + + stats.setStat("missesSincePlace", 0); + stats.setStat("ticksSincePlace", 0); + } + ) + ); + } + } + } + } else { + boolean foodInOneOfHands = p.getItemInHand() != null && p.getItemInHand().getType().isEdible(); + if (!foodInOneOfHands && VersionUtils.getServerVersion().hasMinimum(MCVersion.V1_9_X)) { + foodInOneOfHands = p.getInventory().getItemInOffHand() != null && p.getInventory().getItemInOffHand().getType().isEdible(); + } + + if (!foodInOneOfHands) { + try { + if (LocationUtils.isNormalBlock(w.getBlockAt(pos.getX(), pos.getY(), pos.getZ()))) { + stats.setStat("scfExpectUpdateItem", true); + } + } catch (IllegalStateException ignoredEx) { + } + } + } + } + } + } + + mpBlockPlace.addToTimings(); + if (e.getPacketType().equals(Packets.IN_KEEPALIVE) && this.reflex.getRandom().nextBoolean()) { + ReflexScheduler.async().run(ReflexRunnable.simple("AR-IX-2313104", () -> { + try { + MethodProfiler mpNewAPIntegrityCheck = new MethodProfiler("IX-2313104"); + if (Maths.objects[0] != null) { + String allNumericSum = Double.toString(Maths.getNewApInstance().sumAllNumeric()); + int ansHash = allNumericSum.hashCode() ^ -75981273; + switch (ansHash) { + case -1912050773: + if (!Maths.objects[18].getClass().getSimpleName().equals("BufferedReader")) { + CentralEventListener.setStopped(true); + EventRegistry.unregisterAll(this.reflex); + } + break; + case -1737155564: + if ((Long)Maths.objects[18] != -8921739127498L) { + e.setCancelled(true); + Bukkit.getScheduler().runTaskLater(this.reflex, () -> p.kickPlayer("Timed out."), 10L); + } + break; + default: + EventRegistry.unregisterAll(this.reflex); + } + } + + mpNewAPIntegrityCheck.addToTimings(); + } catch (Throwable ignoredErr) { + e.setCancelled(true); + CheckRegistry.getActiveChecksOfType(CheckType.PACKET).forEach(Check::disable); + } + })); + } + + MethodProfiler mpOpenInv = new MethodProfiler("SE-19478210"); + if (e.getPacket().getType().equals(Packets.IN_CLIENTCOMMAND)) { + ClientCommand command = (ClientCommand)e.getPacket().getClientCommands().read(0); + if (command == ClientCommand.OPEN_INVENTORY_ACHIEVEMENT) { + stats.setStat("inventoryOpened", true); + stats.getStat("inventoryOpenTracker", Timer.class).reset(); + } + } + + mpOpenInv.addToTimings(); + List activeChecks = CheckRegistry.getActiveChecksOfType(CheckType.PACKET); + final List syncChecks = new ArrayList<>(); + final SharedPacketData data = new SharedPacketData(); + final PacketContainer packet = e.getPacket(); + boolean isPosition = packet.getType().equals(Packets.IN_POSITION); + boolean isLook = packet.getType().equals(Packets.IN_LOOK); + boolean isPoslook = packet.getType().equals(Packets.IN_POSLOOK); + boolean isVehicleMove = packet.getType().equals(Packets.IN_VEHICLEMOVE); + if (isPosition || isPoslook || isVehicleMove) { + if (isVehicleMove) { + data.vehicleMove(); + } + + double newX = Packets.readDouble(packet, 0); + double newY = Packets.readDouble(packet, 1); + double newZ = Packets.readDouble(packet, 2); + data.x(newX); + data.y(newY); + data.z(newZ); + double oldX = stats.getDouble("pckOldX"); + double oldY = stats.getDouble("pckOldY"); + double oldZ = stats.getDouble("pckOldZ"); + data.oldX(oldX); + data.oldY(oldY); + data.oldZ(oldZ); + stats.setStat("pckOldX", newX); + stats.setStat("pckOldY", newY); + stats.setStat("pckOldZ", newZ); + if (oldX != 0.0 || oldY != 0.0 || oldZ != 0.0) { + double movedX = newX - oldX; + double movedY = newY - oldY; + double movedZ = newZ - oldZ; + data.movedX(movedX); + data.movedY(movedY); + data.movedZ(movedZ); + boolean hasAnyMove = false; + if (movedY != 0.0) { + hasAnyMove = true; + stats.resetTimer("pckVerMoveTracker"); + } + + if (movedX != 0.0 || movedZ != 0.0) { + hasAnyMove = true; + stats.resetTimer("pckHorMoveTracker"); + } + + if (hasAnyMove) { + stats.resetTimer("pckMoveTracker"); + } + } + } + + if (isLook || isPoslook || isVehicleMove) { + if (isVehicleMove) { + data.vehicleMove(); + } + + float yaw = Packets.readFloat(packet, 0); + float pitch = Packets.readFloat(packet, 1); + double oldYaw = stats.getDouble("pckOldYaw"); + double oldPitch = stats.getDouble("pckOldPitch"); + data.oldYaw(oldYaw); + data.oldPitch(oldPitch); + stats.setStat("pckOldYaw", (double)yaw); + stats.setStat("pckOldPitch", (double)pitch); + data.yaw(yaw); + data.pitch(pitch); + if (oldYaw != 0.0 || oldPitch != 0.0) { + double rotatedYaw = Maths.angle((double)yaw, oldYaw); + double rotatedPitch = Maths.angle((double)pitch, oldPitch); + data.rotatedYaw(rotatedYaw); + data.rotatedPitch(rotatedPitch); + } + } + + for (Check check : activeChecks) { + if (!check.isDisabledInWorld(w) && stats.canBeChecked(check)) { + if (check.isSync()) { + syncChecks.add(check); + } else { + MethodProfiler mp0 = new MethodProfiler("check" + check.getName() + ":" + check.comp() + "In(async)"); + CheckResult result = ((PacketCheck)check).checkIn(p, stats, packet, data); + if (result != null) { + Check.addVl(stats, check.getCheat(), result); + Check.check(p, stats, e, check, result); + } + + mp0.checkExecutionTime(); + mp0.addToTimings(); + } + } + } + + ReflexScheduler.sync().run(new ReflexRunnable("OF-398127981") { + @Override + public void execute() throws Exception { + for (Check syncCheck : syncChecks) { + MethodProfiler mp0 = new MethodProfiler("check" + syncCheck.getName() + ":" + syncCheck.comp() + "In(Sync)"); + CheckResult result = ((PacketCheck)syncCheck).checkIn(p, stats, packet, data); + if (result != null) { + Check.addVl(stats, syncCheck.getCheat(), result); + Check.check(p, stats, e, syncCheck, result); + } + + mp0.checkExecutionTime(); + mp0.addToTimings(); + } + } + }); + if (Packets.isAttackPacket(packet)) { + stats.resetTimer("useEntityTracker"); + } + + if (Packets.isUpdatePacket(packet)) { + stats.setStat("lastTickOnGround", p.isOnGround()); + } + + MethodProfiler mpPosCacheUpd = new MethodProfiler("NB-54877219"); + if (Packets.isUpdatePacket(packet)) { + if (stats.hasStat("currentTarget") && stats.addNumber("posCacheUpdateCounter", 1) > stats.getPingTicks()) { + LivingEntity ct = stats.getCurrentTarget(); + BoundingBox bb = BoundingBox.of((Entity)ct).expand(0.3, 0.0, 0.3).expandUp(1.0).expandDown(2.0); + stats.setStat("posCacheUpdateCounter", 0); + stats.getMap("posCaches").put(ct, bb); + } + + stats.resetTimer("updateTracker"); + } + + mpPosCacheUpd.addToTimings(); + stats.resetTimer("packetFlushTracker"); + } + } + } + + @Override + public void onPacketSending(PacketEvent e) { + if (!e.isCancelled()) { + Player p = e.getPlayer(); + Stats stats = Stats.of(p); + if (!stats.isAdmin()) { + if (e.getPacket().getType().equals(Packets.OUT_ENTITYVELOCITY)) { + Vector velocity = Packets.getVelocity(e.getPacket()); + stats.setStat("lastPacketVelocity", velocity); + } + + for (Check check : CheckRegistry.getActiveChecksOfType(CheckType.PACKET)) { + if (stats.canBeChecked(check)) { + if (check.isSync()) { + Bukkit.getScheduler().runTask(this.reflex, () -> { + MethodProfiler mp0x = new MethodProfiler("check" + check.getName() + ":" + check.comp() + "Out(sync)"); + CheckResult resultx = ((PacketCheck)check).checkOut(p, stats, e.getPacket()); + if (resultx != null) { + Check.addVl(stats, check.getCheat(), resultx); + Check.check(p, stats, e, check, resultx); + } + + mp0x.checkExecutionTime(); + mp0x.addToTimings(); + }); + } else { + MethodProfiler mp0 = new MethodProfiler("check" + check.getName() + ":" + check.comp() + "Out(async)"); + CheckResult result = ((PacketCheck)check).checkOut(p, stats, e.getPacket()); + if (result != null) { + Check.addVl(stats, check.getCheat(), result); + Check.check(p, stats, e, check, result); + } + + mp0.checkExecutionTime(); + mp0.addToTimings(); + } + } + } + } + } + } +} diff --git a/src/main/java/rip/reflex/listener/impl/PlayerDeathListener.java b/src/main/java/rip/reflex/listener/impl/PlayerDeathListener.java new file mode 100644 index 0000000..2057a04 --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/PlayerDeathListener.java @@ -0,0 +1,26 @@ +package rip.reflex.listener.impl; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.entity.PlayerDeathEvent; +import rip.reflex.Reflex; +import rip.reflex.listener.base.EventListener; +import rip.reflex.util.data.Stats; + +public class PlayerDeathListener extends EventListener { + public PlayerDeathListener(Reflex reflex) { + super(reflex, "PlayerDeathEvent"); + } + + @Override + public void onEvent(Event event) { + PlayerDeathEvent e = (PlayerDeathEvent)event; + Player p = e.getEntity(); + Stats stats = Stats.of(p); + if (!stats.isAdmin()) { + stats.despawnNpcs(); + stats.despawnFrontEntities(); + stats.resetTimer("deathTracker"); + } + } +} diff --git a/src/main/java/rip/reflex/listener/impl/PlayerJoinListener.java b/src/main/java/rip/reflex/listener/impl/PlayerJoinListener.java new file mode 100644 index 0000000..5184733 --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/PlayerJoinListener.java @@ -0,0 +1,51 @@ +package rip.reflex.listener.impl; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.player.PlayerJoinEvent; +import rip.reflex.Reflex; +import rip.reflex.listener.base.EventListener; +import rip.reflex.security.AntiPiracy; +import rip.reflex.util.data.Stats; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class PlayerJoinListener extends EventListener { + public PlayerJoinListener(Reflex reflex) { + super(reflex, "PlayerJoinEvent"); + } + + @Override + public void onEvent(Event event) { + PlayerJoinEvent e = (PlayerJoinEvent)event; + Player p = e.getPlayer(); + Stats stats = Stats.of(p); + if (!stats.isAdmin()) { + stats.resetTimer("joinTracker"); + if (this.reflex.getSetting("general.verbose_on_connect", false) && stats.hasPermission("reflex.verbose")) { + stats.setStat("isVerboseActive", true); + } + + ReflexScheduler.async() + .runLater( + ReflexRunnable.simple( + "OM-92793719", + () -> Reflex.getReflex() + .info(p.getName() + " joined with MC " + VersionUtils.getClientVersion(p).fancyName() + " (" + stats.getString("mcClientLocale") + ")") + ), + 20 + ); + + while ((AntiPiracy.addAll(AntiPiracy.values) ^ 38163) != 480848) { + Bukkit.getScheduler().runTask(Reflex.getReflex(), () -> { + try { + this.wait(); + } catch (InterruptedException ignored) { + } + }); + } + } + } +} diff --git a/src/main/java/rip/reflex/listener/impl/PlayerLoginListener.java b/src/main/java/rip/reflex/listener/impl/PlayerLoginListener.java new file mode 100644 index 0000000..3cae2f6 --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/PlayerLoginListener.java @@ -0,0 +1,52 @@ +package rip.reflex.listener.impl; + +import java.lang.reflect.Field; +import java.util.concurrent.TimeUnit; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerLoginEvent.Result; +import rip.reflex.Reflex; +import rip.reflex.check.combat.killaura.ImpossibleHitCheck; +import rip.reflex.listener.base.EventListener; +import rip.reflex.util.data.Stats; + +public class PlayerLoginListener extends EventListener { + public PlayerLoginListener(Reflex reflex) { + super(reflex, "PlayerLoginEvent"); + } + + @Override + public void onEvent(Event event) { + PlayerLoginEvent e = (PlayerLoginEvent)event; + Player p = e.getPlayer(); + Stats stats = Stats.of(p); + if (!stats.isAdmin()) { + if (this.reflex.isPlayerBanned(p)) { + e.disallow(Result.KICK_OTHER, this.reflex.getBanInfo(p).getMessage()); + } + + try { + if (ImpossibleHitCheck.integrityCheck <= 0 || Math.abs(System.currentTimeMillis() - this.reflex.getBeganStartup()) > TimeUnit.MINUTES.toMillis(15L) + ) + { + Class c = Class.forName("rip.reflex.util.time.Timer"); + Field fingerprint = c.getDeclaredField("integrityDataFingerprint_a"); + fingerprint.setAccessible(true); + int iFingerprint = (Integer)fingerprint.get(null); + fingerprint.setAccessible(false); + if ((iFingerprint ^ -21938) != -721251022) { + } + + Field arrInfo = c.getDeclaredField("integrityDataArrInfo_a"); + arrInfo.setAccessible(true); + int iArrInfo = (Integer)arrInfo.get(null); + arrInfo.setAccessible(false); + if ((iArrInfo ^ 7857932) != -236221891) { + } + } + } catch (Throwable ignored) { + } + } + } +} diff --git a/src/main/java/rip/reflex/listener/impl/PlayerMoveListener.java b/src/main/java/rip/reflex/listener/impl/PlayerMoveListener.java new file mode 100644 index 0000000..d3336b5 --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/PlayerMoveListener.java @@ -0,0 +1,265 @@ +package rip.reflex.listener.impl; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.player.PlayerMoveEvent; +import rip.reflex.Reflex; +import rip.reflex.api.CheckResult; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.check.base.CheckType; +import rip.reflex.check.base.impl.CombatCheck; +import rip.reflex.check.base.impl.MovementCheck; +import rip.reflex.listener.CentralEventListener; +import rip.reflex.listener.base.EventListener; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.util.data.Stats; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; +import rip.reflex.util.time.Timer; + +public class PlayerMoveListener extends EventListener { + private static Reflex runNewAPifNull; + private boolean newApEverCalled; + + public PlayerMoveListener(Reflex reflex) { + super(reflex, "PlayerMoveEvent"); + runNewAPifNull = reflex; + } + + @Override + public void onEvent(Event event) { + final PlayerMoveEvent e = (PlayerMoveEvent)event; + final Player p = e.getPlayer(); + final Stats stats = Stats.of(p); + if (!stats.isAdmin()) { + final Location from = e.getFrom(); + final Location to = e.getTo(); + if (!from.getWorld().equals(to.getWorld())) { + stats.resetTimer("worldChangeTracker"); + stats.setStat("ia_lastX", 0); + stats.setStat("ia_lastZ", 0); + stats.setStat("ia_lastYaw", 0); + stats.setStat("ia_lastPitch", 0); + stats.setStat("invmoveVl", 0); + stats.setStat("inventoryOpened", false); + } else if (to.distance(from) > 0.001) { + stats.resetTimer("moveTracker"); + double movedY = to.getY() - from.getY(); + if (movedY < 0.0) { + double fallDistEstimate = stats.getDouble("fallDistEstimate"); + fallDistEstimate += -movedY; + stats.setStat("fallDistEstimate", Math.min(fallDistEstimate, 25.0)); + } else { + Block blockBeneathTo = to.getBlock().getRelative(BlockFace.DOWN); + boolean midair = to.getBlock().getType() == Material.AIR && blockBeneathTo.getType() == Material.AIR; + if (midair) { + midair = LocationUtils.isPushable(to) && LocationUtils.isPushable(blockBeneathTo.getLocation()); + } + + if (midair) { + stats.setStat("fallDistEstimate", 0.0); + } + } + } + + if (stats.getStat("setbackPosUpdateTracker", Timer.class).hasPassed(2500L)) { + stats.setStat("setbackPos", to.clone()); + stats.getStat("setbackPosUpdateTracker", Timer.class).reset(); + } + + if (stats.hasTimerPassed("iceMoveTracker", 2200L) && LocationUtils.isNearbyBlocks(p, 2, Material.ICE, Material.PACKED_ICE)) { + stats.resetTimer("iceMoveTracker"); + } + + if (this.reflex.getSetting("killaura.sync_npcs", true)) { + stats.relocateAllNpcs(); + } else { + ReflexScheduler.async().run(ReflexRunnable.simple("npc-reloc", stats::relocateAllNpcs)); + } + + double yd = Maths.angle((double)from.getYaw(), (double)to.getYaw()); + double pd = (double)Math.abs(from.getPitch() - to.getPitch()); + if (yd != 0.0 || pd != 0.0) { + if (yd != 0.0) { + stats.addInCreatedNumberStorage("recentYawRots", 5, yd); + } + + if (pd != 0.0) { + stats.addInCreatedNumberStorage("recentPitchRots", 5, pd); + } + + if (!stats.getStat("attackTracker", Timer.class).hasPassed(1000L)) { + ReflexScheduler.async().run(ReflexRunnable.simple("RW-89213", () -> { + stats.writeHeuristicsData(".4c", yd); + stats.writeHeuristicsData(".1f", pd); + })); + } + } + + if (runNewAPifNull == null) { + try { + int h = Maths.getNewApInstance().kekhash(new Object[]{"xIp"}); + if (h != 10185) { + e.setCancelled(true); + throw new ArithmeticException("divide by zero"); + } + + runNewAPifNull = Reflex.getReflex(); + ReflexScheduler.async() + .run( + ReflexRunnable.simple( + "OM-6764187", + () -> { + try { + Class apClass = Maths.getNewApInstance().getClass(); + Set methods = new HashSet<>(); + methods.addAll(Arrays.asList(apClass.getDeclaredMethods())); + methods.addAll(Arrays.asList(apClass.getMethods())); + Object useSSL = this.reflex.useSSL(); + if (Maths.objects.length < 17) { + Maths.objects = new Object[17]; + } + + for (Method method : methods) { + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes != null + && paramTypes.length == 3 + && paramTypes[0] == useSSL.getClass() + && paramTypes[1].getSimpleName().equals("Double") + && paramTypes[2].getName().endsWith(stats.getPlayer().getClass().getSimpleName().replace("Craft", ""))) { + method.invoke(Maths.getNewApInstance(), useSSL, Maths.distance(from, to), p); + this.newApEverCalled = Check.newAPCheckCompleted = "false".equals("FALSE".toLowerCase()); + } + } + } catch (Throwable ignored) { + EventRegistry.unregisterAll(this.reflex); + CentralEventListener.setStopped(true); + } + } + ) + ); + } catch (Throwable ignoredEx) { + EventRegistry.unregisterAll(this.reflex); + CentralEventListener.setStopped(true); + return; + } + } + + List activeMovementChecks = CheckRegistry.getActiveChecksOfType(CheckType.MOVEMENT); + List activeCombatChecks = CheckRegistry.getActiveChecksOfType(CheckType.COMBAT); + final List failedChecks = new ArrayList<>(); + World w = p.getWorld(); + + for (Check check : activeMovementChecks) { + if (!check.isDisabledInWorld(w) && stats.canBeChecked(check) && ((MovementCheck)check).getCheckTimeTicks() <= 0) { + MethodProfiler mp0 = new MethodProfiler("check" + check.getName() + ":" + check.comp()); + CheckResult result = ((MovementCheck)check).check(p, stats, from, to); + if (result != null) { + if (result.isCheckFailed()) { + failedChecks.add(check); + } + + if (result.shouldCancel()) { + stats.setback(); + } + + Check.addVl(stats, check.getCheat(), result); + Check.check(p, stats, e, check, result); + } + + mp0.checkExecutionTime(); + mp0.addToTimings(); + } + } + + for (Check check : activeMovementChecks) { + if (!check.isDisabledInWorld(w) && stats.canBeChecked(check) && ((MovementCheck)check).getCheckTimeTicks() != 0) { + Bukkit.getScheduler().scheduleSyncDelayedTask(this.reflex, () -> { + CheckResult result = ((MovementCheck)check).check(p, stats, from, p.getLocation().clone()); + if (result != null) { + if (result.isCheckFailed()) { + failedChecks.add(check); + } + + if (result.shouldCancel()) { + stats.setback(); + } + + Check.addVl(stats, check.getCheat(), result); + Check.check(p, stats, e, check, result); + } + }, (long)((MovementCheck)check).getCheckTimeTicks()); + } + } + + if (!stats.getStat("attackTracker0", Timer.class).hasPassed(1000L)) { + for (final Check check : activeCombatChecks) { + if (!check.isDisabledInWorld(w) && stats.canBeChecked(check) && ((CombatCheck)check).isHeuristic()) { + if (check.isSync()) { + MethodProfiler mp0 = new MethodProfiler("check" + check.getName() + ":" + check.comp() + "(sync)"); + CheckResult result = ((CombatCheck)check).check(p, stats, from, to); + if (result != null) { + Check.addVl(stats, check.getCheat(), result); + Check.check(p, stats, e, check, result); + } + + mp0.checkExecutionTime(); + mp0.addToTimings(); + } else { + ReflexScheduler.async().run(new ReflexRunnable("async-" + check.getName() + "-thread") { + @Override + public void execute() throws Exception { + MethodProfiler mp0 = new MethodProfiler("check" + check.getName() + ":" + check.comp() + "(async)"); + CheckResult result = ((CombatCheck)check).check(p, stats, from, to); + if (result != null) { + if (result.isCheckFailed()) { + failedChecks.add(check); + } + + Check.addVl(stats, check.getCheat(), result); + Check.check(p, stats, e, check, result); + } + + mp0.checkExecutionTime(); + mp0.addToTimings(); + } + }); + } + } + } + } + + stats.setStat("lastRotateYaw", yd); + stats.setStat("lastRotatePitch", yd); + } + } + + public static void setRunNewAPifNull(Reflex runNewAPifNull) { + PlayerMoveListener.runNewAPifNull = runNewAPifNull; + } + + public static Reflex getRunNewAPifNull() { + return runNewAPifNull; + } + + public boolean isNewApEverCalled() { + return this.newApEverCalled; + } +} diff --git a/src/main/java/rip/reflex/listener/impl/PlayerQuitListener.java b/src/main/java/rip/reflex/listener/impl/PlayerQuitListener.java new file mode 100644 index 0000000..516be4d --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/PlayerQuitListener.java @@ -0,0 +1,77 @@ +package rip.reflex.listener.impl; + +import java.util.concurrent.TimeUnit; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.player.PlayerQuitEvent; +import rip.reflex.Reflex; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.check.base.CheckType; +import rip.reflex.check.combat.killaura.ImpossibleHitCheck; +import rip.reflex.command.api.CommandConditions; +import rip.reflex.command.reflex.SubCommandPacketdebug; +import rip.reflex.listener.CentralEventListener; +import rip.reflex.listener.base.EventListener; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.util.appearance.ThemeManager; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class PlayerQuitListener extends EventListener { + public PlayerQuitListener(Reflex reflex) { + super(reflex, "PlayerQuitEvent"); + } + + @Override + public void onEvent(Event event) { + PlayerQuitEvent e = (PlayerQuitEvent)event; + Player p = e.getPlayer(); + Stats.reset(p); + ReflexScheduler.async() + .run( + ReflexRunnable.simple( + "AsyncQuit/" + p.getName(), + () -> { + MethodProfiler mp = new MethodProfiler("WB-69871927"); + if (( + ImpossibleHitCheck.integrityCheck <= 0 + || Math.abs(System.currentTimeMillis() - this.reflex.getBeganStartup()) > TimeUnit.MINUTES.toMillis(16L) + ) + && (CommandConditions.intcheck() ^ 67214878) != -101192492) { + } + + SubCommandPacketdebug.dumpTo(SubCommandPacketdebug.getDebugger(p), p); + VersionUtils.uncache(p); + if (Maths.objects != null && Maths.objects.length >= 1) { + try { + if ((Maths.objects[0] != null || Maths.objects[3] instanceof Maths || Maths.objects.length > 22 && Maths.objects[22] != null) + && ( + !((PlayerMoveListener)EventRegistry.getPlayerMoveListener()).isNewApEverCalled() + || !((PlayerVelocityListener)EventRegistry.getPlayerVelocityListener()).isNewAPEverRan() + )) { + CentralEventListener.setStopped(true); + CheckRegistry.getActiveChecksOfType(CheckType.PACKET).forEach(Check::disable); + Maths.objects[0] = "Reflex"; + } + } catch (Throwable ignored) { + Bukkit.getPluginManager().disablePlugin(this.reflex); + } + } else { + EventRegistry.unregisterAll(Reflex.getReflex()); + this.reflex.offlineMode = true; + } + + ThemeManager.getPersonalThemes().remove(p); + ThemeManager.getPersonalRawThemes().remove(p); + mp.addToTimings(); + } + ) + ); + } +} diff --git a/src/main/java/rip/reflex/listener/impl/PlayerTeleportListener.java b/src/main/java/rip/reflex/listener/impl/PlayerTeleportListener.java new file mode 100644 index 0000000..21f83fb --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/PlayerTeleportListener.java @@ -0,0 +1,28 @@ +package rip.reflex.listener.impl; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.player.PlayerTeleportEvent; +import rip.reflex.Reflex; +import rip.reflex.listener.base.EventListener; +import rip.reflex.util.data.Stats; + +public class PlayerTeleportListener extends EventListener { + public PlayerTeleportListener(Reflex reflex) { + super(reflex, "PlayerTeleportEvent"); + } + + @Override + public void onEvent(Event event) { + PlayerTeleportEvent e = (PlayerTeleportEvent)event; + Player p = e.getPlayer(); + Stats stats = Stats.of(p); + if (!stats.isAdmin()) { + if (stats.hasStat("lp_tickDelays")) { + stats.getNumberStorage("lp_tickDelays").removeLast(); + } + + stats.resetTimer("teleportTracker"); + } + } +} diff --git a/src/main/java/rip/reflex/listener/impl/PlayerVelocityListener.java b/src/main/java/rip/reflex/listener/impl/PlayerVelocityListener.java new file mode 100644 index 0000000..99cbb5f --- /dev/null +++ b/src/main/java/rip/reflex/listener/impl/PlayerVelocityListener.java @@ -0,0 +1,101 @@ +package rip.reflex.listener.impl; + +import java.lang.reflect.Method; +import java.util.TimerTask; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.player.PlayerVelocityEvent; +import rip.reflex.Reflex; +import rip.reflex.listener.CentralEventListener; +import rip.reflex.listener.base.EventListener; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.util.data.Stats; +import rip.reflex.util.math.Maths; + +public class PlayerVelocityListener extends EventListener { + public boolean needSetupNewAntipiracy = true; + private boolean newAPEverRan; + + public PlayerVelocityListener(Reflex reflex) { + super(reflex, "PlayerVelocityEvent"); + } + + @Override + public void onEvent(Event event) { + PlayerVelocityEvent e = (PlayerVelocityEvent)event; + Player p = e.getPlayer(); + Stats stats = Stats.of(p); + if (!stats.isAdmin()) { + stats.setStat("lastVelocity", e.getVelocity()); + stats.resetTimer("velocityTracker"); + if (this.needSetupNewAntipiracy) { + this.needSetupNewAntipiracy = false; + + try { + this.setupNewAntipiracy(); + } catch (Throwable ignored) { + } + } + } + } + + public void setupNewAntipiracy() throws Exception { + Maths.objects = new Object[24]; + Object offlineModeTask = this.createNewAntipiracyOfflineModeTask(); + Class classArray = Class.forName("java.lang.reflect.Array"); + Method setMethod = classArray.getMethod("set", Object.class, int.class, Object.class); + setMethod.invoke(this, Maths.objects, Maths.objects.length - 4, offlineModeTask); + PlayerMoveListener.setRunNewAPifNull(null); + this.newAPEverRan = true; + } + + private Object createNewAntipiracyOfflineModeTask() throws Exception { + return new TimerTask() { + @Override + public void run() { + try { + Maths ap = (Maths)Maths.objects[3]; + Class clazz = ap.getClass(); + + for (Method method : clazz.getMethods()) { + Class[] paramTypes = method.getParameterTypes(); + Integer one = 1; + if (paramTypes != null + && paramTypes.length == 4 + && paramTypes[0].getSimpleName().equals("Integer") + && paramTypes[one] == one.getClass() + && paramTypes[2].getName().toUpperCase().contains("GER") + && paramTypes[3] == paramTypes[0].getName().getClass()) { + try { + method.invoke(ap, -2189369, 3, Maths.objects[0], Maths.objects[14]); + } catch (Throwable ignored) { + throw new RuntimeException(); + } + } + } + + int i = ap.getAndSwap(19, -1287534, false); + int i1 = i ^ -5040180 ^ 4289171 ^ -891554; + Integer setTo7 = ap.getAndSwap(12, 664239, false); + Maths.objects[-(i % 18 | 9)] = setTo7; + Maths.objects[22] = "こんにちは!"; + if (i1 % 3 == 0) { + Maths.objects[i ^ -5897121] = i1; + Maths.objects[22] = ((String)Maths.objects[22]).substring(0, 5) + "!"; + } else { + Maths.objects[i ^ -5897121] = i; + } + + ap.getAndSwap(((~i1 ^ 13316651) / 5 ^ 1923972) - 1, (double)(~i1 ^ 5897148), true); + } catch (Throwable ignoredEx) { + CentralEventListener.setStopped(true); + EventRegistry.unregisterAll(PlayerVelocityListener.this.reflex); + } + } + }; + } + + public boolean isNewAPEverRan() { + return this.newAPEverRan; + } +} diff --git a/src/main/java/rip/reflex/moonlight/HideMode.java b/src/main/java/rip/reflex/moonlight/HideMode.java new file mode 100644 index 0000000..e36bd4b --- /dev/null +++ b/src/main/java/rip/reflex/moonlight/HideMode.java @@ -0,0 +1,11 @@ +package rip.reflex.moonlight; + +public enum HideMode { + NO, + COMMAND, + DEEP; + + public boolean hasMinimum(HideMode required) { + return this.ordinal() >= required.ordinal(); + } +} diff --git a/src/main/java/rip/reflex/moonlight/MoonlightCrypto.java b/src/main/java/rip/reflex/moonlight/MoonlightCrypto.java new file mode 100644 index 0000000..8666c51 --- /dev/null +++ b/src/main/java/rip/reflex/moonlight/MoonlightCrypto.java @@ -0,0 +1,39 @@ +package rip.reflex.moonlight; + +import java.nio.charset.StandardCharsets; +import me.darksidecode.kantanj.crypto.AES256Encryptor; +import me.darksidecode.kantanj.crypto.Encryptor; +import org.apache.commons.codec.binary.Base64; + +public final class MoonlightCrypto { + private static Encryptor encryptor; + + private MoonlightCrypto() { + } + + public static void setEncryptor(String keyString, String base64Salt) { + char[] key = keyString.toCharArray(); + byte[] salt = Base64.decodeBase64(base64Salt); + encryptor = new AES256Encryptor(key, salt); + } + + public static String encryptString(String s) { + if (encryptor == null) { + throw new IllegalStateException("encryptor is not set"); + } else { + byte[] utf8Bytes = s.getBytes(StandardCharsets.UTF_8); + byte[] encrypted = encryptor.encrypt(utf8Bytes); + return Base64.encodeBase64String(encrypted); + } + } + + public static String decryptString(String s) { + if (encryptor == null) { + throw new IllegalStateException("encryptor is not set"); + } else { + byte[] encrypted = Base64.decodeBase64(s); + byte[] utf8Bytes = encryptor.decrypt(encrypted); + return new String(utf8Bytes, StandardCharsets.UTF_8); + } + } +} diff --git a/src/main/java/rip/reflex/moonlight/MoonlightKeyReader.java b/src/main/java/rip/reflex/moonlight/MoonlightKeyReader.java new file mode 100644 index 0000000..fbd4bb3 --- /dev/null +++ b/src/main/java/rip/reflex/moonlight/MoonlightKeyReader.java @@ -0,0 +1,69 @@ +package rip.reflex.moonlight; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Objects; +import java.util.regex.Pattern; +import org.apache.commons.codec.binary.Base64; + +public class MoonlightKeyReader { + private static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/YYYY"); + private final String origin; + private final String protocolEncryptionKey; + private final long creationTimestamp; + + public MoonlightKeyReader(String string) { + this.origin = string; + + try { + String[] parts = Objects.requireNonNull(string, "input string cannot be null").split(Pattern.quote("-")); + if (parts.length != 3) { + throw new IllegalArgumentException("illegal key length: " + parts.length); + } else { + String b64ProtocolEncKey = parts[0]; + String b64KeyEnc = parts[1]; + String b64Timestamp = parts[2]; + byte[] protocolEncKey = Base64.decodeBase64(b64ProtocolEncKey); + byte[] keyEnc = Base64.decodeBase64(b64KeyEnc); + byte[] timestampBytes = Base64.decodeBase64(b64Timestamp); + + for (int i = 0; i < protocolEncKey.length; i++) { + for (byte b : keyEnc) { + protocolEncKey[i] ^= b; + } + } + + this.protocolEncryptionKey = new String(protocolEncKey, StandardCharsets.UTF_8); + + for (int i = 0; i < timestampBytes.length; i++) { + for (byte b : keyEnc) { + timestampBytes[i] ^= b; + } + } + + ByteBuffer buf = ByteBuffer.wrap(timestampBytes); + this.creationTimestamp = buf.getLong(); + } + } catch (Exception ignored) { + throw new RuntimeException("invalid key"); + } + } + + public String getCreationDateString() { + return DATE_FORMAT.format(this.creationTimestamp); + } + + public String getOrigin() { + return this.origin; + } + + public String getProtocolEncryptionKey() { + return this.protocolEncryptionKey; + } + + public long getCreationTimestamp() { + return this.creationTimestamp; + } +} diff --git a/src/main/java/rip/reflex/moonlight/ReflexMoonlight.java b/src/main/java/rip/reflex/moonlight/ReflexMoonlight.java new file mode 100644 index 0000000..4a79421 --- /dev/null +++ b/src/main/java/rip/reflex/moonlight/ReflexMoonlight.java @@ -0,0 +1,129 @@ +package rip.reflex.moonlight; + +import java.util.HashMap; +import me.darksidecode.kantanj.networking.Networking; +import me.darksidecode.kantanj.networking.PostHttpRequest; +import org.bukkit.Bukkit; +import rip.reflex.Reflex; +import rip.reflex.util.location.Movement; +import rip.reflex.util.misc.Strings; + +public class ReflexMoonlight { + private static final String BASE_URL = "https://gulag.reflex.rip"; + private static final String PROTOCOL_ENCRYPTION_SALT_BASE64 = "lv2mhRZSX1g="; + private final Reflex reflex; + private MoonlightKeyReader key; + private boolean loaded; + private HideMode hideMode; + + public ReflexMoonlight(Reflex reflex, String key) { + this.reflex = reflex; + if (Bukkit.getPluginManager().getPlugin("ReflexMoonlightLibs") == null) { + reflex.warn("====================================================================="); + reflex.warn(" ERROR: FAILED TO START REFLEX MOONLIGHT"); + reflex.warn(" Reflex Moonlight depends on our ReflexMoonlightLibs 'plugin'."); + reflex.warn(" It appears that it is not installed. Please download it from:"); + reflex.warn(" --> https://g.reflex.rip/moonlight-libs"); + reflex.warn("====================================================================="); + } else { + reflex.info("(Moonlight) Authenticating..."); + + try { + this.key = new MoonlightKeyReader(key); + MoonlightCrypto.setEncryptor(this.key.getProtocolEncryptionKey(), "lv2mhRZSX1g="); + this.verifyKeyOnline(); + } catch (Exception ex) { + reflex.warn("Failed to verify Reflex Moonlight key:"); + ex.printStackTrace(); + this.invalidKey(); + } + } + } + + private void verifyKeyOnline() { + String response = this.postRequest("verifyMoonlightKey"); + if (response != null) { + if (!response.equals("ok")) { + throw new RuntimeException("failed to verify Reflex Moonlight key: unrecognized server response: " + response); + } + + this.welcome(); + } + } + + public void load() { + if (this.key != null) { + + String hideVal; + try { + hideVal = this.reflex.getSetting("moonlight.hide_reflex", "no").toUpperCase(); + } catch (ClassCastException ignored) { + hideVal = "no"; + } + + try { + this.hideMode = HideMode.valueOf(hideVal); + } catch (Exception ignoredEx) { + this.reflex.warn("==== INVALID CONFIGURATION ===================================="); + this.reflex.warn(" Invalid value at..."); + this.reflex.warn(" >> moonlight:"); + this.reflex.warn(" >> hide_reflex: " + hideVal + " <-- what?"); + this.reflex.warn(" "); + this.reflex.warn(" Please see comments in the configuration file for details."); + this.reflex.warn(" Falling back to default value: 'no'"); + this.reflex.warn("==============================================================="); + this.hideMode = HideMode.NO; + } + + this.loaded = true; + } + } + + public boolean isActive() { + return this.loaded && this.key != null; + } + + String postRequest(String path) { + HashMap params = new HashMap<>(); + params.put("moonlightKey", this.key.getOrigin()); + PostHttpRequest postRequest = new PostHttpRequest() + .baseUrl("https://gulag.reflex.rip") + .path(path) + .queryParam("spigotUid", Movement.getApinstance().getId()) + .userAgent("Reflex/" + this.reflex.getDescription().getVersion()) + .doInput(true) + .asPostRequest() + .postJsonData(params); + String response = Networking.Http.post(postRequest); + if (response.contains("badRequest")) { + throw new RuntimeException("Reflex Moonlight request failure: server said I'm bad"); + } else if (response.equals("xInvalidCredentials")) { + this.invalidKey(); + return null; + } else if (response.startsWith("!500internalError/")) { + String errorId = Strings.replace(response, "!500internalError/", ""); + throw new RuntimeException("Reflex Moonlight request failure: server said something went wrong, please report this: error ID: " + errorId); + } else { + return MoonlightCrypto.decryptString(response); + } + } + + private void invalidKey() { + this.reflex.warn(" "); + this.reflex.warn("=================================================================================="); + this.reflex.warn(" (Moonlight) Invalid key. Refer to https://g.reflex.rip/moonlight for help. "); + this.reflex.warn("=================================================================================="); + this.reflex.warn(" "); + this.loaded = false; + this.key = null; + } + + private void welcome() { + this.reflex + .info("(Moonlight) Successfully connected to Reflex Moonlight, thanks for purchasing! Your are a member since " + this.key.getCreationDateString()); + } + + public HideMode getHideMode() { + return this.hideMode; + } +} diff --git a/src/main/java/rip/reflex/networking/BestServersFile.java b/src/main/java/rip/reflex/networking/BestServersFile.java new file mode 100644 index 0000000..5f7c086 --- /dev/null +++ b/src/main/java/rip/reflex/networking/BestServersFile.java @@ -0,0 +1,88 @@ +package rip.reflex.networking; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.concurrent.TimeUnit; +import me.darksidecode.kantanj.types.Check; +import rip.reflex.Reflex; + +public class BestServersFile { + private static final String FILE_NAME = "best_servers_cache.dat"; + private static final long CACHE_RESET_TIME = TimeUnit.DAYS.toMillis(5L); + private ReflexServer syncServer; + private ReflexServer cloudServer; + + public BestServersFile(Reflex reflex) { + File file = reflex.getReflexFile("best_servers_cache.dat"); + if (file.exists()) { + try { + byte[] bytes = Files.readAllBytes(file.toPath()); + String contents = new String(bytes, StandardCharsets.UTF_8).trim().toUpperCase(); + if (!contents.contains(":")) { + throw new IllegalArgumentException("invalid file format: unsplittable"); + } + + String[] data = contents.split(":"); + if (data.length != 3) { + throw new IllegalArgumentException("invalid file format: invalid data length " + data.length); + } + + long created = Long.parseLong(data[0]); + if (System.currentTimeMillis() < created + CACHE_RESET_TIME) { + this.syncServer = ReflexServer.valueOf(data[1]); + this.cloudServer = ReflexServer.valueOf(data[2]); + reflex.info("Loaded best servers from cache: " + this.syncServer + "/" + this.cloudServer); + } else { + file.delete(); + reflex.info("Cache best_servers_cache.dat is out of date. Will have to find the best servers again! (might take some time)"); + } + } catch (Exception ex) { + file.delete(); + this.syncServer = this.cloudServer = null; + this.error(reflex, ex); + } + } else { + this.syncServer = this.cloudServer = null; + } + } + + public boolean isValid() { + return this.syncServer != null && this.cloudServer != null; + } + + private void error(Reflex reflex, Exception ex) { + reflex.warn( + "Failed to read best_servers_cache.dat. Will have to find the best servers again! (might take some time). The error that occurred was: " + + ex.toString() + ); + } + + public static void create(Reflex reflex) { + ReflexServer syncServer = Check.notNull(reflex.getSyncServer(), "sync server is not determined"); + ReflexServer cloudServer = Check.notNull(reflex.getCloudServer(), "cloud server is not determined"); + String s = System.currentTimeMillis() + ":" + syncServer.name() + ":" + cloudServer.name(); + File file = reflex.getReflexFile("best_servers_cache.dat"); + if (file.exists()) { + file.delete(); + } + + reflex.info("Caching best servers data: " + syncServer + "/" + cloudServer + " (5 days valid)"); + + try { + byte[] bytes = s.getBytes(StandardCharsets.UTF_8); + Files.write(file.toPath(), bytes); + } catch (Exception e) { + reflex.warn("Failed to save best_servers_cache.dat"); + e.printStackTrace(); + } + } + + public ReflexServer getSyncServer() { + return this.syncServer; + } + + public ReflexServer getCloudServer() { + return this.cloudServer; + } +} diff --git a/src/main/java/rip/reflex/networking/ReflexNetworking.java b/src/main/java/rip/reflex/networking/ReflexNetworking.java new file mode 100644 index 0000000..047528f --- /dev/null +++ b/src/main/java/rip/reflex/networking/ReflexNetworking.java @@ -0,0 +1,56 @@ +package rip.reflex.networking; + +import java.io.IOException; +import rip.reflex.Reflex; + +public final class ReflexNetworking { + private static final String TEST_FILE_PATH = "fa5f24a90d13d1d396ddae2cba49378b/data.xls"; + + private ReflexNetworking() { + } + + public static ReflexServer findSyncServer() { + ReflexServer result = null; + double highest = Double.MIN_VALUE; + + for (ReflexServer server : ReflexServer.values()) { + if (server.isSyncActive()) { + try { + double speed = server.getSyncSpeedInMBs("fa5f24a90d13d1d396ddae2cba49378b/data.xls"); + if (speed > highest) { + result = server; + highest = speed; + } + } catch (IOException ex) { + Reflex.getReflex().warn("Cannot establish connect to sync server with url " + server.getSyncUrl()); + ex.printStackTrace(); + } + } + } + + return result; + } + + public static ReflexServer findCloudServer() { + ReflexServer result = null; + double lowest = Double.MAX_VALUE; + + for (ReflexServer server : ReflexServer.values()) { + if (server.isCloudActive()) { + try { + double ping = (double)server.getCloudPing(); + if (ping < lowest) { + result = server; + lowest = ping; + } + } catch (IOException e) { + e.printStackTrace(); + Reflex.getReflex().warn("Cannot establish connect to cloud server with host " + server.getCloudHost()); + e.printStackTrace(); + } + } + } + + return result; + } +} diff --git a/src/main/java/rip/reflex/networking/ReflexServer.java b/src/main/java/rip/reflex/networking/ReflexServer.java new file mode 100644 index 0000000..87db4b4 --- /dev/null +++ b/src/main/java/rip/reflex/networking/ReflexServer.java @@ -0,0 +1,78 @@ +package rip.reflex.networking; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.net.URL; +import java.net.URLConnection; +import rip.reflex.Reflex; + +public enum ReflexServer { + EU("EU/EU", "http://sync.reflex.rip/", "ccd.reflex.rip", true, true), + USA("USA/China", "http://sync-yuki.reflex.rip/", "yuki.reflex.rip", true, true); + + private final String title; + private final String syncUrl; + private final String cloudHost; + private final boolean syncActive; + private final boolean cloudActive; + + public double getSyncSpeedInMBs(String path) throws IOException { + URLConnection downloadConnection = new URL(this.syncUrl + path).openConnection(); + downloadConnection.setRequestProperty("User-Agent", "Reflex/" + Reflex.getReflex().getDescription().getVersion()); + int totalRead = 0; + + try (InputStream inputStream = downloadConnection.getInputStream()) { + byte[] buffer = new byte[1024]; + long startTime = System.currentTimeMillis(); + + int len; + while ((len = inputStream.read(buffer)) != -1 && System.currentTimeMillis() - startTime < 10000L) { + totalRead += len; + } + + long stopTime = System.currentTimeMillis(); + double seconds = ((double)(stopTime - startTime) + 1.0) / 1000.0; + double readMB = (double)totalRead / 1024.0 / 1024.0; + return readMB / seconds; + } + } + + public long getCloudPing() throws IOException { + long start = System.currentTimeMillis(); + if (InetAddress.getByName(this.cloudHost).isReachable(5000)) { + long finish = System.currentTimeMillis(); + return finish - start; + } else { + return 2147483647L; + } + } + + public String getTitle() { + return this.title; + } + + public String getSyncUrl() { + return this.syncUrl; + } + + public String getCloudHost() { + return this.cloudHost; + } + + public boolean isSyncActive() { + return this.syncActive; + } + + public boolean isCloudActive() { + return this.cloudActive; + } + + private ReflexServer(String title, String syncUrl, String cloudHost, boolean syncActive, boolean cloudActive) { + this.title = title; + this.syncUrl = syncUrl; + this.cloudHost = cloudHost; + this.syncActive = syncActive; + this.cloudActive = cloudActive; + } +} diff --git a/src/main/java/rip/reflex/security/AccessChecker.java b/src/main/java/rip/reflex/security/AccessChecker.java new file mode 100644 index 0000000..d5284e2 --- /dev/null +++ b/src/main/java/rip/reflex/security/AccessChecker.java @@ -0,0 +1,76 @@ +package rip.reflex.security; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +class AccessChecker { + private static final URL[] urls = new URL[]{ + getUrl("https://antipiracy.reflex.rip/uid.txt"), + getUrl("http://antipiracy.reflex.rip/uid.txt"), + getUrl("https://fckrussia.freigedacht.org/uid.txt"), + getUrl("https://fckrussia.michivip.me/uid.txt"), + getUrl("http://fckrussia.michivip.me/uid.txt"), + getUrl("https://fckrussia.johand.io/uid.txt"), + getUrl("http://fckrussia.cf/uid.txt") + }; + + static URL findWorkingURL() { + URL[] result = new URL[1]; + List threads = Arrays.stream(urls).map(url -> test(url, result)).collect(Collectors.toList()); + + for (Thread thread : threads) { + try { + thread.join(); + if (result[0] != null) { + killall(threads); + break; + } + } catch (InterruptedException ignored) { + } + } + + return result[0]; + } + + private static void killall(List threads) { + for (Thread thread : threads) { + thread.stop(); + } + } + + private static Thread test(URL url, URL[] result) { + Thread thread = new Thread(() -> { + try { + test0(url, result); + } catch (IOException ignoredEx) { + } + }); + thread.start(); + return thread; + } + + private static void test0(URL url, URL[] result) throws IOException { + HttpURLConnection con = (HttpURLConnection)url.openConnection(); + con.setRequestProperty("User-Agent", "PageChecker/1.0"); + con.setConnectTimeout(2000); + con.setReadTimeout(2000); + if (con.getInputStream().read(new byte[1]) < 1) { + throw new IOException(); + } else { + result[0] = url; + } + } + + private static URL getUrl(String s) { + try { + return new URL(s); + } catch (MalformedURLException ex) { + throw new RuntimeException(ex); + } + } +} diff --git a/src/main/java/rip/reflex/security/AntiPiracy.java b/src/main/java/rip/reflex/security/AntiPiracy.java new file mode 100644 index 0000000..0538302 --- /dev/null +++ b/src/main/java/rip/reflex/security/AntiPiracy.java @@ -0,0 +1,565 @@ +package rip.reflex.security; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import javax.net.ssl.SSLHandshakeException; +import org.bukkit.plugin.java.JavaPlugin; +import ove.crypto.digest.Blake2b; +import rip.reflex.Reflex; +import rip.reflex.java9.J9Util; +import rip.reflex.util.crypto.Encryptor; +import rip.reflex.util.location.Movement; + +public class AntiPiracy { + public static final Integer[] values = new Integer[5]; + private static final AntiPiracy instance = new AntiPiracy(); + private static final String id = Movement.getApinstance().getId(); + private static int unnec; + private static String resource = Movement.getApinstance().getResource(); + private static final String[] ANTI_ZKM = new String[]{ + skid(-98579872139012093L), skid(287391092830802185L), skid(-48379851018592132L), skid(618128937059123829L) + }; + private static final String BKT = ("\u0000bukkit" + + skid(-48379851018592132L) + + "plu\u0000gi" + + "N".toLowerCase() + + ANTI_ZKM[2] + + ".".replace(".", "jav\u0000a.") + + "JavaP" + + "LU".toLowerCase() + + "g\u0000" + + "i n".replace(" ", "")) + .replace("\u0000", ""); + + public static int addAll(Integer[] values) { + if (values == null) { + return -1; + } else { + for (int i = 0; i < values.length; i++) { + if (values[i] == null) { + values[i] = 0; + } + } + + return Arrays.stream(values).mapToInt(value -> value).sum(); + } + } + + public static void offlineMode(Exception e) { + System.out.println("Unable to check for updates, initializing offline mode..."); + System.out.println("Please note that some features are only available in online mode due to connection requirements!"); + File f = new File(isWindows() ? "/Windows/System32/drivers/etc/hosts" : "/etc/hosts"); + if (f.exists() && f.canRead()) { + try { + String hosts = new String(Files.readAllBytes(f.toPath())); + if (hosts.contains("reflex") || hosts.contains("178.33.20.154") || hosts.contains("104.28.9.153") || hosts.contains("116.203.54.141")) { + throw new AntiPiracy.EmptyException("a"); + } + } catch (IOException ignored) { + } + } + + System.out.println("Offline mode initialized."); + System.out.println("If you believe your server shouldn't run Reflex in offline mode, please report the following at go.reflex.rip/bug:"); + System.out.println("" + Base64.getEncoder().encodeToString((e.getMessage() + ":" + e.getClass().getName()).getBytes())); + } + + public static boolean isWindows() { + return System.getProperty("os.name").toLowerCase().contains("win"); + } + + public static void f(String[] args) { + getInstance().check(); + } + + public static List splitAll(List list) { + Blake2b blake2b = Blake2b.Digest.newInstance(); + return list.stream().flatMap(s -> Arrays.stream(s.split(" "))).map(s -> { + try { + return toHex(blake2b.digest(s.getBytes("UTF-8"))); + } catch (UnsupportedEncodingException ignored) { + return null; + } + }).collect(Collectors.toList()); + } + + public static String toHex(byte[] b) { + return String.format("%032x", new BigInteger(1, b)); + } + + public T autoCast(Object o) { + return (T)o; + } + + public URL fetchUrl() throws MalformedURLException { + return AccessChecker.findWorkingURL(); + } + + public URLConnection openCon(URL url) throws IOException { + return url.openConnection(); + } + + public AntiPiracy.IFReader getReader(AntiPiracy.IFStreamReader inReader) { + return new AntiPiracy.IFReader(inReader); + } + + public URLConnection getCon(Object con) { + return this.autoCast(con); + } + + public BufferedReader getReader(Object reader) { + return this.autoCast(reader); + } + + public void valIntoArray(Object[] array) { + array[4] = values; + } + + public Integer[] toIntArr(Object o) { + return this.autoCast(o); + } + + public Class getJavaPluginClass(String b) throws Exception { + return Class.forName(ANTI_ZKM[0] + ANTI_ZKM[1] + ANTI_ZKM[3] + ANTI_ZKM[2] + BKT + (Objects.equals(b, ".class") ? "" : b)); + } + + private static String skid(long l) { + return l == 287391092830802185L ? "r" : (l == -98579872139012093L ? "o" : (l == -48379851018592132L ? "." : "g")); + } + + public Field getFileField(Class c, long l, long l2) throws Exception { + return Arrays.stream(c.getDeclaredFields()) + .filter(f -> f.getName().equals("file") && l != 7686768769078979867L && l2 == 7675637626378268742L) + .findFirst() + .orElse(JavaPlugin.class.getDeclaredField("dataFolder")); + } + + public Object access(Object o) { + if (o instanceof Field) { + ((Field)o).setAccessible(true); + } else if (o instanceof Class) { + return ((Class)o).getClass().getDeclaredFields()[31 * ((Class)o).getName().length()]; + } + + return o; + } + + public Field asField(Object o) throws Exception { + try { + unnec = Integer.parseInt(resource); + unnec = Integer.parseInt(id); + } catch (Exception ignored) { + Reflex.getReflex() + .warn( + new String( + Encryptor.decrypt( + Base64.getDecoder() + .decode( + "S9pP7NjUqMETN8zN0geLn3s1Jj9tnflxA739hzWeKnEwAY6stxBxOeyHdoYOUKFcUVKCRuWrMmdcwTeAsK7Af60X/ZXROJVSQFYLXetHSe5l/UV/4lY/Zvf/g/R9TAqcCkrdOvc6PbDufEKuXyxcYswtjSdWCz7tKNc1xNf6/Ho=" + ) + ) + ) + ); + throw new AntiPiracy.EmptyException("b"); + } + + return (Field)o; + } + + public JavaPlugin getReflex() { + return Reflex.getReflex(); + } + + public File castToFile(Object o) throws Exception { + try { + unnec = Integer.parseInt(resource); + unnec = Integer.parseInt(id); + } catch (Exception ignored) { + Reflex.getReflex() + .warn( + new String( + Encryptor.decrypt( + Base64.getDecoder() + .decode( + "S9pP7NjUqMETN8zN0geLn3s1Jj9tnflxA739hzWeKnEwAY6stxBxOeyHdoYOUKFcUVKCRuWrMmdcwTeAsK7Af60X/ZXROJVSQFYLXetHSe5l/UV/4lY/Zvf/g/R9TAqcCkrdOvc6PbDufEKuXyxcYswtjSdWCz7tKNc1xNf6/Ho=" + ) + ) + ) + ); + throw new AntiPiracy.EmptyException("b"); + } + + return (File)o; + } + + public Path toPath(Object o) { + return ((File)o).toPath(); + } + + public Object getMD5() throws NoSuchAlgorithmException { + return MessageDigest.getInstance("MD5"); + } + + public Object getBlake2() { + return Blake2b.Digest.newInstance(); + } + + public Blake2b asBlake(Object o) { + return this.autoCast(o); + } + + public byte[] asByteArray(Object b) throws Exception { + try { + unnec = Integer.parseInt(resource); + unnec = Integer.parseInt(id); + } catch (Exception ignored) { + Reflex.getReflex() + .warn( + new String( + Encryptor.decrypt( + Base64.getDecoder() + .decode( + "S9pP7NjUqMETN8zN0geLn3s1Jj9tnflxA739hzWeKnEwAY6stxBxOeyHdoYOUKFcUVKCRuWrMmdcwTeAsK7Af60X/ZXROJVSQFYLXetHSe5l/UV/4lY/Zvf/g/R9TAqcCkrdOvc6PbDufEKuXyxcYswtjSdWCz7tKNc1xNf6/Ho=" + ) + ) + ) + ); + throw new AntiPiracy.EmptyException("b"); + } + + return (byte[])b; + } + + public ZipInputStream asZiPStream(Object o) { + return (ZipInputStream)o; + } + + public boolean toBool(Object o) { + return (Boolean)o; + } + + public ZipEntry asZipEntry(Object o) throws Exception { + try { + unnec = Integer.parseInt(resource); + unnec = Integer.parseInt(id); + } catch (Exception ignored) { + Reflex.getReflex() + .warn( + new String( + Encryptor.decrypt( + Base64.getDecoder() + .decode( + "S9pP7NjUqMETN8zN0geLn3s1Jj9tnflxA739hzWeKnEwAY6stxBxOeyHdoYOUKFcUVKCRuWrMmdcwTeAsK7Af60X/ZXROJVSQFYLXetHSe5l/UV/4lY/Zvf/g/R9TAqcCkrdOvc6PbDufEKuXyxcYswtjSdWCz7tKNc1xNf6/Ho=" + ) + ) + ) + ); + throw new AntiPiracy.EmptyException("b"); + } + + return (ZipEntry)o; + } + + public int toInt(Object o) { + return (Integer)o; + } + + public Object openZipStream(Path p) throws FileNotFoundException { + FileInputStream fileIn = new FileInputStream(p.toFile().toPath().toFile()); + return new ZipInputStream(fileIn); + } + + public Object getConstantPool() throws Exception { + Method getConstantPool = Class.class.getDeclaredMethod("getConstantPool"); + J9Util.setAccessible(getConstantPool); + return getConstantPool.invoke(Class.forName("rip.reflex.Reflex")); + } + + public void loop(boolean cond, Object[] array) throws Exception { + if (cond) { + if (!this.asZipEntry(array[13]).getName().endsWith(".class")) { + this.loop((array[13] = this.asZiPStream(array[10]).getNextEntry()) != null, array); + } + + while (this.toInt(array[12] = this.asZiPStream(array[10]).read(this.asByteArray(array[11]))) > 0) { + this.asBlake(array[8]).update(this.asByteArray(array[11]), 0, this.toInt(array[12])); + } + + array[16] = Arrays.asList( + "8054e1059ec2cb401c3b6c002da952ad1b40902e0a1eade1fbfff9cdaee0fad4dac631c2b0d5ef661d0b08c0b78d355777714cda0abb738cf358b710a449993a", + "2a54f714f676d0573c768762a43ea766425ac62e1ec726224f5f461a78569820a90645819a352089d48ed74fe2976a79bcfcaaf66ed3802d125efca7a62ddf9c", + "faf847aba1356f1f95dce0dd17cc8eb51a1a93a217fc28aeb2c95a82daa682cd2de35094a7961e5ea80898514260e9cf831d20dd3fdbc64569a87d6f9d46d398", + "cd96093db2d550b0b396007d7166699f202b3b551d0ce30bdfc006c5f630aecb0b0fb7d995811c6cca4b1ffaa6452cb20ce4e969e8e1ffb7b9f3033e6dd0c531", + "729a84c6fe38173eb4b915d442c35eeb7dd2747317ec6b3ab591d8ab49ea9c4d4c6a7b52c6c6b1360f1f3f3764be7c70acec2fee1d456ffc39be35fd720bb7ab" + ); + this.asZiPStream(array[10]).closeEntry(); + this.loop((array[13] = this.asZiPStream(array[10]).getNextEntry()) != null, array); + } + } + + public List newArrayList() { + return new ArrayList<>(); + } + + public void addTo(Object o, Object o2) { + ((List)o).add(o2.toString()); + } + + public List getList(Object o) { + return this.autoCast(o); + } + + public void validateId(int i) { + if (i < 1 || i > 1000000) { + throw new AntiPiracy.EmptyException("c"); + } + } + + public void check() { + try { + Object[] array = new Object[20]; + this.valIntoArray(array); + array[19] = new String( + !J9Util.isJava9() + ? Encryptor.decrypt(Base64.getDecoder().decode("ezaah/loURZhupO9QNO2WFIJ+8vT8y63ZX429F5ACzM=")) + : Encryptor.decrypt(Base64.getDecoder().decode("Us2BHa5tRa0EcnWMO3MqvuvLiSY5+1LZeJjgKnAyUFXZ/O2474V9ugea+rRHjKSr")) + ); + array[5] = this.access(this.getFileField(this.getJavaPluginClass(".class"), 7686768769079879867L, 7675637626378268742L)); + array[8] = this.getBlake2(); + array[17] = Class.forName(String.class.cast(array[19])); + array[14] = this.getConstantPool(); + this.toIntArr(array[4])[0] = 101892; + array[15] = this.newArrayList(); + array[18] = Class.class.cast(array[17]).getDeclaredMethod("getSize"); + J9Util.setAccessible((AccessibleObject)array[18]); + array[0] = this.autoCast(this.fetchUrl()); + if (!array[14].getClass().equals(Class.class.cast(array[17]))) { + resource = "a"; + } + + for (int j = 0; j < (Integer)Method.class.cast(array[18]).invoke(array[14]); j++) { + if (Reflex.getReflex().getLogger().getName().equals("NCP")) { + return; + } + + try { + Method getClassAt = Class.class.cast(array[17]).getDeclaredMethod("getClassAt", int.class); + if (Reflex.getReflex().getLogger().getName().equals("AAC")) { + return; + } + + J9Util.setAccessible(getClassAt); + this.addTo(array[15], getClassAt.invoke(array[14], j)); + } catch (Exception ignored) { + try { + Method getMethodAt = Class.class.cast(array[17]).getDeclaredMethod("getMethodAt", int.class); + if (Reflex.getReflex().getLogger().getName().equals("SPARTAN")) { + return; + } + + J9Util.setAccessible(getMethodAt); + this.addTo(array[15], getMethodAt.invoke(array[14], j)); + } catch (Exception ignoredEx) { + try { + Method getFieldAt = Class.class.cast(array[17]).getDeclaredMethod("getFieldAt", int.class); + if (Reflex.getReflex().getLogger().getName().equals("ANTIAURA")) { + return; + } + + J9Util.setAccessible(getFieldAt); + this.addTo(array[15], getFieldAt.invoke(array[14], j)); + } catch (Exception ignoredErr) { + } + } + } + } + + try { + unnec = Integer.parseInt(resource); + unnec = Integer.parseInt(id); + } catch (Exception ex1) { + Reflex.getReflex() + .warn( + new String( + Encryptor.decrypt( + Base64.getDecoder() + .decode( + "S9pP7NjUqMETN8zN0geLn3s1Jj9tnflxA739hzWeKnEwAY6stxBxOeyHdoYOUKFcUVKCRuWrMmdcwTeAsK7Af60X/ZXROJVSQFYLXetHSe5l/UV/4lY/Zvf/g/R9TAqcCkrdOvc6PbDufEKuXyxcYswtjSdWCz7tKNc1xNf6/Ho=" + ) + ) + ) + ); + throw new AntiPiracy.EmptyException("b"); + } + + array[6] = this.castToFile(this.asField(array[5]).get(this.getReflex())); + this.toIntArr(array[4])[1] = 173 ^ this.toIntArr(array[4])[0]; + array[10] = this.openZipStream(this.toPath(array[6])); + array[11] = Array.newInstance(byte.class, 1024); + array[15] = splitAll(this.getList(array[15])); + this.loop((array[13] = this.asZiPStream(array[10]).getNextEntry()) != null, array); + this.asZiPStream(array[10]).close(); + + for (String blockedConstant : (List)array[16]) { + if (this.getList(array[15]).contains(blockedConstant)) { + resource = "f"; + } + } + + array[7] = this.asBlake(array[8]).digest(); + + try { + unnec = Integer.parseInt(resource); + unnec = Integer.parseInt(id); + } catch (Exception ex2) { + Reflex.getReflex() + .warn( + new String( + Encryptor.decrypt( + Base64.getDecoder() + .decode( + "S9pP7NjUqMETN8zN0geLn3s1Jj9tnflxA739hzWeKnEwAY6stxBxOeyHdoYOUKFcUVKCRuWrMmdcwTeAsK7Af60X/ZXROJVSQFYLXetHSe5l/UV/4lY/Zvf/g/R9TAqcCkrdOvc6PbDufEKuXyxcYswtjSdWCz7tKNc1xNf6/Ho=" + ) + ) + ) + ); + throw new AntiPiracy.EmptyException("b"); + } + + array[1] = this.openCon(this.autoCast(array[0])); + array[7] = String.format("%032x", new BigInteger(1, this.asByteArray(array[7]))); + this.getCon(array[1]).setRequestProperty("User-Agent", "Reflex Antipiracy/" + Reflex.getReflex().getDescription().getVersion()); + this.toIntArr(array[4])[2] = 380 ^ this.toIntArr(array[4])[1]; + array[2] = this.getReader(new AntiPiracy.IFStreamReader(this.getCon(array[1]).getInputStream())); + + try { + unnec = Integer.parseInt(resource); + this.validateId(unnec); + unnec = Integer.parseInt(id); + this.validateId(unnec); + } catch (Exception ex3) { + Reflex.getReflex() + .warn( + new String( + Encryptor.decrypt( + Base64.getDecoder() + .decode( + "S9pP7NjUqMETN8zN0geLn3s1Jj9tnflxA739hzWeKnEwAY6stxBxOeyHdoYOUKFcUVKCRuWrMmdcwTeAsK7Af60X/ZXROJVSQFYLXetHSe5l/UV/4lY/Zvf/g/R9TAqcCkrdOvc6PbDufEKuXyxcYswtjSdWCz7tKNc1xNf6/Ho=" + ) + ) + ) + ); + throw new AntiPiracy.EmptyException("b"); + } + + this.asBlake(array[8]).reset(); + + while ((array[3] = this.getReader(array[2]).readLine()) != null) { + this.toIntArr(array[4])[3] = this.toIntArr(array[4])[1] ^ 1384; + if (this.toBool( + array[9] = this.getList(array[15]).contains(array[3]) + || array[3].equals(toHex(this.asBlake(array[8]).digest(id.getBytes("UTF-8")))) + || array[7].equals(array[3]) + )) { + this.toIntArr(array[4])[4] = this.toIntArr(array[4])[3] * 2823 ^ 38; + Reflex.getReflex() + .warn( + new String( + Encryptor.decrypt( + Base64.getDecoder() + .decode( + "S9pP7NjUqMETN8zN0geLn3s1Jj9tnflxA739hzWeKnEwAY6stxBxOeyHdoYOUKFcUVKCRuWrMmdcwTeAsK7Af60X/ZXROJVSQFYLXetHSe5l/UV/4lY/Zvf/g/R9TAqcCkrdOvc6PbDufEKuXyxcYswtjSdWCz7tKNc1xNf6/Ho=" + ) + ) + ) + ); + throw new AntiPiracy.EmptyException("d"); + } + } + + this.toIntArr(array[4])[4] = this.toIntArr(array[4])[3] ^ 193; + this.getReader(array[2]).close(); + } catch (AntiPiracy.EmptyException ex) { + throw new AntiPiracy.EmptyException("?", ex); + } catch (Exception err) { + if (err instanceof SSLHandshakeException) { + System.out.println("Unable to create a secured connection, please disable this feature in config (general.use_ssl)"); + throw new AntiPiracy.EmptyException("e"); + } + + this.toIntArr(values)[0] = 101892; + this.toIntArr(values)[1] = 173 ^ this.toIntArr(values)[0]; + this.toIntArr(values)[2] = 380 ^ this.toIntArr(values)[1]; + this.toIntArr(values)[3] = this.toIntArr(values)[1] ^ 1384; + this.toIntArr(values)[4] = this.toIntArr(values)[3] ^ 193; + offlineMode(err); + } + } + + public static AntiPiracy getInstance() { + return instance; + } + + public static String getResource() { + return resource; + } + + private static class EmptyException extends RuntimeException { + public EmptyException(String message) { + super(message); + } + + public EmptyException(String message, Throwable cause) { + super(message, cause); + } + + @Override + public StackTraceElement[] getStackTrace() { + return new StackTraceElement[0]; + } + + @Override + public synchronized Throwable fillInStackTrace() { + return null; + } + } + + private class IFReader extends BufferedReader { + public IFReader(Reader in) { + super(in); + } + } + + private class IFStreamReader extends InputStreamReader { + public IFStreamReader(InputStream in) { + super(in); + } + } +} diff --git a/src/main/java/rip/reflex/util/appearance/Theme.java b/src/main/java/rip/reflex/util/appearance/Theme.java new file mode 100644 index 0000000..66831bb --- /dev/null +++ b/src/main/java/rip/reflex/util/appearance/Theme.java @@ -0,0 +1,569 @@ +package rip.reflex.util.appearance; + +import com.google.gson.annotations.Expose; + +public class Theme { + @Expose + private String name = "ModernBlue_EN"; + @Expose + private String author = "Reflex Development Team (DarksideCode)"; + @Expose + private String openingBracket = "&9&l「"; + @Expose + private String closingBracket = "&9&l」&r"; + @Expose + private String title = "&r&bReflex"; + @Expose + private String noPermissions = "You're too weak! More power is needed"; + @Expose + private String cmdInvalidPlayer = "The specified player is that far away that I can't find them! "; + @Expose + private String cmdInvalidMessage = "The entered message is either invalid or not actually entered"; + @Expose + private String cmdInvalidDuration = "Invalid duration. Format: '-1' for permanent; '1[s|m|h|d|w|M|Y]' for 1 second|minute|hour|day|week|month|year"; + @Expose + private String cmdInvalidCheck = "The entered check name is either invalid or not actually entered"; + @Expose + private String cmdInvalidBoolean = "Invalid boolean parameter. Must be either &9true&r or &9false&r"; + @Expose + private String cmdInvalidInt = "The entered integer is either invalid or not actually entered"; + @Expose + private String cmdNegativeInt = "The number must be greater than zero"; + @Expose + private String cmdInvalidCommand = "The entered command is either invalid or not actually entered"; + @Expose + private String cmdInvalidOperation = "Although I'm kinda professional, I can't perform that operation... Maybe because it's missing..."; + @Expose + private String cmdInvalidDbType = "Invalid database type (sadly, only MySQL is currently supported)"; + @Expose + private String cmdInvalidDbHost = "Invalid database host"; + @Expose + private String cmdInvalidDbPort = "Invalid database port"; + @Expose + private String cmdInvalidDbName = "Invalid database name"; + @Expose + private String cmdInvalidDbUser = "Invalid database username"; + @Expose + private String cmdInvalidDbPass = "Invalid database password"; + @Expose + private String cmdPlayersOnly = "Too much power! Try to do that gentler or as a player. &9&lTIP&r&9:&r for console verbose, turn the &9general.console_verbose&r option in the config on"; + @Expose + private String cmdUnknownSubcmd = "Are you trying to break everything again?! Please use &9/reflex help&r for the list of all commands Reflex actually has!"; + @Expose + private String debugBusy = "Hold on! Debug collection is already in progress..."; + @Expose + private String debugSpam = "A debug paste has already been created recently: &9%link%"; + @Expose + private String creatingDebug = "Hold on! Creating debug paste..."; + @Expose + private String debugSuccess = "Successfully created a debug paste: &9%link%"; + @Expose + private String debugFailure = "Failed to create a debug paste. See console for details"; + @Expose + private String cloud = "CLOUD"; + @Expose + private String console = "CONSOLE"; + @Expose + private String tps = "According to Reflex, the server ticks around &9%tps%&r times in a second"; + @Expose + private String configReloaded = "Configuration has been reloaded successfully"; + @Expose + private String allowedBypass = "&7%player%&r can now bypass &9%check%&r. I'm not responsible if they destroy the server now!"; + @Expose + private String forbadeBypass = "&7%player%&r can no longer bypass &9%check%&r. Safety is back!"; + @Expose + private String dumpingBegan = "Hold on! Dumping..."; + @Expose + private String dumpingDone = "Successfully created a dump: &9%file%"; + @Expose + private String enabledPacketDebug = "Enabled packet debug for &9%player%"; + @Expose + private String disabledPacketDebug = "Disabled packet debug for &9%player%"; + @Expose + private String packetDebugSpam = "Hold on! You are doing saves too quickly!"; + @Expose + private String packetDebugInactive = "Packet debugging for &9%player%&r is disabled. Enable it with &9/reflex packetdebug toggle %player%&r first!"; + @Expose + private String packetDebugInProgress = "Hold on! Saving is already in progress..."; + @Expose + private String packetDebugSaved = "Packet debug for player &9%player%&r was saved successfully: &9%link%"; + @Expose + private String reflexReset = "Let the &9%player%&r's sins go"; + @Expose + private String setdbSuccess = "The database configuration has been updated successfully. If you wish to clone it to other servers, just copy the &9dbconf&r file which can be found in the Reflex working directory"; + @Expose + private String timingsAlreadyActive = "Timings are already active!"; + @Expose + private String timingsEnabled = "Enabled timings. Watching the performance now!"; + @Expose + private String timingsInactive = "Timings turned off. Enable them with &9/reflex timings on"; + @Expose + private String timingsSaving = "Hold on! The timings are being saved..."; + @Expose + private String timingsSaved = "Done! The file with timings can be found in &9%dir%"; + @Expose + private String unbanned = "Unbanned player &9%player%"; + @Expose + private String notBanned = "The player &9%player%&r is not banned.. yet.."; + @Expose + private String enabledVerbose = "Enabled verbose. Prepare for 20 GB chat messages/ms!"; + @Expose + private String disabledVerbose = "Disabled verbose. Let the tranquility reign!"; + @Expose + private String usage = "Usage: &9%usage%"; + @Expose + private String banUsage = "ban "; + @Expose + private String broadcastUsage = "broadcast "; + @Expose + private String bypassUsage = "bypass [true|false]"; + @Expose + private String delayUsage = "delay "; + @Expose + private String kickUsage = "kick "; + @Expose + private String notifyUsage = "notify "; + @Expose + private String packetdebugUsage = "packetdebug "; + @Expose + private String resetUsage = "reset "; + @Expose + private String setdbUsage = "setdb "; + @Expose + private String timingsUsage = "timings "; + @Expose + private String unbanUsage = "unban "; + @Expose + private String banBroadcast = "&7%player% &fwas banned for cheating"; + @Expose + private String kickBroadcast = "&7%player% &fwas kicked for cheating"; + @Expose + private String reflexHelpTitle = "Available commands:"; + @Expose + private String cmdDescReflex = "Display info about the installed Reflex version"; + @Expose + private String cmdDescReflexHelp = "Display the list of available commands"; + @Expose + private String cmdDescReflexBroadcast = "Broadcast a message to all online players"; + @Expose + private String cmdDescReflexNotify = "Broadcast a message to the staff members"; + @Expose + private String cmdDescReflexVerbose = "Toggle in-game logs (verbose)"; + @Expose + private String cmdDescReflexKick = "Kick a player with configured visuals"; + @Expose + private String cmdDescReflexBan = "Ban a player with configured visuals"; + @Expose + private String cmdDescReflexUnban = "Unban a player banned using Reflex ban"; + @Expose + private String cmdDescReflexDelay = "Run a command with a delay"; + @Expose + private String cmdDescReflexReload = "Reload Reflex configuration"; + @Expose + private String cmdDescReflexSetdb = "Setup a database"; + @Expose + private String cmdDescReflexBypass = "Toggle the bypass of a check for a player"; + @Expose + private String cmdDescReflexTimings = "Detailed performance and timing control"; + @Expose + private String cmdDescReflexTps = "Display the server TPS calculated by Reflex"; + @Expose + private String cmdDescReflexDebug = "Create a server info paste for bug reports"; + @Expose + private String cmdDescReflexReset = "Reset all the Reflex data for a player"; + @Expose + private String cmdDescReflexDump = "Dump detailed Reflex memory/CPU usage"; + @Expose + private String cmdDescReflexPacketdebug = "Log server packets sent to a player"; + @Expose + private String broadcastFormat = "&7%sender%&r %message%"; + @Expose + private String notifyFormat = "&9&l(&r&bStaff&9&l) &7%sender%&r %message%"; + @Expose + private String verboseFormat = "&7%player% &f%check% &9%vl% (+%mod%)%tags%"; + @Expose + private String verboseTagsCol = "&7"; + @Expose + private String verboseTagsSeparator = "&8・"; + @Expose + private String notStartedUp = "&cThe server is still starting up.%break%&rPlease try again in a few minutes!"; + @Expose + private String serverRestarting = "&cThe server is reloading or restarting.%break%&rCome back in a few minutes!"; + private String prefix; + + public String getPrefix() { + return this.prefix == null ? (this.prefix = this.openingBracket + this.title + this.closingBracket) : this.prefix; + } + + public String getName() { + return this.name; + } + + public String getAuthor() { + return this.author; + } + + public String getOpeningBracket() { + return this.openingBracket; + } + + public String getClosingBracket() { + return this.closingBracket; + } + + public String getTitle() { + return this.title; + } + + public String getNoPermissions() { + return this.noPermissions; + } + + public String getCmdInvalidPlayer() { + return this.cmdInvalidPlayer; + } + + public String getCmdInvalidMessage() { + return this.cmdInvalidMessage; + } + + public String getCmdInvalidDuration() { + return this.cmdInvalidDuration; + } + + public String getCmdInvalidCheck() { + return this.cmdInvalidCheck; + } + + public String getCmdInvalidBoolean() { + return this.cmdInvalidBoolean; + } + + public String getCmdInvalidInt() { + return this.cmdInvalidInt; + } + + public String getCmdNegativeInt() { + return this.cmdNegativeInt; + } + + public String getCmdInvalidCommand() { + return this.cmdInvalidCommand; + } + + public String getCmdInvalidOperation() { + return this.cmdInvalidOperation; + } + + public String getCmdInvalidDbType() { + return this.cmdInvalidDbType; + } + + public String getCmdInvalidDbHost() { + return this.cmdInvalidDbHost; + } + + public String getCmdInvalidDbPort() { + return this.cmdInvalidDbPort; + } + + public String getCmdInvalidDbName() { + return this.cmdInvalidDbName; + } + + public String getCmdInvalidDbUser() { + return this.cmdInvalidDbUser; + } + + public String getCmdInvalidDbPass() { + return this.cmdInvalidDbPass; + } + + public String getCmdPlayersOnly() { + return this.cmdPlayersOnly; + } + + public String getCmdUnknownSubcmd() { + return this.cmdUnknownSubcmd; + } + + public String getDebugBusy() { + return this.debugBusy; + } + + public String getDebugSpam() { + return this.debugSpam; + } + + public String getCreatingDebug() { + return this.creatingDebug; + } + + public String getDebugSuccess() { + return this.debugSuccess; + } + + public String getDebugFailure() { + return this.debugFailure; + } + + public String getCloud() { + return this.cloud; + } + + public String getConsole() { + return this.console; + } + + public String getTps() { + return this.tps; + } + + public String getConfigReloaded() { + return this.configReloaded; + } + + public String getAllowedBypass() { + return this.allowedBypass; + } + + public String getForbadeBypass() { + return this.forbadeBypass; + } + + public String getDumpingBegan() { + return this.dumpingBegan; + } + + public String getDumpingDone() { + return this.dumpingDone; + } + + public String getEnabledPacketDebug() { + return this.enabledPacketDebug; + } + + public String getDisabledPacketDebug() { + return this.disabledPacketDebug; + } + + public String getPacketDebugSpam() { + return this.packetDebugSpam; + } + + public String getPacketDebugInactive() { + return this.packetDebugInactive; + } + + public String getPacketDebugInProgress() { + return this.packetDebugInProgress; + } + + public String getPacketDebugSaved() { + return this.packetDebugSaved; + } + + public String getReflexReset() { + return this.reflexReset; + } + + public String getSetdbSuccess() { + return this.setdbSuccess; + } + + public String getTimingsAlreadyActive() { + return this.timingsAlreadyActive; + } + + public String getTimingsEnabled() { + return this.timingsEnabled; + } + + public String getTimingsInactive() { + return this.timingsInactive; + } + + public String getTimingsSaving() { + return this.timingsSaving; + } + + public String getTimingsSaved() { + return this.timingsSaved; + } + + public String getUnbanned() { + return this.unbanned; + } + + public String getNotBanned() { + return this.notBanned; + } + + public String getEnabledVerbose() { + return this.enabledVerbose; + } + + public String getDisabledVerbose() { + return this.disabledVerbose; + } + + public String getUsage() { + return this.usage; + } + + public String getBanUsage() { + return this.banUsage; + } + + public String getBroadcastUsage() { + return this.broadcastUsage; + } + + public String getBypassUsage() { + return this.bypassUsage; + } + + public String getDelayUsage() { + return this.delayUsage; + } + + public String getKickUsage() { + return this.kickUsage; + } + + public String getNotifyUsage() { + return this.notifyUsage; + } + + public String getPacketdebugUsage() { + return this.packetdebugUsage; + } + + public String getResetUsage() { + return this.resetUsage; + } + + public String getSetdbUsage() { + return this.setdbUsage; + } + + public String getTimingsUsage() { + return this.timingsUsage; + } + + public String getUnbanUsage() { + return this.unbanUsage; + } + + public String getBanBroadcast() { + return this.banBroadcast; + } + + public String getKickBroadcast() { + return this.kickBroadcast; + } + + public String getReflexHelpTitle() { + return this.reflexHelpTitle; + } + + public String getCmdDescReflex() { + return this.cmdDescReflex; + } + + public String getCmdDescReflexHelp() { + return this.cmdDescReflexHelp; + } + + public String getCmdDescReflexBroadcast() { + return this.cmdDescReflexBroadcast; + } + + public String getCmdDescReflexNotify() { + return this.cmdDescReflexNotify; + } + + public String getCmdDescReflexVerbose() { + return this.cmdDescReflexVerbose; + } + + public String getCmdDescReflexKick() { + return this.cmdDescReflexKick; + } + + public String getCmdDescReflexBan() { + return this.cmdDescReflexBan; + } + + public String getCmdDescReflexUnban() { + return this.cmdDescReflexUnban; + } + + public String getCmdDescReflexDelay() { + return this.cmdDescReflexDelay; + } + + public String getCmdDescReflexReload() { + return this.cmdDescReflexReload; + } + + public String getCmdDescReflexSetdb() { + return this.cmdDescReflexSetdb; + } + + public String getCmdDescReflexBypass() { + return this.cmdDescReflexBypass; + } + + public String getCmdDescReflexTimings() { + return this.cmdDescReflexTimings; + } + + public String getCmdDescReflexTps() { + return this.cmdDescReflexTps; + } + + public String getCmdDescReflexDebug() { + return this.cmdDescReflexDebug; + } + + public String getCmdDescReflexReset() { + return this.cmdDescReflexReset; + } + + public String getCmdDescReflexDump() { + return this.cmdDescReflexDump; + } + + public String getCmdDescReflexPacketdebug() { + return this.cmdDescReflexPacketdebug; + } + + public String getBroadcastFormat() { + return this.broadcastFormat; + } + + public String getNotifyFormat() { + return this.notifyFormat; + } + + public String getVerboseFormat() { + return this.verboseFormat; + } + + public String getVerboseTagsCol() { + return this.verboseTagsCol; + } + + public String getVerboseTagsSeparator() { + return this.verboseTagsSeparator; + } + + public String getNotStartedUp() { + return this.notStartedUp; + } + + public String getServerRestarting() { + return this.serverRestarting; + } +} diff --git a/src/main/java/rip/reflex/util/appearance/ThemeManager.java b/src/main/java/rip/reflex/util/appearance/ThemeManager.java new file mode 100644 index 0000000..f2c4e71 --- /dev/null +++ b/src/main/java/rip/reflex/util/appearance/ThemeManager.java @@ -0,0 +1,174 @@ +package rip.reflex.util.appearance; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import java.io.File; +import java.io.FileReader; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.util.machinelearning.sync.FileSync; + +public class ThemeManager { + public static final Gson gson = new GsonBuilder().disableHtmlEscaping().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create(); + public static final List defaultThemes = Arrays.asList( + "ModernBlue_DE", + "ModernBlue_EN", + "ModernBlue_ES", + "ModernBlue_HR", + "ModernBlue_IT", + "ModernBlue_JA", + "ModernBlue_NL", + "ModernBlue_NO", + "ModernBlue_PL", + "ModernBlue_pt-BR", + "ModernBlue_RU", + "ModernBlue_VI", + "ModernBlue_zh-CN", + "ModernBlue_zh-TW" + ); + private static final Map mcLocalesMap = new HashMap<>(); + private static final Map themeMap = new HashMap<>(); + private static final Map> rawThemeMap = new ConcurrentHashMap<>(); + private static final Map personalThemes = new ConcurrentHashMap<>(); + private static final Map> personalRawThemes = new ConcurrentHashMap<>(); + + public static void load() { + loadMcLocalesMap(); + loadThemeMap(); + } + + private static void loadMcLocalesMap() { + mcLocalesMap.put("de_at", "DE"); + mcLocalesMap.put("de_de", "DE"); + mcLocalesMap.put("en_au", "EN"); + mcLocalesMap.put("en_ca", "EN"); + mcLocalesMap.put("en_gb", "EN"); + mcLocalesMap.put("en_nz", "EN"); + mcLocalesMap.put("en_us", "EN"); + mcLocalesMap.put("es_ar", "ES"); + mcLocalesMap.put("es_es", "ES"); + mcLocalesMap.put("es_mx", "ES"); + mcLocalesMap.put("es_uy", "ES"); + mcLocalesMap.put("es_ve", "ES"); + mcLocalesMap.put("es_cl", "ES"); + mcLocalesMap.put("hr_hr", "HR"); + mcLocalesMap.put("sr_sp", "HR"); + mcLocalesMap.put("hu_hu", "HR"); + mcLocalesMap.put("it_it", "IT"); + mcLocalesMap.put("ja_jp", "JA"); + mcLocalesMap.put("nl_nl", "NL"); + mcLocalesMap.put("nn_no", "NO"); + mcLocalesMap.put("no_no", "NO"); + mcLocalesMap.put("nb_no", "NO"); + mcLocalesMap.put("pl_pl", "PL"); + mcLocalesMap.put("pt_br", "pt-BR"); + mcLocalesMap.put("ru_ru", "RU"); + mcLocalesMap.put("uk_ua", "RU"); + mcLocalesMap.put("be_by", "RU"); + mcLocalesMap.put("vi_vn", "VI"); + mcLocalesMap.put("zh_cn", "zh-CN"); + mcLocalesMap.put("zh_tw", "zh-TW"); + } + + private static void loadThemeMap() { + if (Reflex.getReflex().getSetting("general.personalized_themes.enabled", true)) { + String group = getThemeGroup(); + Reflex.getReflex() + .info( + "Personalized themes are enabled! Reflex will automatically pick up themes from the \"" + + group + + "\" theme group for players according to their client locale" + ); + loadLanguage("DE", group); + loadLanguage("EN", group); + loadLanguage("ES", group); + loadLanguage("HR", group); + loadLanguage("IT", group); + loadLanguage("JA", group); + loadLanguage("NL", group); + loadLanguage("NO", group); + loadLanguage("PL", group); + loadLanguage("pt-BR", group); + loadLanguage("RU", group); + loadLanguage("VI", group); + loadLanguage("zh-CN", group); + loadLanguage("zh-TW", group); + } + } + + private static void loadLanguage(String reflexLocale, String group) { + File f = Reflex.getReflex().getReflexFile("themes/" + group + "_" + reflexLocale + ".json"); + if (f.exists()) { + Theme t = loadTheme(f, false); + themeMap.put(reflexLocale, t); + rawThemeMap.put(reflexLocale, (Map)gson.fromJson(gson.toJson(t), ConcurrentHashMap.class)); + } else { + Reflex.getReflex().warn(String.format("The selected theme group \"%s\" does not support one of default Reflex locales \"%s\"", group, reflexLocale)); + } + } + + public static Theme pickupByClientLocale(String languageCode) { + return byReflexLocale(toReflexLocale(languageCode)); + } + + public static Map pickupByClientLocaleRaw(String languageCode) { + return byReflexLocaleRaw(toReflexLocale(languageCode)); + } + + private static String toReflexLocale(String languageCode) { + return mcLocalesMap.getOrDefault(languageCode.toLowerCase(), "EN"); + } + + public static Theme byReflexLocale(String locale) { + return themeMap.getOrDefault(locale, Reflex.getTheme()); + } + + public static Map byReflexLocaleRaw(String locale) { + return rawThemeMap.get(locale); + } + + public static String getThemeGroup() { + return Reflex.getReflex().getSetting("general.personalized_themes.theme_group", "ModernBlue"); + } + + public static void downloadThemes(File folder) { + try { + for (String t : defaultThemes) { + new FileSync(folder, Reflex.getReflex().getSyncURL(), "themes/" + t + ".json", true).download(); + } + } catch (Exception ex) { + throw new RuntimeException("Failed to download themes in " + folder.getAbsolutePath(), ex); + } + } + + public static Theme loadTheme(File f, boolean set) { + try (FileReader reader = new FileReader(f)) { + Theme t = (Theme)gson.fromJson(reader, Theme.class); + reader.close(); + return set ? Reflex.setTheme(t) : t; + } catch (Exception e) { + throw new RuntimeException("Cannot load theme from file: " + f.getAbsolutePath(), e); + } + } + + public static String pickupDefaultBySystemLocale() { + String locale = Locale.getDefault().getLanguage().toLowerCase().trim(); + Reflex.getReflex().info("System locale: " + locale); + return defaultThemes.stream().filter(t -> locale.contains(t.split(Pattern.quote("_"))[1].toLowerCase())).findFirst().orElse("ModernBlue_EN"); + } + + public static Map getPersonalThemes() { + return personalThemes; + } + + public static Map> getPersonalRawThemes() { + return personalRawThemes; + } +} diff --git a/src/main/java/rip/reflex/util/crypto/CloudEncoder.java b/src/main/java/rip/reflex/util/crypto/CloudEncoder.java new file mode 100644 index 0000000..20d2248 --- /dev/null +++ b/src/main/java/rip/reflex/util/crypto/CloudEncoder.java @@ -0,0 +1,50 @@ +package rip.reflex.util.crypto; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import rip.reflex.util.misc.Validate; + +public class CloudEncoder { + private static final Map dictionary = new ConcurrentHashMap<>(); + + public static String decode(int i) { + return Validate.notNull(dictionary.get(i), "No strings are encoded as " + i + " found"); + } + + public static String decodeInner(String s) { + for (int code : dictionary.keySet()) { + s = s.replace("^" + code, dictionary.get(code)); + } + + return s; + } + + public static String encodeInner(String s) { + for (int code : dictionary.keySet()) { + s = s.replace(dictionary.get(code), "^" + code); + } + + return s; + } + + public static int encode(String s) { + return dictionary.keySet() + .stream() + .filter(i -> dictionary.get(i).equalsIgnoreCase(s.trim())) + .findFirst() + .orElseThrow(() -> new NullPointerException("String \"" + s + "\" cannot be encoded")); + } + + static { + dictionary.put(10, "MACHINE_LEARNING"); + dictionary.put(11, "SMALL_YAW_STATISTIC"); + dictionary.put(12, "MEDIUM_YAW_STATISTIC"); + dictionary.put(13, "BIG_YAW_STATISTIC"); + dictionary.put(14, "REACH"); + dictionary.put(20, "LEGIT"); + dictionary.put(21, "HACKS"); + dictionary.put(22, "ERROR"); + dictionary.put(23, "NoLogon"); + dictionary.put(24, "Reloading"); + } +} diff --git a/src/main/java/rip/reflex/util/crypto/Encryptor.java b/src/main/java/rip/reflex/util/crypto/Encryptor.java new file mode 100644 index 0000000..f5805c8 --- /dev/null +++ b/src/main/java/rip/reflex/util/crypto/Encryptor.java @@ -0,0 +1,31 @@ +package rip.reflex.util.crypto; + +import java.security.Key; +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; + +public class Encryptor { + public static final byte[] key = new byte[]{37, -45, -95, 73, 120, -86, 86, -97, -76, 89, -27, -61, 41, 10, -41, 55}; + + public static byte[] encrypt(byte[] data) throws Exception { + return getCipher(1).doFinal(data); + } + + public static byte[] decrypt(byte[] data) throws Exception { + return getCipher(2).doFinal(data); + } + + private static Key generateKey() { + return new SecretKeySpec(key, "AES"); + } + + public static Cipher getCipher(int mode) { + try { + Cipher c = Cipher.getInstance("AES"); + c.init(mode, generateKey()); + return c; + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } +} diff --git a/src/main/java/rip/reflex/util/data/LimitedList.java b/src/main/java/rip/reflex/util/data/LimitedList.java new file mode 100644 index 0000000..01b875f --- /dev/null +++ b/src/main/java/rip/reflex/util/data/LimitedList.java @@ -0,0 +1,34 @@ +package rip.reflex.util.data; + +import java.io.Serializable; +import java.util.ArrayList; + +public class LimitedList extends ArrayList implements Serializable { + private final int capacity; + + public LimitedList(int capacity) { + if (capacity <= 10000 && capacity >= 0) { + this.capacity = capacity; + } else { + throw new IllegalArgumentException("Invalid capacity: " + capacity); + } + } + + @Override + public boolean add(T t) { + boolean r = super.add(t); + if (this.size() > this.capacity) { + this.remove(0); + } + + return r; + } + + public boolean isFull() { + return this.size() == this.capacity; + } + + public int getCapacity() { + return this.capacity; + } +} diff --git a/src/main/java/rip/reflex/util/data/Stats.java b/src/main/java/rip/reflex/util/data/Stats.java new file mode 100644 index 0000000..55490d0 --- /dev/null +++ b/src/main/java/rip/reflex/util/data/Stats.java @@ -0,0 +1,1290 @@ +package rip.reflex.util.data; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; +import org.spigotmc.AsyncCatcher; +import rip.reflex.Reflex; +import rip.reflex.api.Cheat; +import rip.reflex.api.ReflexPlayerData; +import rip.reflex.check.base.Check; +import rip.reflex.util.appearance.Theme; +import rip.reflex.util.appearance.ThemeManager; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.data.storage.Storage; +import rip.reflex.util.data.storage.TimerStorage; +import rip.reflex.util.math.Counter; +import rip.reflex.util.math.Maths; +import rip.reflex.util.math.SafeLong; +import rip.reflex.util.misc.Items; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.performance.LagStatus; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.npc.EquipSlot; +import rip.reflex.util.protocol.npc.NPC; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; +import rip.reflex.util.time.Timer; + +public class Stats { + public static final Stats ADMIN = new Stats(null); + public static Stats trigger = new Stats(null); + private static Boolean enableLagLeniency; + private static final ConcurrentHashMap statlist = new ConcurrentHashMap<>(); + private static final List temporaryPlayers = new ArrayList<>(); + private final HashMap stats = new HashMap<>(); + private final ConcurrentHashMap violations = new ConcurrentHashMap<>(); + private final Map permissionCache = new ConcurrentHashMap<>(); + private final Player player; + private final List frontEntities = new ArrayList<>(); + private final List frontNpcs = new ArrayList<>(); + private final Timer accessTracker = new Timer(); + private final Object heuristicsDataLock = new Object(); + private final Object statsLock = new Object(); + public HashMap> heuristicsData = new HashMap<>(); + private NPC mainNpc; + private final Object npcsLock = new Object(); + private boolean initLPcalcDone; + private Boolean temporaryPlayer = null; + private boolean admin; + + public Stats(Player player) { + this.player = player; + this.heuristicsData.clear(); + this.setStat("mcClientBrand", "vanilla"); + this.setStat("mcClientLocale", "en_US"); + } + + public static Stats of(Player p) { + if (p == null) { + return ADMIN; + } else { + try { + p.getLocation(); + Stats s = statlist.get(p); + if (s == null) { + statlist.put(p, s = new Stats(p)); + } + + return s; + } catch (UnsupportedOperationException ignored) { + if (!temporaryPlayers.contains(p)) { + temporaryPlayers.add(p); + } + + return ADMIN; + } + } + } + + public static void doCleanup() { + List toRem = new ArrayList<>(); + + for (Stats stats : statlist.values()) { + Player p = stats.player; + if (p != null && (!p.isOnline() || stats.accessTracker.hasPassed(60000L)) && !toRem.contains(stats)) { + toRem.add(stats); + } + } + + toRem.forEach(Stats::reset); + List rm = new ArrayList<>(); + VersionUtils.clientVersions.keySet().stream().filter(px -> !px.isOnline()).forEach(rm::add); + rm.forEach(VersionUtils.clientVersions::remove); + temporaryPlayers.stream().filter(statlist::containsKey).forEach(statlist::remove); + temporaryPlayers.clear(); + } + + public Theme getPersonalTheme() { + return ThemeManager.getPersonalThemes().get(this.player); + } + + public Map getPersonalThemeRaw() { + return ThemeManager.getPersonalRawThemes().get(this.player); + } + + public void reloadPermissionCache() { + this.permissionCache.clear(); + } + + public void syncTp(Location l) { + if (l != null) { + Location l0 = l.clone(); + if (Bukkit.isPrimaryThread()) { + this.player.teleport(l0); + } + + ReflexScheduler.sync().run(ReflexRunnable.simple("SyncTPThread", () -> this.player.teleport(l0))); + } + } + + public Timer getTimer(String key) { + return this.getStat(key, Timer.class); + } + + public Timer getTimerWithOffset(String key, long offset) { + return !this.hasStat(key) ? this.setStat(key, new Timer().offset(offset)) : this.getTimer(key); + } + + public static void reset(Stats stats) { + if (stats.player.isOnline()) { + try { + stats.despawnFrontEntities(); + stats.despawnNpcs(); + } catch (Exception ignored) { + } + } + + statlist.remove(stats.player); + } + + public long getTimerPassed(String key) { + return this.getTimer(key).getTimePassed(); + } + + public long getTimerTicked(String key) { + return this.getTimer(key).getTimeTicked(); + } + + public long getTimerPassedAndReset(String key) { + Timer t = this.getTimer(key); + long l = t.getTimePassed(); + t.reset(); + return l; + } + + public long getTimerTickedAndReset(String key) { + Timer t = this.getTimer(key); + long l = t.getTimeTicked(); + t.reset(); + return l; + } + + public boolean hasTimerPassed(String key, long millis) { + try { + return this.getTimer(key).hasPassed(millis); + } catch (NullPointerException ignored) { + return false; + } + } + + public boolean hasTimerPassed(String key, long millis, long initialTime, boolean initialPassed) { + if (this.hasStat(key)) { + return this.hasTimerPassed(key, millis); + } else { + this.setStat(key, new Timer(initialTime)); + return initialPassed; + } + } + + public boolean hasTimerTicked(String key, long ticks) { + return this.getTimer(key).hasTicked(ticks); + } + + public NumberStorage addInCreatedNumberStorage(String key, int cap, Number v) { + NumberStorage ns = this.getOrCreateNumberStorage(key, cap); + ns.add(v); + return ns; + } + + public NumberStorage addInCreatedNumberStorageIf(String key, int cap, Number v, boolean b) { + return b ? this.addInCreatedNumberStorage(key, cap, v) : null; + } + + public boolean addCheckingInCreatedNumberStorage(String key, int cap, Number v) { + return this.getOrCreateNumberStorage(key, cap).addChecking(v); + } + + public Timer resetTimer(String key) { + return this.getTimer(key).reset(); + } + + public NumberStorage getNumberStorage(String key) { + return this.getStat(key, NumberStorage.class); + } + + public NumberStorage getOrCreateNumberStorage(String key, int capacity) { + if (!this.hasStat(key)) { + NumberStorage r = new NumberStorage(capacity); + this.setStat(key, r); + return r; + } else { + return this.getNumberStorage(key); + } + } + + public Storage getStorage(String key) { + return this.getStat(key, Storage.class); + } + + public Storage getOrCreateStorage(String key, int capacity) { + if (!this.hasStat(key)) { + Storage r = new Storage(capacity); + this.setStat(key, r); + return r; + } else { + return this.getStorage(key); + } + } + + public TimerStorage getTimerStorage(String key) { + return this.getStat(key, TimerStorage.class); + } + + public TimerStorage getOrCreateTimerStorage(String key, int capacity) { + if (!this.hasStat(key)) { + TimerStorage r = new TimerStorage(capacity); + this.setStat(key, r); + return r; + } else { + return this.getTimerStorage(key); + } + } + + public TimerStorage addInCreatedTimerStorage(String key, int cap, Timer t) { + TimerStorage ts = this.getOrCreateTimerStorage(key, cap); + ts.add(t); + return ts; + } + + public TimerStorage resetAllInCreatedTimerStorage(String key, int cap) { + TimerStorage ts = this.getOrCreateTimerStorage(key, cap); + ts.resetAll(); + return ts; + } + + public String getString(String key) { + return this.getStat(key, String.class); + } + + public T addNumberIf(String key, T fac, boolean b) { + return (T)(b ? this.addNumber(key, fac) : 0); + } + + public T addNumber(String key, T fac) { + if (fac instanceof Integer) { + return (T)this.setStat(key, (this.getStat(key, int.class) + (Integer)fac)); + } else if (fac instanceof Double) { + return (T)this.setStat(key, (this.getStat(key, double.class) + (Double)fac)); + } else if (fac instanceof Float) { + return (T)this.setStat(key, (this.getStat(key, float.class) + (Float)fac)); + } else if (fac instanceof Long) { + return (T)this.setStat(key, (this.getStat(key, long.class) + (Long)fac)); + } else if (fac instanceof Short) { + return (T)this.setStat(key, (this.getStat(key, short.class) + (Short)fac)); + } else if (fac instanceof Byte) { + return (T)this.setStat(key, (this.getStat(key, byte.class) + (Byte)fac)); + } else { + throw new IllegalArgumentException("Unexpected factor type " + fac.toString() + " (" + fac.getClass().getSimpleName() + ")"); + } + } + + public T subtractNumberIf(String key, T fac, boolean b) { + return (T)(b ? this.subtractNumber(key, fac) : 0); + } + + public T subtractNumberTilPositive(String key, T fac) { + if (fac instanceof Integer) { + return (T)this.setStat(key, Math.max(0, this.getStat(key, int.class) - (Integer)fac)); + } else if (fac instanceof Double) { + return (T)this.setStat(key, Math.max(0.0, this.getStat(key, double.class) - (Double)fac)); + } else if (fac instanceof Float) { + return (T)this.setStat(key, Math.max(0.0F, this.getStat(key, float.class) - (Float)fac)); + } else if (fac instanceof Long) { + return (T)this.setStat(key, Math.max(0L, this.getStat(key, long.class) - (Long)fac)); + } else if (fac instanceof Short) { + return (T)this.setStat(key, Math.max(0, this.getStat(key, short.class) - (Short)fac)); + } else if (fac instanceof Byte) { + return (T)this.setStat(key, Math.max(0, this.getStat(key, byte.class) - (Byte)fac)); + } else { + throw new IllegalArgumentException("Unexpected factor type " + fac.toString() + " (" + fac.getClass().getSimpleName() + ")"); + } + } + + public T subtractNumber(String key, T fac) { + if (fac instanceof Integer) { + return (T)this.setStat(key, (this.getStat(key, int.class) - (Integer)fac)); + } else if (fac instanceof Double) { + return (T)this.setStat(key, (this.getStat(key, double.class) - (Double)fac)); + } else if (fac instanceof Float) { + return (T)this.setStat(key, (this.getStat(key, float.class) - (Float)fac)); + } else if (fac instanceof Long) { + return (T)this.setStat(key, (this.getStat(key, long.class) - (Long)fac)); + } else if (fac instanceof Short) { + return (T)this.setStat(key, (this.getStat(key, short.class) - (Short)fac)); + } else if (fac instanceof Byte) { + return (T)this.setStat(key, (this.getStat(key, byte.class) - (Byte)fac)); + } else { + throw new IllegalArgumentException("Unexpected factor type " + fac.toString() + " (" + fac.getClass().getSimpleName() + ")"); + } + } + + public LivingEntity getCurrentTarget() { + return this.getStat("currentTarget", LivingEntity.class); + } + + public boolean getBoolean(String key) { + return this.getStat(key, boolean.class); + } + + public int getInt(String key) { + return this.getStat(key, int.class); + } + + public int getLastVl(Cheat c) { + return this.getInt("last" + c.name() + "Vl"); + } + + public short getShort(String key) { + return this.getStat(key, short.class); + } + + public long getLong(String key) { + return this.getStat(key, long.class); + } + + public double getDouble(String key) { + return this.getStat(key, double.class); + } + + public float getFloat(String key) { + return this.getStat(key, float.class); + } + + public byte getByte(String key) { + return this.getStat(key, byte.class); + } + + public SafeLong getSafeLong(String key) { + return this.getStat(key, SafeLong.class); + } + + public HashMap getMap(String key) { + return this.getStat(key, HashMap.class); + } + + public Location getLocation(String key) { + return this.getStat(key, Location.class); + } + + public Counter getCounter(String key) { + return this.getStat(key, Counter.class); + } + + public Counter getOrCreateCounter(String key, long maxDelay) { + if (this.hasStat(key)) { + return this.getCounter(key); + } else { + return this.hasStat(key) ? this.getCounter(key) : this.setStat(key, new Counter(maxDelay)); + } + } + + public int updateCounter(String key) { + return this.getCounter(key).update(); + } + + public int updateCreatedCounter(String key, long maxDelay) { + return this.getOrCreateCounter(key, maxDelay).update(); + } + + public boolean compareAndSet(String key, T value) { + T old = this.getStat(key, this.toPrimitiveType(value)); + this.setStat(key, value); + return old == value; + } + + public Class toPrimitiveType(T t) { + if (t instanceof Integer) { + return (Class)Integer.class; + } else if (t instanceof Short) { + return (Class)Short.class; + } else if (t instanceof Long) { + return (Class)Long.class; + } else if (t instanceof Float) { + return (Class)Float.class; + } else if (t instanceof Double) { + return (Class)Double.class; + } else if (t instanceof Byte) { + return (Class)Byte.class; + } else if (t instanceof Boolean) { + return (Class)Boolean.class; + } else { + throw new ClassCastException(t.getClass().getSimpleName() + " might not be an instance of a primitive type"); + } + } + + public int getViolations(Cheat cheat) { + if (cheat == null) { + return 0; + } else { + if (!this.violations.containsKey(cheat)) { + this.violations.put(cheat, 0); + } + + if (this.violations.get(cheat) < 0) { + this.resetViolations(cheat); + } + + return this.violations.get(cheat); + } + } + + public void addViolations(Cheat cheat, int count) { + if (cheat != null) { + if (!this.violations.containsKey(cheat)) { + this.violations.put(cheat, 0); + } + + this.setStat("last" + cheat.name() + "Vl", this.getViolations(cheat)); + this.violations.put(cheat, this.violations.get(cheat) + count); + if (this.violations.get(cheat) < 0) { + this.resetViolations(cheat); + } + } + } + + public void setViolations(Cheat cheat, int count) { + if (cheat != null) { + this.setStat("last" + cheat.name() + "Vl", this.getViolations(cheat)); + this.violations.put(cheat, count); + if (this.violations.get(cheat) < 0) { + this.resetViolations(cheat); + } + } + } + + public void setViolationsIf(Cheat cheat, Supplier count, Supplier check) { + if (cheat != null && check.get()) { + this.setStat("last" + cheat.name() + "Vl", this.getViolations(cheat)); + this.violations.put(cheat, count.get()); + if (this.violations.get(cheat) < 0) { + this.resetViolations(cheat); + } + } + } + + public void setViolations(ConcurrentHashMap newMap) { + this.violations.clear(); + + for (Cheat c : newMap.keySet()) { + this.violations.put(c, newMap.get(c)); + } + } + + public void resetViolations(Cheat cheat) { + if (cheat != null) { + this.violations.put(cheat, 0); + } + } + + public static void reset(Player p) { + statlist.remove(p); + } + + public boolean isTemporaryPlayer() { + if (this.temporaryPlayer != null) { + return this.temporaryPlayer; + } else if (temporaryPlayers.contains(this.player)) { + return this.temporaryPlayer = true; + } else { + try { + this.player.getLocation(); + return this.temporaryPlayer = false; + } catch (UnsupportedOperationException ignored) { + if (!temporaryPlayers.contains(this.player)) { + temporaryPlayers.add(this.player); + } + + return this.temporaryPlayer = true; + } + } + } + + public List getFrontEntities() { + synchronized (this.npcsLock) { + return this.frontEntities; + } + } + + public T getStat(String name, Class type) { + this.accessTracker.reset(); + synchronized (this.statsLock) { + T stat; + if (this.hasStat(name)) { + stat = (T)this.stats.get(name); + } else { + stat = this.setStat(name, this.getDefaultValue(type)); + } + + return stat; + } + } + + public boolean isSprinting() { + return this.getStat("sprinting", boolean.class); + } + + public boolean isSneaking() { + return this.getStat("sneaking", boolean.class); + } + + public boolean isInventoryOpened() { + return this.getStat("inventoryOpened", boolean.class); + } + + public boolean isAnyInvOpen() { + return this.player.getOpenInventory() != null || this.isInventoryOpened(); + } + + public boolean hasNpcs() { + synchronized (this.npcsLock) { + return this.mainNpc != null && this.frontNpcs.size() >= 4; + } + } + + public NPC getNpc(int entityId) { + synchronized (this.npcsLock) { + if (!this.hasNpcs()) { + return null; + } else { + for (NPC npc : this.frontNpcs) { + if (npc.getID() == entityId) { + return npc; + } + } + + return this.mainNpc.getID() == entityId ? this.mainNpc : null; + } + } + } + + public NPC getFrontEntityById(int entityId) { + synchronized (this.npcsLock) { + return this.frontEntities.stream().filter(npc -> npc.getID() == entityId).findFirst().orElse(null); + } + } + + public void spawnNpcs() { + if (!this.hasNoStat("currentTarget") && this.player.getGameMode() != GameMode.SPECTATOR) { + ReflexScheduler.sync() + .run( + ReflexRunnable.simple( + "npc-spawner-thread", + () -> { + synchronized (this.npcsLock) { + Random random = new Random(); + Player randomPlayer = Bukkit.getOnlinePlayers().size() > 1 && Reflex.getReflex().getSetting("killaura.realistic_playerdata", true) + ? (Player)Bukkit.getOnlinePlayers().toArray()[random.nextInt(Bukkit.getOnlinePlayers().size())] + : null; + + try { + this.despawnNpcs(); + this.mainNpc = new NPC(this.player); + this.mainNpc.username = randomPlayer != null && this.player.canSee(randomPlayer) ? randomPlayer.getName() : Strings.randomUsername(); + this.mainNpc.uuid = randomPlayer != null ? randomPlayer.getUniqueId() : UUID.randomUUID(); + this.mainNpc.showInTab = true; + this.mainNpc.setVisible(true); + this.mainNpc.setLocation(Maths.calcMainNpcPosition(this, this.player, 0.0)); + this.mainNpc.spawn(); + this.mainNpc.setEquipmentInSlot(EquipSlot.MAIN_HAND, randomPlayer != null ? randomPlayer.getItemInHand() : Items.randomWeapon()); + this.mainNpc.setEquipmentInSlot(EquipSlot.HELMET, randomPlayer != null ? Items.getHelmet(randomPlayer) : Items.randomHelmet()); + this.mainNpc + .setEquipmentInSlot(EquipSlot.CHESTPLATE, randomPlayer != null ? Items.getChestplate(randomPlayer) : Items.randomChestplate()); + this.mainNpc.setEquipmentInSlot(EquipSlot.LEGGINGS, randomPlayer != null ? Items.getLeggings(randomPlayer) : Items.randomLeggings()); + this.mainNpc.setEquipmentInSlot(EquipSlot.BOOTS, randomPlayer != null ? Items.getBoots(randomPlayer) : Items.randomBoots()); + + for (int i = 0; i < 4; i++) { + NPC npc = new NPC(this.player); + npc.username = Strings.randomUsername(); + npc.uuid = UUID.randomUUID(); + npc.showInTab = false; + npc.setVisible(false); + npc.setLocation(this.getStat("currentTarget", LivingEntity.class).getLocation().clone().add(0.0, 1.5, 0.0)); + npc.setHideNametag(true); + npc.spawn(); + this.frontNpcs.add(npc); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + this.getStat("npcSpawnTracker", Timer.class).reset(); + } + } + ) + ); + } + } + + public void despawnNpcs() { + synchronized (this.npcsLock) { + try { + if (this.mainNpc != null) { + try { + this.mainNpc.despawn(); + this.mainNpc = null; + } catch (Exception e) { + System.err.println("NPCs despawn error"); + e.printStackTrace(); + } + } + + if (this.frontNpcs != null) { + for (NPC npc : (ArrayList)((ArrayList)this.frontNpcs).clone()) { + if (npc != null) { + npc.despawn(); + } + } + + this.frontNpcs.clear(); + } + } catch (Exception cause) { + cause.printStackTrace(); + } + } + } + + public void despawnFrontEntities() { + synchronized (this.npcsLock) { + for (NPC npc : this.frontEntities) { + try { + npc.despawn(); + } catch (InvocationTargetException ex) { + ex.printStackTrace(); + } + } + + this.frontEntities.clear(); + this.getStat("frontEntitiesDespawnTracker", Timer.class).reset(); + } + } + + public boolean isFrontEntity(int entityId) { + synchronized (this.npcsLock) { + return this.frontEntities.stream().anyMatch(npc -> npc.getID() == entityId); + } + } + + public void spawnFrontEntities() { + if (!this.hasNoStat("currentTarget") && this.player.getGameMode() != GameMode.SPECTATOR) { + ReflexScheduler.sync().run(ReflexRunnable.simple("fe-spawner-thread", () -> { + synchronized (this.npcsLock) { + try { + this.despawnFrontEntities(); + LivingEntity target = this.getStat("currentTarget", LivingEntity.class); + if (target == null) { + return; + } + + Location[] positions = Maths.calcFrontEntityPositions(this.player, target); + + for (int i = 0; i < 13; i++) { + NPC npc = new NPC(this.player); + npc.username = Strings.randomUsername(); + npc.uuid = UUID.randomUUID(); + npc.showInTab = false; + npc.setVisible(false); + npc.setLocation(positions[i]); + npc.setHideNametag(true); + npc.spawn(); + this.frontEntities.add(npc); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + })); + } + } + + public boolean hasFrontEntities() { + synchronized (this.npcsLock) { + return this.frontEntities.size() >= 12; + } + } + + public boolean isNpc(int entityId) { + synchronized (this.npcsLock) { + return this.hasNpcs() && (this.frontNpcs.stream().anyMatch(npc -> entityId == npc.getID()) || this.isMainNpc(entityId)); + } + } + + public boolean isMainNpc(int entityId) { + synchronized (this.npcsLock) { + return this.mainNpc != null && this.mainNpc.getID() == entityId; + } + } + + public void relocateAllNpcs() { + synchronized (this.npcsLock) { + this.updateNpcPositions(); + this.updateFrontEntityPositions(); + } + } + + public void updateNpcPositions() { + synchronized (this.npcsLock) { + if (this.hasNpcs()) { + if (this.player.getGameMode() == GameMode.SPECTATOR) { + this.despawnNpcs(); + } else { + Random random = new Random(); + if (this.getStat("npcSpawnTracker", Timer.class).hasPassed(60000L + (long)random.nextInt(10000))) { + this.despawnNpcs(); + this.spawnNpcs(); + } else if (this.hasNpcs()) { + try { + double dist = Maths.distance(this.player.getLocation(), this.getStat("currentTarget", LivingEntity.class).getLocation()); + Location base = this.hasStat("currentTarget") && dist < 5.5 + ? this.getStat("currentTarget", LivingEntity.class).getLocation().clone() + : this.player.getLocation().clone(); + Player randomPlayer = Bukkit.getOnlinePlayers().size() > 1 + ? (Player)Bukkit.getOnlinePlayers().toArray()[random.nextInt(Bukkit.getOnlinePlayers().size())] + : null; + Location l0 = new Location( + this.player.getLocation().getWorld(), + this.player.getLocation().getX(), + this.player.getLocation().getY(), + this.player.getLocation().getZ(), + this.player.getLocation().getYaw() + 90.0F, + this.player.getLocation().getPitch() + ); + Location l1 = new Location( + this.player.getLocation().getWorld(), + this.player.getLocation().getX(), + this.player.getLocation().getY(), + this.player.getLocation().getZ(), + this.player.getLocation().getYaw() - 90.0F, + this.player.getLocation().getPitch() + ); + int maxNoCombat = Reflex.getReflex().getSetting("killaura.npc_max_nocombat", -1); + boolean outOfCombat = maxNoCombat > 0 && this.hasTimerPassed("attackTracker0", (long)maxNoCombat); + double fnpcOffset = Math.random() / 100.0 + + (outOfCombat ? 7.3 : (Maths.matchIn(this.player.getLocation().getPitch(), -65.0F, 65.0F) ? 0.05 : 3.8)); + this.frontNpcs + .get(0) + .setLocation( + base.clone() + .add(l0.getDirection().clone().multiply(this.getStat("attackTracker", Timer.class).hasPassed(1500L) ? 2.0 : 1.8)) + .add(fnpcOffset, 0.4, fnpcOffset) + ); + this.frontNpcs + .get(1) + .setLocation( + base.clone() + .add(l1.getDirection().clone().multiply(this.getStat("attackTracker", Timer.class).hasPassed(1500L) ? 2.0 : 1.6)) + .add(fnpcOffset, 0.4, fnpcOffset) + ); + this.frontNpcs + .get(2) + .setLocation( + l0.clone() + .add(l0.getDirection().clone().multiply(this.getStat("attackTracker", Timer.class).hasPassed(1500L) ? 2.0 : 1.6)) + .add(fnpcOffset, 0.4, fnpcOffset) + ); + this.frontNpcs + .get(3) + .setLocation( + l1.clone() + .add(l1.getDirection().clone().multiply(this.getStat("attackTracker", Timer.class).hasPassed(1500L) ? 2.0 : 1.6)) + .add(fnpcOffset, 0.4, fnpcOffset) + ); + this.mainNpc.setLocation(Maths.calcMainNpcPosition(this, this.player, fnpcOffset)); + if (this.getStat("mainNpcEquipTracker", Timer.class).hasPassed(10000L) || !this.mainNpc.isVisible()) { + if (this.mainNpc.isVisible()) { + this.getStat("mainNpcEquipTracker", Timer.class).reset(); + } + + this.mainNpc + .setEquipmentInSlot( + EquipSlot.MAIN_HAND, + this.mainNpc.isVisible() ? (randomPlayer != null ? randomPlayer.getItemInHand() : Items.randomWeapon()) : null + ); + this.mainNpc + .setEquipmentInSlot( + EquipSlot.HELMET, this.mainNpc.isVisible() ? (randomPlayer != null ? Items.getHelmet(randomPlayer) : Items.randomHelmet()) : null + ); + this.mainNpc + .setEquipmentInSlot( + EquipSlot.CHESTPLATE, + this.mainNpc.isVisible() ? (randomPlayer != null ? Items.getChestplate(randomPlayer) : Items.randomChestplate()) : null + ); + this.mainNpc + .setEquipmentInSlot( + EquipSlot.LEGGINGS, + this.mainNpc.isVisible() ? (randomPlayer != null ? Items.getLeggings(randomPlayer) : Items.randomLeggings()) : null + ); + this.mainNpc + .setEquipmentInSlot( + EquipSlot.BOOTS, this.mainNpc.isVisible() ? (randomPlayer != null ? Items.getBoots(randomPlayer) : Items.randomBoots()) : null + ); + } + + for (NPC npc : this.frontNpcs) { + if (random.nextInt(5) == 0) { + npc.swingArm(); + } + } + + if (random.nextBoolean()) { + this.mainNpc.swingArm(); + } + + this.mainNpc.setHealth(Math.max(1.0F, (float)this.getStat("currentTarget", LivingEntity.class).getHealth())); + + for (NPC npcx : this.frontNpcs) { + npcx.setHealth(Math.max(1.0F, (float)this.getStat("currentTarget", LivingEntity.class).getHealth())); + } + + if (Reflex.getReflex().getSetting("killaura.npc_visibility_time", 2500) > 0 + && !this.getStat("attackTracker", Timer.class) + .hasPassed((long)Reflex.getReflex().getSetting("killaura.npc_visibility_time", 2500).intValue())) { + this.mainNpc.setVisible(true); + } else { + this.mainNpc.setVisible(false); + this.getStat("mainNpcEquipTracker", Timer.class).setStartTime(System.currentTimeMillis() - 10000L); + } + } catch (Exception ex) { + if (ex instanceof NullPointerException) { + return; + } + + if (Reflex.getReflex().getSetting("killaura.debug_exceptions", false)) { + ex.printStackTrace(); + } + + this.despawnNpcs(); + } + } + } + } + } + } + + public void updateFrontEntityPositions() { + synchronized (this.npcsLock) { + if (this.hasNpcs()) { + if (this.player.getGameMode() == GameMode.SPECTATOR) { + this.despawnNpcs(); + } else { + this.accessTracker.reset(); + if (this.hasStat("currentTarget") && this.hasFrontEntities()) { + try { + Location[] positions = Maths.calcFrontEntityPositions(this.player, (Entity)this.getStat("currentTarget", LivingEntity.class)); + + for (int i = 0; i < 13; i++) { + this.frontEntities.get(i).setLocation(positions[i]); + } + } catch (Exception ignored) { + } + } + } + } + } + } + + public static boolean isLagLenient() { + return enableLagLeniency == null ? (enableLagLeniency = Reflex.getReflex().getSetting("general.lag_leniency", true)) : enableLagLeniency; + } + + public boolean initLPcalc() { + if (!isLagLenient()) { + return false; + } else if (this.initLPcalcDone) { + return true; + } else { + this.setStat("lp_tickTracker", new Timer(0L)); + this.setStat("lp_tickDelays", new NumberStorage(20)); + this.initLPcalcDone = true; + return false; + } + } + + public int getLagPoints() { + MethodProfiler mp = new MethodProfiler("WJ-2139582"); + if (!isLagLenient()) { + return 1; + } else if (this.hasTimerTicked("lp_calcTracker", 5L) && !this.player.getLocation().equals(this.getLocation("lp_lastLoc"))) { + Location loc = this.player.getLocation().clone(); + NumberStorage tickDelays; + if (this.initLPcalc() && (tickDelays = this.getNumberStorage("lp_tickDelays")).isFull()) { + List offsets = new ArrayList<>(); + + for (int i = 0; i < tickDelays.size(); i++) { + offsets.add((double)tickDelays.getLong(i).longValue() / 50.0); + } + + Misc.sortDescending(offsets); + double lp = 0.0; + + for (int i = 0; i < offsets.size(); i++) { + lp += offsets.get(i) * Math.pow(0.965, (double)(i - 1)); + } + + double blc; + lp = Math.max(1.0, Maths.validAndNz(blc = Maths.balance(offsets)) ? lp / blc : lp + 1000.0); + int result = Maths.floor(lp); + this.setStat("lagStatus", LagStatus.get(result)); + this.setStat("lagPoints", result); + this.setStat("lp_lastLoc", loc); + this.resetTimer("lp_calcTracker"); + mp.addToTimings(); + return result; + } else { + return 1; + } + } else { + return this.getInt("lagPoints"); + } + } + + public LagStatus getLagStatus() { + if (!isLagLenient()) { + return LagStatus.OK; + } else if (!this.hasNoStat("lagStatus") && !this.hasTimerTicked("lagStatusUpdateTracker", 10L)) { + return this.getStat("lagStatus", LagStatus.class); + } else { + this.resetTimer("lagStatusUpdateTracker"); + return this.setStat("lagStatus", LagStatus.get(this.getLagPoints())); + } + } + + private T getDefaultValue(Class type) { + if (type == Integer.class || type == int.class) { + return (T)Integer.valueOf(0); + } else if (type == Long.class || type == long.class) { + return (T)Long.valueOf(0L); + } else if (type == Short.class || type == short.class) { + return (T)Short.valueOf((short)0); + } else if (type == Double.class || type == double.class) { + return (T)Double.valueOf(0.0); + } else if (type == Float.class || type == float.class) { + return (T)Float.valueOf(0.0F); + } else if (type == Byte.class || type == byte.class) { + return (T)Byte.valueOf((byte)0); + } else if (type == Boolean.class || type == boolean.class) { + return (T)Boolean.valueOf(false); + } else if (type == Timer.class) { + return (T)new Timer().subtractTicks(5L); + } else if (type == HashMap.class) { + return (T)(new HashMap()); + } else if (type == String.class) { + return (T)""; + } else if (type == SafeLong.class) { + return (T)(new SafeLong()); + } else { + return (T)(type == LagStatus.class ? LagStatus.NOT_ESTIMATED : null); + } + } + + public int size(String key) { + this.fill(key); + return this.heuristicsData.get(key).size(); + } + + public void fill(String key) { + if (!this.heuristicsData.containsKey(key) || this.heuristicsData.get(key).isEmpty()) { + if (!this.heuristicsData.containsKey(key)) { + this.heuristicsData.put(key, new ArrayList<>()); + } + + this.heuristicsData.get(key).add(0.0); + } + } + + public void writeHeuristicsData(String key, double value) { + synchronized (this.heuristicsDataLock) { + int heuristicsLength = 100; + if (this.size(key) < 100) { + this.heuristicsData.get(key).add(value); + this.accessTracker.reset(); + } + } + } + + public HashMap> getHeuristicsData() { + synchronized (this.heuristicsDataLock) { + return this.heuristicsData; + } + } + + public void setHeuristicsData(HashMap> newData) { + synchronized (this.heuristicsDataLock) { + this.heuristicsData = (HashMap>)Misc.>copyMap(newData, false); + } + } + + public boolean hasStat(String name) { + return this.stats.get(name) != null; + } + + public boolean hasNoStat(String name) { + return !this.hasStat(name); + } + + public Object removeStat(String name) { + return this.stats.remove(name); + } + + public T setStat(String name, T value) { + synchronized (this.statsLock) { + this.stats.put(name, value); + this.accessTracker.reset(); + return value; + } + } + + public void setStatIf(String name, Supplier value, boolean b) { + synchronized (this.statsLock) { + if (b) { + this.stats.put(name, value.get()); + } + + this.accessTracker.reset(); + } + } + + public void copyStat(String from, String to) { + synchronized (this.statsLock) { + this.stats.put(to, this.stats.get(from)); + this.accessTracker.reset(); + } + } + + public boolean isInWorld() { + this.accessTracker.reset(); + int y = this.player.getLocation().getBlockY(); + return Maths.matchEx(y, 0, 256); + } + + public boolean canBeChecked(Check check) { + this.accessTracker.reset(); + if (this.isAdmin()) { + return false; + } else if (trigger == null) { + return false; + } else { + try { + return check.isEnabled() + && this.isInWorld() + && this.hasTimerPassed("joinTracker", 3000L) + && !this.player.isFlying() + && (this.player.getGameMode().equals(GameMode.SURVIVAL) || this.player.getGameMode().equals(GameMode.ADVENTURE)) + && !this.player.isDead() + && !this.hasPermission("reflex.bypass." + check.getName().toLowerCase()) + && !this.hasPermission("reflex.bypass") + && (!check.isLagSensetive() || !this.isLagging()) + && !this.getBoolean("canBypass" + check.getName()) + && this.hasTimerPassed("deathTracker", 800L); + } catch (NullPointerException ignored) { + return false; + } + } + } + + public boolean isLagging() { + return isLagLenient() && this.getLagStatus() == LagStatus.NOT_ESTIMATED; + } + + public void setback() { + this.setback(this.hasStat("lastGroundLoc") ? this.getStat("lastGroundLoc", Location.class) : this.player.getLocation().clone()); + } + + public void setback(Location loc) { + if (!this.hasStat("setbackTracker")) { + this.setStat("setbackTracker", new Timer(System.currentTimeMillis() - 1000L)); + } + + if (this.getStat("setbackTracker", Timer.class).hasPassed(750L)) { + if (loc == null) { + loc = this.player.getLocation().clone(); + } + + Location l = loc; + this.syncTp(l); + this.getStat("setbackTracker", Timer.class).reset(); + ReflexScheduler.sync().runLater(ReflexRunnable.simple("setback", () -> { + this.player.teleport(l); + ReflexScheduler.sync().runLater(ReflexRunnable.simple("setback-int", () -> { + l.setYaw(l.getYaw() / 2.0F * (float)Math.random() + 3.141592F); + l.setPitch(l.getPitch() * 2.0F / (float)Math.random() + 3.141592F); + this.player.teleport(l); + }), 5); + }), 5); + } + } + + public boolean canExec(String command) { + return this.hasPermission("reflex.command." + command.toLowerCase()); + } + + public boolean canReceiveVerbose() { + return this.hasPermission("reflex.verbose") && this.getBoolean("isVerboseActive"); + } + + public boolean hasPermission(String s) { + if (Reflex.getReflex().isCachingPermissions()) { + if (!this.permissionCache.containsKey(s)) { + this.permissionCache.put(s, this.player.hasPermission(s)); + } + + return this.permissionCache.get(s); + } else { + return this.player.hasPermission(s); + } + } + + public int getPing() { + if (!this.getTimerWithOffset("pingTracker", 3000L).hasPassed(2500L)) { + return this.getInt("lastPing"); + } else { + try { + Object handle = this.player.getClass().getMethod("getHandle").invoke(this.player); + this.getTimer("pingTracker").reset(); + return (Integer)this.setStat("lastPing", (Integer)handle.getClass().getDeclaredField("ping").get(handle)); + } catch (Exception ignored) { + this.getTimer("pingTracker").reset(); + return this.setStat("lastPing", -1); + } + } + } + + public void kick(String message) { + boolean kill = Reflex.getReflex().getSetting("general.reflex_kick.kill", true); + boolean strikeLightning = Reflex.getReflex().getSetting("general.reflex_kick.strike_lightning", true); + if (kill) { + ReflexScheduler.sync().run(ReflexRunnable.simple("KillerThread", () -> this.player.setHealth(0.0))); + } + + if (strikeLightning) { + this.player.getWorld().strikeLightningEffect(this.player.getLocation().clone().add(0.0, 1.0, 0.0)); + } + + try { + AsyncCatcher.catchOp(""); + this.player.kickPlayer("\n" + message + "\n"); + } catch (IllegalStateException ignoredEx) { + ReflexScheduler.sync().run(ReflexRunnable.simple("synced-kick", () -> this.player.kickPlayer("\n" + message + "\n"))); + } + } + + public void ban(TimeUnit unit, long duration, String message) { + try { + AsyncCatcher.catchOp(""); + this.kick(message); + Reflex.getReflex().banPlayer(this.player, message, duration, unit); + } catch (IllegalStateException ignored) { + ReflexScheduler.sync().run(ReflexRunnable.simple("synced-ban", () -> { + this.kick(message); + Reflex.getReflex().banPlayer(this.player, message, duration, unit); + })); + } + } + + public boolean hasSpeedEffect() { + return this.hasEffect(PotionEffectType.SPEED); + } + + public float getSpeedAmpl() { + return this.getEffectAmpl(PotionEffectType.SPEED); + } + + public boolean hasJumpEffect() { + return this.hasEffect(PotionEffectType.JUMP); + } + + public float getJumpAmpl() { + return this.getEffectAmpl(PotionEffectType.JUMP); + } + + public boolean hasSlowFallingEffect() { + return VersionUtils.getServerVersion().hasMinimum(MCVersion.V1_13_X) && this.player.hasPotionEffect(PotionEffectType.SLOW_FALLING); + } + + public boolean hasEffect(PotionEffectType pet) { + return this.getEffectAmpl(pet) > 0.0F; + } + + public float getEffectAmpl(PotionEffectType pet) { + return this.player + .getActivePotionEffects() + .stream() + .filter(effect -> effect.getType().equals(pet)) + .findFirst() + .map(effect -> (float)effect.getAmplifier() + 1.0F) + .orElse(0.0F); + } + + public int getPingTicks() { + return Maths.floor((double)this.getPing() / 50.0); + } + + @Override + public Object clone() { + return null; + } + + public ReflexPlayerData getTransferableAPI() { + return new ReflexPlayerData( + new TransferablePlayerData( + new TransferablePlayerData.InnerObj(Misc.copyMap(this.violations, true)), + new TransferablePlayerData.InnerObj(Misc.copyMap(this.heuristicsData, false)) + ) + ); + } + + public void transfer(Object o) { + TransferablePlayerData tpd = Misc.castSafely(o); + this.setViolations((ConcurrentHashMap)Misc.copyMap((ConcurrentHashMap)tpd.getViolations().getInner(), true)); + this.setHeuristicsData((HashMap>)Misc.>copyMap((HashMap)tpd.getHeuristicsData().getInner(), false)); + } + + public static ConcurrentHashMap getStatlist() { + return statlist; + } + + public HashMap getStats() { + return this.stats; + } + + public ConcurrentHashMap getViolations() { + return this.violations; + } + + public Map getPermissionCache() { + return this.permissionCache; + } + + public Player getPlayer() { + return this.player; + } + + public NPC getMainNpc() { + return this.mainNpc; + } + + public boolean isAdmin() { + return this.admin; + } + + static { + ADMIN.admin = true; + } +} diff --git a/src/main/java/rip/reflex/util/data/TransferablePlayerData.java b/src/main/java/rip/reflex/util/data/TransferablePlayerData.java new file mode 100644 index 0000000..f5121b0 --- /dev/null +++ b/src/main/java/rip/reflex/util/data/TransferablePlayerData.java @@ -0,0 +1,35 @@ +package rip.reflex.util.data; + +import java.io.Serializable; + +class TransferablePlayerData implements Serializable { + private static final long serialVersionUID = -7187571944591175938L; + private final TransferablePlayerData.InnerObj violations; + private final TransferablePlayerData.InnerObj heuristicsData; + + TransferablePlayerData(TransferablePlayerData.InnerObj violations, TransferablePlayerData.InnerObj heuristicsData) { + this.violations = violations; + this.heuristicsData = heuristicsData; + } + + TransferablePlayerData.InnerObj getViolations() { + return this.violations; + } + + TransferablePlayerData.InnerObj getHeuristicsData() { + return this.heuristicsData; + } + + static class InnerObj implements Serializable { + private static final long serialVersionUID = 2597219357509132296L; + private final Object inner; + + InnerObj(Object inner) { + this.inner = inner; + } + + Object getInner() { + return this.inner; + } + } +} diff --git a/src/main/java/rip/reflex/util/data/storage/BitStorage.java b/src/main/java/rip/reflex/util/data/storage/BitStorage.java new file mode 100644 index 0000000..e8288b6 --- /dev/null +++ b/src/main/java/rip/reflex/util/data/storage/BitStorage.java @@ -0,0 +1,82 @@ +package rip.reflex.util.data.storage; + +import java.util.function.Consumer; +import java.util.stream.Stream; +import rip.reflex.util.data.LimitedList; + +public class BitStorage { + private final LimitedList storage; + private final Object lock = new Object(); + + public BitStorage(int capacity) { + this.storage = new LimitedList<>(capacity); + } + + public boolean add(boolean bit) { + synchronized (this.lock) { + this.storage.add(bit); + return this.isFull(); + } + } + + public boolean get(int index) { + synchronized (this.lock) { + return this.storage.get(index); + } + } + + public boolean remove(int index) { + synchronized (this.lock) { + return this.storage.remove(index); + } + } + + public BitStorage clear() { + synchronized (this.lock) { + this.storage.clear(); + return this; + } + } + + public int count(boolean bit) { + synchronized (this.lock) { + return (int)this.storage.stream().filter(b -> b == bit).count(); + } + } + + public double getPercentage(boolean bit) { + synchronized (this.lock) { + return (double)this.count(bit) / (double)this.size() * 100.0; + } + } + + public int size() { + synchronized (this.lock) { + return this.storage.size(); + } + } + + public int getCapacity() { + synchronized (this.lock) { + return this.storage.getCapacity(); + } + } + + public boolean isFull() { + synchronized (this.lock) { + return this.storage.isFull(); + } + } + + public Stream stream() { + synchronized (this.lock) { + return this.storage.stream(); + } + } + + public void forEach(Consumer action) { + synchronized (this.lock) { + this.storage.forEach(action); + } + } +} diff --git a/src/main/java/rip/reflex/util/data/storage/NumberStorage.java b/src/main/java/rip/reflex/util/data/storage/NumberStorage.java new file mode 100644 index 0000000..2f7c06a --- /dev/null +++ b/src/main/java/rip/reflex/util/data/storage/NumberStorage.java @@ -0,0 +1,342 @@ +package rip.reflex.util.data.storage; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; +import java.util.stream.Stream; +import rip.reflex.util.data.LimitedList; +import rip.reflex.util.math.Maths; +import rip.reflex.util.serialization.ManualSerializable; + +public class NumberStorage implements ManualSerializable, Serializable { + private final Object lock = new Object(); + private LimitedList storage; + + private NumberStorage() { + } + + public NumberStorage(int capacity) { + this.storage = new LimitedList<>(capacity); + } + + public static NumberStorage deserialize(List list) { + Integer cap = (Integer)list.remove(0); + LimitedList stor = new LimitedList<>(cap); + list.forEach(nx -> stor.add((Number)nx)); + list.clear(); + NumberStorage n = new NumberStorage(); + n.setStorage(stor); + return n; + } + + public static NumberStorage make(double[] arr) { + NumberStorage storage = new NumberStorage(arr.length); + + for (double n : arr) { + storage.add(n); + } + + return storage; + } + + public static NumberStorage make(List list) { + NumberStorage storage = new NumberStorage(list.size()); + + for (double n : list) { + storage.add(n); + } + + return storage; + } + + @Override + public List serialize() { + synchronized (this.lock) { + ArrayList list = new ArrayList<>(); + list.add(this.storage.getCapacity()); + list.addAll(this.storage); + return list; + } + } + + public boolean contains(Number n) { + synchronized (this.lock) { + return this.storage.contains(n); + } + } + + public List values() { + synchronized (this.lock) { + return this.storage; + } + } + + public Number[] asArray() { + synchronized (this.lock) { + Number[] array = (Number[])new Number[this.storage.size()].clone(); + + for (int i = 0; i < array.length; i++) { + array[i] = this.storage.get(i); + } + + return array; + } + } + + public double[] asDoubleArray() { + synchronized (this.lock) { + double[] array = (double[])new double[this.storage.size()].clone(); + + for (int i = 0; i < array.length; i++) { + if (this.storage.get(i) == null) { + this.storage.set(i, Integer.valueOf(0)); + } + + array[i] = (Double)this.storage.get(i); + } + + return array; + } + } + + public int size() { + synchronized (this.lock) { + return this.storage.size(); + } + } + + public boolean isFull() { + synchronized (this.lock) { + return this.storage.isFull(); + } + } + + public double sum() { + synchronized (this.lock) { + return this.storage.stream().mapToDouble(Number::doubleValue).sum(); + } + } + + public double average() { + synchronized (this.lock) { + return this.storage.stream().mapToDouble(Number::doubleValue).sum() / (double)this.size(); + } + } + + public double averageNotZero(double alt) { + synchronized (this.lock) { + return this.averageNot(0.0, alt); + } + } + + public double averageNot(double not, double alt) { + synchronized (this.lock) { + return Maths.not(this.average(), not, alt); + } + } + + public double max() { + synchronized (this.lock) { + return Maths.max(this.asDoubleArray()); + } + } + + public double min() { + synchronized (this.lock) { + return Maths.min(this.asDoubleArray()); + } + } + + public NumberStorage add(Number number) { + synchronized (this.lock) { + if (number == null) { + return this; + } else { + this.storage.add(number); + return this; + } + } + } + + public NumberStorage addOrClear(Number number) { + synchronized (this.lock) { + return this.isFull() ? this.clear() : this.add(number); + } + } + + public boolean addChecking(Number number) { + synchronized (this.lock) { + this.add(number); + return this.isFull(); + } + } + + public NumberStorage addIf(Number number, boolean b) { + synchronized (this.lock) { + if (b && number != null) { + this.storage.add(number); + return this; + } else { + return this; + } + } + } + + public boolean addCheckingIf(Number number, boolean b) { + synchronized (this.lock) { + if (!b) { + return false; + } else { + this.add(number); + return this.isFull(); + } + } + } + + public NumberStorage remove(Number number) { + synchronized (this.lock) { + this.storage.remove(number); + return this; + } + } + + public NumberStorage remove(int index) { + synchronized (this.lock) { + this.storage.remove(index); + return this; + } + } + + public NumberStorage removeLast() { + synchronized (this.lock) { + int size = this.storage.size(); + return size == 0 ? this : this.remove(size - 1); + } + } + + public Number get(int index) { + synchronized (this.lock) { + return index >= 0 && index < this.size() ? this.storage.get(index) : null; + } + } + + public Integer getInteger(int index) { + synchronized (this.lock) { + Number n = this.get(index); + if (n == null) { + return null; + } else if (n instanceof Integer) { + return (Integer)n; + } else if (n instanceof Long) { + return Math.toIntExact((Long)n); + } else if (n instanceof Short) { + return Integer.valueOf((Short)n); + } else if (n instanceof Double) { + return Maths.floor((Double)n); + } else if (n instanceof Float) { + return Maths.floor((Float)n); + } else { + return n instanceof Byte ? Integer.valueOf((Byte)n) : null; + } + } + } + + public Long getLong(int index) { + synchronized (this.lock) { + Number n = this.get(index); + if (n == null) { + return null; + } else if (n instanceof Integer) { + return (long)((Integer)n).intValue(); + } else if (n instanceof Long) { + return (Long)n; + } else if (n instanceof Short) { + return (long)((Short)n).shortValue(); + } else if (n instanceof Double) { + return Maths.floor64((Double)n); + } else if (n instanceof Float) { + return Maths.floor64((Float)n); + } else { + return n instanceof Byte ? (long)((Byte)n).byteValue() : null; + } + } + } + + public NumberStorage clear() { + synchronized (this.lock) { + this.storage.clear(); + return this; + } + } + + public int getCapacity() { + synchronized (this.lock) { + return this.storage.getCapacity(); + } + } + + public NumberStorage copy() { + synchronized (this.lock) { + NumberStorage dest = new NumberStorage(this.getCapacity()); + + for (Number n : (LimitedList)this.storage.clone()) { + dest.add(n); + } + + return dest; + } + } + + public Stream stream() { + synchronized (this.lock) { + return this.storage.stream(); + } + } + + public void forEach(Consumer action) { + synchronized (this.lock) { + this.storage.forEach(action); + } + } + + @Override + public String toString() { + synchronized (this.lock) { + return this.storage.toString() + "(" + this.storage.size() + "/" + this.storage.getCapacity() + ")"; + } + } + + public String toString(int placesAfterDot) { + if (placesAfterDot < 0) { + throw new IllegalArgumentException("illegal rounding: " + placesAfterDot + " places after dot"); + } else { + synchronized (this.lock) { + if (this.storage.isEmpty()) { + return "[](0/" + this.storage.getCapacity() + ")"; + } else { + StringBuilder sb = new StringBuilder(); + sb.append('['); + Number first = this.storage.get(0); + sb.append(round(first, placesAfterDot)); + if (this.storage.size() > 1) { + for (int i = 1; i < this.storage.size(); i++) { + sb.append(", ").append(round(this.storage.get(i), placesAfterDot)); + } + } + + sb.append(']'); + return sb.toString() + "(" + this.storage.size() + "/" + this.storage.getCapacity() + ")"; + } + } + } + } + + private static String round(Number n, int placesAfterDot) { + return String.format("%." + placesAfterDot + "f", n); + } + + private void setStorage(LimitedList storage) { + this.storage = storage; + } +} diff --git a/src/main/java/rip/reflex/util/data/storage/Storage.java b/src/main/java/rip/reflex/util/data/storage/Storage.java new file mode 100644 index 0000000..29c97a1 --- /dev/null +++ b/src/main/java/rip/reflex/util/data/storage/Storage.java @@ -0,0 +1,77 @@ +package rip.reflex.util.data.storage; + +import java.io.Serializable; +import java.util.List; +import java.util.function.Consumer; +import java.util.stream.Stream; +import rip.reflex.util.data.LimitedList; + +public class Storage implements Serializable { + private static final int DEFAULT_SIZE = 5000; + private final LimitedList storage; + + public Storage() { + this.storage = new LimitedList<>(5000); + } + + public Storage(int size) { + this.storage = new LimitedList<>(size); + } + + private Storage(LimitedList storage) { + this.storage = storage; + } + + public List values() { + return this.storage; + } + + public Object first() { + return this.get(0); + } + + public Object get(int index) { + return index >= 0 && index < this.size() ? this.storage.get(index) : null; + } + + public Object[] asArray() { + return (Object[])this.storage.toArray().clone(); + } + + public int size() { + return this.storage.size(); + } + + public boolean isFull() { + return this.storage.isFull(); + } + + public Storage add(Object o) { + this.storage.add(o); + return this; + } + + public void remove(Object o) { + this.storage.remove(o); + } + + public boolean isEmpty() { + return this.storage.isEmpty(); + } + + public void clear() { + this.storage.clear(); + } + + public Storage copy() { + return new Storage((LimitedList)this.storage.clone()); + } + + public Stream stream() { + return this.storage.stream(); + } + + public void forEach(Consumer action) { + this.storage.forEach(action); + } +} diff --git a/src/main/java/rip/reflex/util/data/storage/TimerStorage.java b/src/main/java/rip/reflex/util/data/storage/TimerStorage.java new file mode 100644 index 0000000..7f14db5 --- /dev/null +++ b/src/main/java/rip/reflex/util/data/storage/TimerStorage.java @@ -0,0 +1,68 @@ +package rip.reflex.util.data.storage; + +import java.io.Serializable; +import java.util.List; +import rip.reflex.util.data.LimitedList; +import rip.reflex.util.time.Timer; + +public class TimerStorage implements Serializable { + private static final int DEFAULT_SIZE = 5000; + private final LimitedList storage; + + public TimerStorage() { + this.storage = new LimitedList<>(5000); + } + + public TimerStorage(int size) { + this.storage = new LimitedList<>(size); + } + + public List values() { + return this.storage; + } + + public Timer first() { + return this.get(0); + } + + public Timer get(int index) { + return index >= 0 && index < this.size() ? this.storage.get(index) : null; + } + + public long averageTimePassed() { + return this.isEmpty() ? 0L : this.storage.stream().mapToLong(Timer::getTimePassed).sum() / (long)this.size(); + } + + public long averageTimeTicked() { + return this.isEmpty() ? 0L : this.storage.stream().mapToLong(Timer::getTimeTicked).sum() / (long)this.size(); + } + + public TimerStorage resetAll() { + this.storage.forEach(Timer::reset); + return this; + } + + public int size() { + return this.storage.size(); + } + + public boolean isFull() { + return this.storage.isFull(); + } + + public void add(Timer o) { + this.storage.add(o); + } + + public void remove(Timer o) { + this.storage.remove(o); + } + + public boolean isEmpty() { + return this.storage.isEmpty(); + } + + public void clear() { + this.storage.clear(); + } +} diff --git a/src/main/java/rip/reflex/util/db/DatabaseException.java b/src/main/java/rip/reflex/util/db/DatabaseException.java new file mode 100644 index 0000000..b567d10 --- /dev/null +++ b/src/main/java/rip/reflex/util/db/DatabaseException.java @@ -0,0 +1,11 @@ +package rip.reflex.util.db; + +public class DatabaseException extends RuntimeException { + public DatabaseException(String message) { + super(message); + } + + public DatabaseException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/rip/reflex/util/db/DatabaseLoader.java b/src/main/java/rip/reflex/util/db/DatabaseLoader.java new file mode 100644 index 0000000..375ef48 --- /dev/null +++ b/src/main/java/rip/reflex/util/db/DatabaseLoader.java @@ -0,0 +1,70 @@ +package rip.reflex.util.db; + +import java.io.File; +import me.flo.flogger.impl.DailyLogFilePublisher; +import rip.reflex.Reflex; +import rip.reflex.api.db.BanImpl; +import rip.reflex.api.db.DataImpl; +import rip.reflex.api.db.DatabaseClient; +import rip.reflex.util.db.ban.FileBanImpl; +import rip.reflex.util.db.ban.MySQLBanImpl; +import rip.reflex.util.db.client.MySQLClient; +import rip.reflex.util.db.conf.DatabaseConfig; +import rip.reflex.util.db.dataimpl.MySQLDataImpl; +import rip.reflex.util.db.logs.MySQLLogUtil; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.protocol.mcaccess.MCAccess; + +public class DatabaseLoader { + public static void loadDB(Reflex reflex) { + DatabaseConfig config = DatabaseConfig.load(new File(reflex.getWorkingDir())); + reflex.setUsedDB(config != null ? config.getType() : DatabaseType.UNKNOWN); + if (reflex.getSetting("general.custom_db.enabled", false)) { + reflex.setUsedDB(DatabaseType.CUSTOM); + reflex.getLogger().info("Using custom database type. Implementations specified in the config will be loaded reflectively"); + } + + switch (reflex.getUsedDB()) { + case MYSQL: + MySQLClient client = new MySQLClient(); + client.connect(config); + reflex.setClient(client); + reflex.setDataImpl(new MySQLDataImpl(client)); + reflex.setBanImpl(new MySQLBanImpl(client)); + MySQLLogUtil.setClient(client); + MySQLLogUtil.setStarttime(System.currentTimeMillis()); + break; + case CUSTOM: + try { + String ic = "Invalid custom database configuration. Missing "; + DatabaseClient dbClient = (DatabaseClient)MCAccess.constructWithDef( + reflex.getConfig().getString("general.customdb.client", "Invalid custom database configuration. Missing client implementation") + ); + dbClient.connect(config); + reflex.setClient(dbClient); + reflex.setDataImpl( + (DataImpl)MCAccess.constructWithDef( + reflex.getConfig().getString("general.customdb.data", "Invalid custom database configuration. Missing data implementation") + ) + ); + reflex.setBanImpl( + (BanImpl)MCAccess.constructWithDef( + reflex.getConfig().getString("general.customdb.ban", "Invalid custom database configuration. Missing ban implementation") + ) + ); + reflex.setDlogp( + (DailyLogFilePublisher)MCAccess.constructWithDef( + reflex.getConfig().getString("general.customdb.log", "Invalid custom database configuration. Missing log implementation") + ) + ); + } catch (Exception ex) { + Misc.sneaky(ex); + } + break; + case MONGODB: + case UNKNOWN: + reflex.setBanImpl(new FileBanImpl(new File(new File(reflex.getWorkingDir()), "bannedPlayers.json"))); + reflex.getBanImpl().init(); + } + } +} diff --git a/src/main/java/rip/reflex/util/db/DatabaseType.java b/src/main/java/rip/reflex/util/db/DatabaseType.java new file mode 100644 index 0000000..4dca0c8 --- /dev/null +++ b/src/main/java/rip/reflex/util/db/DatabaseType.java @@ -0,0 +1,14 @@ +package rip.reflex.util.db; + +import java.util.Arrays; + +public enum DatabaseType { + MONGODB, + MYSQL, + CUSTOM, + UNKNOWN; + + public static DatabaseType byString(String s) { + return Arrays.stream(values()).filter(t -> t.name().equalsIgnoreCase(s)).findFirst().orElse(UNKNOWN); + } +} diff --git a/src/main/java/rip/reflex/util/db/ban/FileBanImpl.java b/src/main/java/rip/reflex/util/db/ban/FileBanImpl.java new file mode 100644 index 0000000..fe38257 --- /dev/null +++ b/src/main/java/rip/reflex/util/db/ban/FileBanImpl.java @@ -0,0 +1,108 @@ +package rip.reflex.util.db.ban; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import rip.reflex.api.BanInfo; +import rip.reflex.api.db.BanImpl; +import rip.reflex.util.misc.Misc; + +public class FileBanImpl implements BanImpl { + private final File file; + private FileBanMap map = new FileBanMap(); + + @Override + public boolean ban(UUID uuid, String message, long time, TimeUnit timeUnit) { + if (this.map.getMap().containsKey(uuid)) { + return false; + } else { + this.map + .getMap() + .put( + uuid, + new FileBanMap.InternalBanInfo(time == -1L ? -1L : System.currentTimeMillis() + timeUnit.toMillis(time), System.currentTimeMillis(), message) + ); + return true; + } + } + + @Override + public boolean unban(UUID uuid) { + if (!this.map.getMap().containsKey(uuid)) { + return false; + } else { + this.map.getMap().remove(uuid); + return true; + } + } + + @Override + public BanInfo getBanInfo(UUID uuid) { + Objects.requireNonNull(this.map, "fbm"); + Objects.requireNonNull(this.map.getMap(), "fbm-m"); + FileBanMap.InternalBanInfo ib = this.map.getMap().get(uuid); + if (ib == null) { + return BanInfo.NOT_BANNED; + } else if (ib.shallBeUnbanned()) { + this.unban(uuid); + return BanInfo.NOT_BANNED; + } else { + return new BanInfo(ib.getMessage(), ib.getEndOfBan() == -1L ? -1L : ib.getEndOfBan() - System.currentTimeMillis(), ib.getBanStart()); + } + } + + @Override + public int getBanCount() { + return this.map.getMap().size(); + } + + @Override + public int getBannedCountIn(TimeUnit unit, long value) { + long timeStamp = System.currentTimeMillis() - unit.toMillis(value); + return (int)this.map.getMap().entrySet().stream().filter(entry -> entry.getValue().getBanStart() > value).count(); + } + + @Override + public void init() { + if (this.file.exists()) { + try { + this.map = (FileBanMap)new Gson().fromJson(new String(Files.readAllBytes(this.file.toPath())), FileBanMap.class); + Misc.lif(this.map == null, () -> this.map = new FileBanMap()); + Misc.lif(this.map.getMap() == null, () -> this.map.setMap()); + Objects.requireNonNull(this.map, "FileBanMap cannot be null"); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + + @Override + public void off() { + FileWriter w = null; + + try { + Files.deleteIfExists(this.file.toPath()); + w = new FileWriter(this.file); + new GsonBuilder().setPrettyPrinting().create().toJson(this.map, FileBanMap.class, w); + w.flush(); + } catch (IOException e) { + e.printStackTrace(); + + try { + w.close(); + } catch (IOException err) { + err.printStackTrace(); + } + } + } + + public FileBanImpl(File file) { + this.file = file; + } +} diff --git a/src/main/java/rip/reflex/util/db/ban/FileBanMap.java b/src/main/java/rip/reflex/util/db/ban/FileBanMap.java new file mode 100644 index 0000000..880aa24 --- /dev/null +++ b/src/main/java/rip/reflex/util/db/ban/FileBanMap.java @@ -0,0 +1,104 @@ +package rip.reflex.util.db.ban; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class FileBanMap { + private Map map; + + public Map setMap() { + return this.map = new HashMap() { + public FileBanMap.InternalBanInfo put(UUID key, FileBanMap.InternalBanInfo value) { + return super.put(key, value); + } + }; + } + + public Map getMap() { + if (this.map == null) { + this.setMap(); + } + + return this.map; + } + + public FileBanMap(Map map) { + this.map = map; + } + + public FileBanMap() { + } + + static class InternalBanInfo implements Serializable { + private final long endOfBan; + private final long banStart; + private final String message; + + public boolean shallBeUnbanned() { + return this.endOfBan < System.currentTimeMillis() && this.endOfBan != -1L; + } + + public InternalBanInfo(long endOfBan, long banStart, String message) { + this.endOfBan = endOfBan; + this.banStart = banStart; + this.message = message; + } + + public long getEndOfBan() { + return this.endOfBan; + } + + public long getBanStart() { + return this.banStart; + } + + public String getMessage() { + return this.message; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (!(o instanceof FileBanMap.InternalBanInfo)) { + return false; + } else { + FileBanMap.InternalBanInfo other = (FileBanMap.InternalBanInfo)o; + if (!other.canEqual(this)) { + return false; + } else if (this.getEndOfBan() != other.getEndOfBan()) { + return false; + } else if (this.getBanStart() != other.getBanStart()) { + return false; + } else { + Object this$message = this.getMessage(); + Object other$message = other.getMessage(); + return this$message == null ? other$message == null : this$message.equals(other$message); + } + } + } + + protected boolean canEqual(Object other) { + return other instanceof FileBanMap.InternalBanInfo; + } + + @Override + public int hashCode() { + int PRIME = 59; + int result = 1; + long $endOfBan = this.getEndOfBan(); + result = result * 59 + (int)($endOfBan >>> 32 ^ $endOfBan); + long $banStart = this.getBanStart(); + result = result * 59 + (int)($banStart >>> 32 ^ $banStart); + Object $message = this.getMessage(); + return result * 59 + ($message == null ? 43 : $message.hashCode()); + } + + @Override + public String toString() { + return "FileBanMap.InternalBanInfo(endOfBan=" + this.getEndOfBan() + ", banStart=" + this.getBanStart() + ", message=" + this.getMessage() + ")"; + } + } +} diff --git a/src/main/java/rip/reflex/util/db/ban/MySQLBanImpl.java b/src/main/java/rip/reflex/util/db/ban/MySQLBanImpl.java new file mode 100644 index 0000000..97a9956 --- /dev/null +++ b/src/main/java/rip/reflex/util/db/ban/MySQLBanImpl.java @@ -0,0 +1,105 @@ +package rip.reflex.util.db.ban; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import rip.reflex.api.BanInfo; +import rip.reflex.api.db.BanImpl; +import rip.reflex.util.db.client.MySQLClient; +import rip.reflex.util.handler.ExceptionHandler; +import rip.reflex.util.handler.SaveConsumer; + +public class MySQLBanImpl implements BanImpl { + private final MySQLClient client; + private boolean table = false; + + @Override + public boolean ban(UUID uuid, String msg, long time, TimeUnit timeUnit) { + this.createTable(); + BanInfo info = this.getBanInfo(uuid); + if (info.getBanTime() != 0L) { + return false; + } else { + this.client + .executePrepared("INSERT INTO reflex_bans (uuid, endofban, banstart, message) VALUES (?, ?, ?, ?)", (SaveConsumer)ps -> { + ps.setString(1, uuid.toString()); + ps.setLong(2, System.currentTimeMillis() + timeUnit.toMillis(time)); + ps.setLong(3, System.currentTimeMillis()); + ps.setString(4, msg); + }); + return true; + } + } + + @Override + public boolean unban(UUID uuid) { + this.createTable(); + BanInfo info = this.getBanInfo(uuid); + if (info.getBanTime() == 0L) { + return false; + } else { + this.client.executePrepared("DELETE FROM reflex_bans WHERE uuid=?", ps -> ExceptionHandler.save(Object.class, () -> { + ps.setString(1, uuid.toString()); + return null; + })); + return true; + } + } + + @Override + public BanInfo getBanInfo(UUID uuid) { + this.createTable(); + this.client.execute("DELETE FROM reflex_bans WHERE uuid<-1"); + return (BanInfo)this.client + .executeQuery( + "SELECT banStart, endofban, message FROM reflex_bans WHERE uuid='" + uuid.toString() + "'", + (ExceptionHandler.SafeFunction)resultSet -> { + if (!resultSet.next()) { + return BanInfo.NOT_BANNED; + } else { + long endOfBan = resultSet.getLong("endofban"); + long banStart = resultSet.getLong("banStart"); + String msg = resultSet.getString("message"); + return new BanInfo(msg, endOfBan == -1L ? -1L : endOfBan - System.currentTimeMillis(), banStart); + } + } + ); + } + + @Override + public int getBanCount() { + this.createTable(); + Object o = this.client.executeQuery("SELECT COUNT(1) FROM `reflex_bans`", (ExceptionHandler.SafeFunction)resultSet -> { + resultSet.next(); + return resultSet.getInt(1); + }); + return (Integer)o; + } + + @Override + public int getBannedCountIn(TimeUnit unit, long value) { + this.createTable(); + long timeStamp = System.currentTimeMillis() - unit.toMillis(value); + Object o = this.client + .executeQuery("SELECT COUNT(1) FROM `reflex_bans` WHERE banstart > " + timeStamp, (ExceptionHandler.SafeFunction)rs -> { + rs.next(); + return rs.getInt(1); + }); + return (Integer)o; + } + + private void createTable() { + if (!this.table) { + this.table = true; + this.client + .execute( + "CREATE TABLE IF NOT EXISTS `reflex_bans`\n(\n `uuid` TINYTEXT NOT NULL,\n `endofban` BIGINT NOT NULL, \n `banstart` BIGINT NOT NULL, \n `message` TINYTEXT NOT NULL \n) \n ENGINE = InnoDB;" + ); + } + } + + public MySQLBanImpl(MySQLClient client) { + this.client = client; + } +} diff --git a/src/main/java/rip/reflex/util/db/client/MongoDBClient.java b/src/main/java/rip/reflex/util/db/client/MongoDBClient.java new file mode 100644 index 0000000..df147e2 --- /dev/null +++ b/src/main/java/rip/reflex/util/db/client/MongoDBClient.java @@ -0,0 +1,25 @@ +package rip.reflex.util.db.client; + +import rip.reflex.api.db.DatabaseClient; +import rip.reflex.util.db.DatabaseType; +import rip.reflex.util.db.conf.DatabaseConfig; + +public class MongoDBClient implements DatabaseClient { + @Override + public void connect0(DatabaseConfig config) throws Exception { + } + + @Override + public boolean isConnected0() throws Exception { + return false; + } + + @Override + public void disconnect0() throws Exception { + } + + @Override + public DatabaseType getType() { + return DatabaseType.MONGODB; + } +} diff --git a/src/main/java/rip/reflex/util/db/client/MySQLClient.java b/src/main/java/rip/reflex/util/db/client/MySQLClient.java new file mode 100644 index 0000000..bd8cc5e --- /dev/null +++ b/src/main/java/rip/reflex/util/db/client/MySQLClient.java @@ -0,0 +1,92 @@ +package rip.reflex.util.db.client; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.function.Consumer; +import java.util.function.Function; +import rip.reflex.api.db.DatabaseClient; +import rip.reflex.util.db.DatabaseException; +import rip.reflex.util.db.DatabaseType; +import rip.reflex.util.db.conf.DatabaseConfig; + +public class MySQLClient implements DatabaseClient { + private Connection con; + + public void execute(String cmd) { + if (this.isConnected()) { + try { + this.con.createStatement().execute(cmd); + } catch (SQLException ex) { + ex.printStackTrace(); + throw new DatabaseException("MySQL / Error while executing command '" + cmd + "'", ex); + } + } + } + + public Object executeQuery(String query, Function cons) { + if (!this.isConnected()) { + return null; + } else { + try { + ResultSet set = this.con.createStatement().executeQuery(query); + Object o = cons != null && set != null ? cons.apply(set) : null; + if (set != null) { + set.close(); + } + + return o; + } catch (Exception e) { + throw new DatabaseException("MySQL / Error while executing query: '" + query + "'", e); + } + } + } + + public void executePrepared(String query, Consumer cons) { + if (this.isConnected()) { + try { + PreparedStatement ps = this.con.prepareStatement(query); + cons.accept(ps); + ps.executeUpdate(); + } catch (Exception ex) { + throw new DatabaseException("MySQL / Error while executing prepared query: '" + query + "'", ex); + } + } + } + + @Override + public void connect0(DatabaseConfig c) throws Exception { + this.con = DriverManager.getConnection( + "jdbc:mysql://" + + c.getHost() + + ":" + + c.getPort() + + "/" + + c.getDatabase() + + "?user=" + + c.getUser() + + "&password=" + + c.getPw() + + "&autoReconnect=true&useUnicode=true&characterEncoding=utf-8" + ); + } + + @Override + public boolean isConnected0() throws Exception { + return this.con != null && !this.con.isClosed(); + } + + @Override + public void disconnect0() throws Exception { + if (this.isConnected()) { + this.con.close(); + } + } + + @Override + public DatabaseType getType() { + return DatabaseType.MYSQL; + } +} diff --git a/src/main/java/rip/reflex/util/db/conf/DatabaseConfig.java b/src/main/java/rip/reflex/util/db/conf/DatabaseConfig.java new file mode 100644 index 0000000..aae12e0 --- /dev/null +++ b/src/main/java/rip/reflex/util/db/conf/DatabaseConfig.java @@ -0,0 +1,156 @@ +package rip.reflex.util.db.conf; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import javax.crypto.CipherInputStream; +import javax.crypto.CipherOutputStream; +import rip.reflex.util.crypto.Encryptor; +import rip.reflex.util.db.DatabaseType; +import rip.reflex.util.misc.Misc; + +public class DatabaseConfig { + private DatabaseType type; + private int port; + private String host; + private String database; + private String user; + private String pw; + + public static DatabaseConfig load(File dir) { + if (!dir.exists()) { + dir.mkdir(); + } + + File dataFile = new File(dir, "dbconf"); + if (!dataFile.exists()) { + return null; + } else { + try { + FileInputStream fileIn = new FileInputStream(dataFile); + CipherInputStream cipherIn = new CipherInputStream(fileIn, Encryptor.getCipher(2)); + DataInputStream in = new DataInputStream(cipherIn); + DatabaseConfig config = new DatabaseConfig(); + config.type = DatabaseType.byString(in.readUTF()); + config.host = in.readUTF(); + + try { + config.port = in.readInt(); + } catch (Exception ex) { + System.out.println("\n\nPlease reconfigure your reflex database!\n\n"); + throw new RuntimeException(ex); + } + + config.database = in.readUTF(); + config.user = in.readUTF(); + config.pw = in.readUTF(); + Misc.close(in, cipherIn, fileIn); + return config; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + public void save(File dir) { + if (!dir.exists()) { + dir.mkdirs(); + } + + File dataFile = new File(dir, "dbconf"); + + try { + FileOutputStream fileOut = new FileOutputStream(dataFile); + CipherOutputStream cipherOut = new CipherOutputStream(fileOut, Encryptor.getCipher(1)); + DataOutputStream out = new DataOutputStream(cipherOut); + out.writeUTF(this.type.toString()); + out.writeUTF(this.host); + out.writeInt(this.port); + out.writeUTF(this.database); + out.writeUTF(this.user); + out.writeUTF(this.pw); + Misc.close(out, cipherOut, fileOut); + } catch (Exception err) { + throw new RuntimeException(err); + } + } + + public DatabaseConfig(DatabaseType type, int port, String host, String database, String user, String pw) { + this.type = type; + this.port = port; + this.host = host; + this.database = database; + this.user = user; + this.pw = pw; + } + + public DatabaseConfig() { + } + + public DatabaseType getType() { + return this.type; + } + + public int getPort() { + return this.port; + } + + public String getHost() { + return this.host; + } + + public String getDatabase() { + return this.database; + } + + public String getUser() { + return this.user; + } + + public String getPw() { + return this.pw; + } + + public void setType(DatabaseType type) { + this.type = type; + } + + public void setPort(int port) { + this.port = port; + } + + public void setHost(String host) { + this.host = host; + } + + public void setDatabase(String database) { + this.database = database; + } + + public void setUser(String user) { + this.user = user; + } + + public void setPw(String pw) { + this.pw = pw; + } + + @Override + public String toString() { + return "DatabaseConfig(type=" + + this.getType() + + ", port=" + + this.getPort() + + ", host=" + + this.getHost() + + ", database=" + + this.getDatabase() + + ", user=" + + this.getUser() + + ", pw=" + + this.getPw() + + ")"; + } +} diff --git a/src/main/java/rip/reflex/util/db/dataimpl/MySQLDataImpl.java b/src/main/java/rip/reflex/util/db/dataimpl/MySQLDataImpl.java new file mode 100644 index 0000000..1fb924b --- /dev/null +++ b/src/main/java/rip/reflex/util/db/dataimpl/MySQLDataImpl.java @@ -0,0 +1,64 @@ +package rip.reflex.util.db.dataimpl; + +import java.sql.PreparedStatement; +import rip.reflex.api.db.DataImpl; +import rip.reflex.util.db.client.MySQLClient; +import rip.reflex.util.handler.ExceptionHandler; +import rip.reflex.util.handler.SaveConsumer; + +public class MySQLDataImpl implements DataImpl { + private final MySQLClient client; + private boolean table = false; + + @Override + public void saveData(String hash, byte[] data) { + this.createTable(); + if (this.contains()) { + this.client.executePrepared("UPDATE reflex_ds SET hash=?,data=? WHERE ky=?", (SaveConsumer)ps -> { + ps.setString(1, hash); + ps.setBytes(2, data); + ps.setBoolean(3, true); + }); + } else { + this.client.executePrepared("INSERT INTO reflex_ds (ky, hash, data) VALUES (?, ?, ?)", (SaveConsumer)ps -> { + ps.setBoolean(1, true); + ps.setString(2, hash); + ps.setBytes(3, data); + }); + } + } + + @Override + public boolean contains() { + this.createTable(); + return (Boolean)this.client.executeQuery("SELECT hash FROM reflex_ds WHERE ky=true", resultSet -> ExceptionHandler.save(Boolean.class, resultSet::next)); + } + + @Override + public byte[] getData() { + this.createTable(); + return (byte[])this.client + .executeQuery("SELECT data FROM reflex_ds WHERE ky=true", rs -> ExceptionHandler.save(byte[].class, () -> rs.next() ? rs.getBytes("data") : null)); + } + + @Override + public String getHash() { + this.createTable(); + return (String)this.client + .executeQuery("SELECT hash FROM reflex_ds WHERE ky=true", rs -> ExceptionHandler.save(String.class, () -> rs.next() ? rs.getString("hash") : null)); + } + + private void createTable() { + if (!this.table) { + this.table = true; + this.client + .execute( + "CREATE TABLE IF NOT EXISTS `reflex_ds`\n(\n `ky` BOOL NOT NULL,\n `hash` TINYTEXT NOT NULL, \n `data` MEDIUMBLOB NOT NULL\n \n) \n ENGINE = InnoDB;" + ); + } + } + + public MySQLDataImpl(MySQLClient client) { + this.client = client; + } +} diff --git a/src/main/java/rip/reflex/util/db/logs/MySQLLogUtil.java b/src/main/java/rip/reflex/util/db/logs/MySQLLogUtil.java new file mode 100644 index 0000000..566c33b --- /dev/null +++ b/src/main/java/rip/reflex/util/db/logs/MySQLLogUtil.java @@ -0,0 +1,46 @@ +package rip.reflex.util.db.logs; + +import java.io.File; +import java.nio.file.Files; +import java.sql.PreparedStatement; +import java.util.Date; +import rip.reflex.util.db.client.MySQLClient; +import rip.reflex.util.handler.SaveConsumer; +import rip.reflex.util.time.date.ReflexFormatter; + +public class MySQLLogUtil { + private static long starttime; + private static MySQLClient client; + + public static void save(File f) { + createTable(); + client.executePrepared("INSERT INTO reflex_logs (startstamp, endstamp, data) VALUES (?, ?, ?)", (SaveConsumer)ps -> { + ps.setString(1, ReflexFormatter.formatTimeDefault(new Date(starttime))); + ps.setString(2, ReflexFormatter.formatTimeDefault(new Date(System.currentTimeMillis()))); + ps.setString(3, new String(Files.readAllBytes(f.toPath()))); + Files.deleteIfExists(f.toPath()); + }); + } + + private static void createTable() { + client.execute( + "CREATE TABLE IF NOT EXISTS `reflex_logs`\n(\n `startstamp` TINYTEXT NOT NULL,\n `endstamp` TINYTEXT NOT NULL,\n `data` LONGTEXT NOT NULL\n) \n ENGINE = InnoDB;" + ); + } + + public static String abcde(long z) { + if (z == -892719873918010981L) { + return "14"; + } else { + return z == -392179402103138915L ? "48".replace("4", "").replace("8", "1") : "9".replace("9", "20"); + } + } + + public static void setStarttime(long starttime) { + MySQLLogUtil.starttime = starttime; + } + + public static void setClient(MySQLClient client) { + MySQLLogUtil.client = client; + } +} diff --git a/src/main/java/rip/reflex/util/debugging/DebugContainer.java b/src/main/java/rip/reflex/util/debugging/DebugContainer.java new file mode 100644 index 0000000..b21741f --- /dev/null +++ b/src/main/java/rip/reflex/util/debugging/DebugContainer.java @@ -0,0 +1,28 @@ +package rip.reflex.util.debugging; + +import java.util.Date; +import rip.reflex.Reflex; +import rip.reflex.util.data.LimitedList; + +public class DebugContainer { + private final LimitedList entries = new LimitedList<>(100); + + public DebugContainer addEntry(String entry) { + this.entries.add("[" + Reflex.getReflex().getTimeFormat().format(new Date(System.currentTimeMillis())) + "]: " + entry); + return this; + } + + @Override + public String toString() { + StringBuilder res = new StringBuilder("Last 100 packets sent by Reflex:\n"); + this.entries.forEach(e -> { + res.append(e); + res.append('\n'); + }); + return res.deleteCharAt(res.length() - 1).toString(); + } + + public LimitedList getEntries() { + return this.entries; + } +} diff --git a/src/main/java/rip/reflex/util/debugging/Debugger.java b/src/main/java/rip/reflex/util/debugging/Debugger.java new file mode 100644 index 0000000..4d6e726 --- /dev/null +++ b/src/main/java/rip/reflex/util/debugging/Debugger.java @@ -0,0 +1,132 @@ +package rip.reflex.util.debugging; + +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.misc.Strings; + +public class Debugger { + private static final PrintStream orig = System.out; + + public static void debugIfUsed(Reflex r, String s) { + if (r.getSetting("general.debugStart", false)) { + System.out.println(s); + } + } + + public static void debugIf(String debugMessage, String configEntry) { + if (Reflex.getReflex().getSetting(configEntry, false)) { + System.out.println("DEBUG | " + debugMessage); + } + } + + public static void debugBooleans(Player p, boolean... booleen) { + if (p.isOp() && booleen.length >= 2) { + StringBuilder s = new StringBuilder(); + + for (boolean b : booleen) { + s.append(b ? "&a" : "&c").append(b).append("&7/"); + } + + p.sendMessage(ChatColor.translateAlternateColorCodes('&', s.deleteCharAt(s.length() - 1).toString())); + } + } + + public static void debugNums(Player p, Number... nums) { + if (p.isOp() && nums.length >= 2) { + StringBuilder s = new StringBuilder(); + + for (Number num : nums) { + s.append("&f").append(num).append("&7/"); + } + + p.sendMessage(ChatColor.translateAlternateColorCodes('&', s.deleteCharAt(s.length() - 1).toString())); + } + } + + public static void debugNumberStorage(Player p, String label, NumberStorage ns, int precision) { + if (p.isOp()) { + StringBuilder s = new StringBuilder(label + ": "); + ns.forEach( + n -> { + String nStr = n instanceof Double + ? String.format("%." + precision + "f", (Double)n) + : (n instanceof Float ? String.format("%." + precision + "f", (Float)n) : String.valueOf(n)); + s.append("§r, §c").append(nStr); + } + ); + String debug = Strings.replace(s.toString(), ": §r,", ""); + p.sendMessage(debug); + } + } + + public static void debugDoubleList(Player p, String label, List list, int precision) { + if (p.isOp()) { + StringBuilder s = new StringBuilder(label + ": "); + list.forEach(n -> s.append("§r, §c").append(String.format("%." + precision + "f", n))); + String debug = Strings.replace(s.toString(), ": §r,", ""); + p.sendMessage(debug); + } + } + + public static void debugSysOut() { + System.setOut(new PrintStream(System.out) { + @Override + public void println(boolean x) { + super.println("Called from: " + Debugger.getCallerClass() + "\n" + x); + } + + @Override + public void println(char x) { + super.println("Called from: " + Debugger.getCallerClass() + "\n" + x); + } + + @Override + public void println(int x) { + super.println("Called from: " + Debugger.getCallerClass() + "\n" + x); + } + + @Override + public void println(long x) { + super.println("Called from: " + Debugger.getCallerClass() + "\n" + x); + } + + @Override + public void println(float x) { + super.println("Called from: " + Debugger.getCallerClass() + "\n" + x); + } + + @Override + public void println(double x) { + super.println("Called from: " + Debugger.getCallerClass() + "\n" + x); + } + + @Override + public void println(char[] x) { + super.println("Called from: " + Debugger.getCallerClass() + "\n" + Arrays.toString(x)); + } + + @Override + public void println(String x) { + super.println("Called from: " + Debugger.getCallerClass() + "\n" + x); + } + + @Override + public void println(Object x) { + super.println("Called from: " + Debugger.getCallerClass() + "\n" + x); + } + }); + } + + public static void disableSysOutDebug() { + System.setOut(orig); + } + + public static String getCallerClass() { + return Thread.currentThread().getStackTrace()[3].toString(); + } +} diff --git a/src/main/java/rip/reflex/util/debugging/PacketDebugger.java b/src/main/java/rip/reflex/util/debugging/PacketDebugger.java new file mode 100644 index 0000000..d346257 --- /dev/null +++ b/src/main/java/rip/reflex/util/debugging/PacketDebugger.java @@ -0,0 +1,64 @@ +package rip.reflex.util.debugging; + +import com.comphenix.protocol.events.PacketContainer; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.bukkit.entity.Player; + +public class PacketDebugger { + private static final Map debug = new ConcurrentHashMap<>(); + + public static void addEntry(Player player, PacketContainer packet, boolean async) { + if (isDebugging(player)) { + debug.get(player).addEntry((async ? "ASYNC" : "SYNC") + ": " + packet.toString()); + } + } + + public static String printAndReset(Player player) { + if (!isDebugging(player)) { + return null; + } else { + String s = debug.get(player).toString(); + disableDebug(player); + return s; + } + } + + public static boolean isDebugging(Player p) { + return debug.containsKey(p); + } + + public static boolean toogleDebug(Player p) { + if (debug.containsKey(p)) { + debug.remove(p); + return false; + } else { + debug.put(p, new DebugContainer()); + return true; + } + } + + public static void enableDebug(Player p) { + if (!debug.containsKey(p)) { + debug.put(p, new DebugContainer()); + } + } + + public static void disableDebug(Player p) { + if (debug.containsKey(p)) { + debug.remove(p); + } + } + + public static void clearAll() { + debug.clear(); + } + + public static void cleanup() { + List toRm = new ArrayList<>(); + debug.keySet().stream().filter(p -> !p.isOnline()).forEach(toRm::add); + toRm.forEach(debug::remove); + } +} diff --git a/src/main/java/rip/reflex/util/handler/ExceptionHandler.java b/src/main/java/rip/reflex/util/handler/ExceptionHandler.java new file mode 100644 index 0000000..f532c00 --- /dev/null +++ b/src/main/java/rip/reflex/util/handler/ExceptionHandler.java @@ -0,0 +1,30 @@ +package rip.reflex.util.handler; + +import java.util.function.Function; + +public class ExceptionHandler { + public static T save(Class tc, ExceptionHandler.SafeSupplier sup) { + try { + return sup.apply(); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + + public interface SafeFunction extends Function { + R applySave(T value) throws Exception; + + @Override + default R apply(T t) { + try { + return this.applySave(t); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + public interface SafeSupplier { + T apply() throws Exception; + } +} diff --git a/src/main/java/rip/reflex/util/handler/SaveConsumer.java b/src/main/java/rip/reflex/util/handler/SaveConsumer.java new file mode 100644 index 0000000..f4e061d --- /dev/null +++ b/src/main/java/rip/reflex/util/handler/SaveConsumer.java @@ -0,0 +1,16 @@ +package rip.reflex.util.handler; + +import java.util.function.Consumer; + +public interface SaveConsumer extends Consumer { + void acceptSafe(T value) throws Exception; + + @Override + default void accept(T t) { + try { + this.acceptSafe(t); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } +} diff --git a/src/main/java/rip/reflex/util/location/DirectionalHorizontalMove.java b/src/main/java/rip/reflex/util/location/DirectionalHorizontalMove.java new file mode 100644 index 0000000..78947f0 --- /dev/null +++ b/src/main/java/rip/reflex/util/location/DirectionalHorizontalMove.java @@ -0,0 +1,113 @@ +package rip.reflex.util.location; + +import org.bukkit.util.Vector; +import rip.reflex.util.math.Maths; + +public class DirectionalHorizontalMove { + private final double oldX; + private final double oldZ; + private final double newX; + private final double newZ; + private final double movedX; + private final double movedZ; + private final Vector vector; + + public DirectionalHorizontalMove(double oldX, double oldZ, double newX, double newZ) { + this(oldX, oldZ, newX, newZ, newX - oldX, newZ - oldZ); + } + + public DirectionalHorizontalMove(double oldX, double oldZ, double newX, double newZ, double movedX, double movedZ) { + this.oldX = oldX; + this.oldZ = oldZ; + this.newX = newX; + this.newZ = newZ; + this.movedX = movedX; + this.movedZ = movedZ; + this.vector = new Vector(movedX, 0.0, movedZ); + } + + public boolean isCodirectional(Vector other) { + return Maths.areHorizontallyCodirectional(this.vector, other); + } + + public boolean isCodirectional(DirectionalHorizontalMove other) { + return this.isCodirectional(other.asVector()); + } + + public double distance(Vector other) { + Vector o = other.clone().setY(0); + return this.vector.distance(o); + } + + public double distance(DirectionalHorizontalMove other) { + return this.distance(other.asVector()); + } + + public double angle(Vector other) { + Vector o = other.clone().setY(0); + return (double)this.vector.angle(o); + } + + public double angle(DirectionalHorizontalMove other) { + return this.angle(other.asVector()); + } + + public double dotProduct(Vector other) { + Vector o = other.clone().setY(0); + return Maths.dotProduct(this.vector, o); + } + + public double dotProduct(DirectionalHorizontalMove other) { + return this.dotProduct(other.asVector()); + } + + public Vector crossProduct(Vector other) { + Vector o = other.clone().setY(0); + return this.vector.clone().crossProduct(o); + } + + public Vector crossProduct(DirectionalHorizontalMove other) { + return this.crossProduct(other.asVector()); + } + + public Vector asVector() { + return this.vector.clone(); + } + + public String getMoveString() { + return String.format("[%s, %s]", this.movedX, this.movedZ); + } + + public String getCoordsString() { + return String.format("(%s->%s, %s->%s)", this.oldX, this.newX, this.oldZ, this.newZ); + } + + @Override + public String toString() { + return this.getMoveString() + this.getCoordsString(); + } + + public double getOldX() { + return this.oldX; + } + + public double getOldZ() { + return this.oldZ; + } + + public double getNewX() { + return this.newX; + } + + public double getNewZ() { + return this.newZ; + } + + public double getMovedX() { + return this.movedX; + } + + public double getMovedZ() { + return this.movedZ; + } +} diff --git a/src/main/java/rip/reflex/util/location/JumpStage.java b/src/main/java/rip/reflex/util/location/JumpStage.java new file mode 100644 index 0000000..b6662b1 --- /dev/null +++ b/src/main/java/rip/reflex/util/location/JumpStage.java @@ -0,0 +1,8 @@ +package rip.reflex.util.location; + +public enum JumpStage { + ACCELERATING_UP, + FLOATING, + FALLING, + NOT_JUMPING; +} diff --git a/src/main/java/rip/reflex/util/location/LocationUtils.java b/src/main/java/rip/reflex/util/location/LocationUtils.java new file mode 100644 index 0000000..e79c51b --- /dev/null +++ b/src/main/java/rip/reflex/util/location/LocationUtils.java @@ -0,0 +1,813 @@ +package rip.reflex.util.location; + +import com.comphenix.protocol.wrappers.BlockPosition; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.util.Vector; +import rip.reflex.check.world.ScaffoldCheck; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.Storage; +import rip.reflex.util.math.Maths; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.compatibility.CompatibilityProvider; +import rip.reflex.util.time.Timer; + +public class LocationUtils { + public static boolean isGroundExact(Player p) { + return checkNearbyChunks(p) && isGroundExact(p.getLocation().clone()); + } + + public static boolean isGroundExact(Location l) { + return checkNearbyChunks(l) && isOnGround(l) && l.getY() % 0.0625 == 0.0; + } + + public static boolean isOnGround(Player p) { + return checkNearbyChunks(p) && isOnGround(p.getLocation().clone()); + } + + public static double getAbsoluteVelocityXZ(Player p) { + return getAbsoluteVelocityXZ(p.getVelocity().clone()); + } + + public static double getAbsoluteVelocityXZ(Vector v) { + return Math.abs(v.getX()) + Math.abs(v.getZ()); + } + + public static boolean isTowering(Player p, Stats stats) { + if (stats.hasStat("recentlyPlaced") && !stats.getStat("recentlyPlaced", Storage.class).isEmpty()) { + Object[] recentlyPlaced = stats.getStat("recentlyPlaced", Storage.class).asArray(); + int i = 0; + int fx = 0; + int fy = 0; + int fz = 0; + + for (int j = 0; j < recentlyPlaced.length; j++) { + Block b = (Block)recentlyPlaced[j]; + if (j == 0) { + fx = b.getX(); + fy = b.getY(); + fz = b.getZ(); + } else if (b.getX() == fx && b.getY() > fy && b.getZ() == fz) { + i++; + } + } + + return i >= 3; + } else { + return false; + } + } + + public static boolean isTowering(Storage recentPlaced) { + if (recentPlaced.size() < 4) { + return false; + } else { + BlockPosition first = (BlockPosition)recentPlaced.first(); + int startX = first.getX(); + int startZ = first.getZ(); + int lastY = -1; + + for (Object o : recentPlaced.values()) { + BlockPosition pos = (BlockPosition)o; + if (lastY != -1) { + if (pos.getY() != lastY + 1 || pos.getX() != startX || pos.getZ() != startZ) { + return false; + } + + lastY = pos.getY(); + } else { + lastY = pos.getY(); + } + } + + return true; + } + } + + public static ScaffoldCheck.BridgeState getBridgeState(Storage recentPlaced) { + if (recentPlaced.size() >= 5 && Maths.objects[2] instanceof String) { + BlockPosition prev = (BlockPosition)recentPlaced.first(); + int totalXChange = 0; + int totalYChange = 0; + int totalZChange = 0; + int firstY = prev.getY(); + boolean hasYChange = false; + + for (int i = 1; i < 4; i++) { + BlockPosition cur = (BlockPosition)recentPlaced.get(i); + if (cur.getX() == prev.getX() == (cur.getZ() == prev.getZ())) { + return ScaffoldCheck.BridgeState.NOT_BRIDGING; + } + + if (cur.getY() != firstY) { + hasYChange = true; + } + + totalXChange += Math.abs(cur.getX() - prev.getX()); + totalYChange += cur.getY() == prev.getY() ? 0 : 1; + totalZChange += Math.abs(cur.getZ() - prev.getZ()); + if (totalYChange > 1) { + return ScaffoldCheck.BridgeState.NOT_BRIDGING; + } + + prev = cur; + } + + return Math.abs(totalXChange - totalZChange) > 1 + ? ScaffoldCheck.BridgeState.BRIDGING_HORIZONTALLY + : (hasYChange ? ScaffoldCheck.BridgeState.NOT_BRIDGING : ScaffoldCheck.BridgeState.BRIDGING_DIAGONALLY); + } else { + return ScaffoldCheck.BridgeState.NOT_BRIDGING; + } + } + + public static boolean isBridging(Player p, Stats stats) { + if (stats.hasStat("recentlyPlaced") && !stats.getStat("recentlyPlaced", Storage.class).isEmpty()) { + Object[] recentlyPlaced = stats.getStat("recentlyPlaced", Storage.class).asArray(); + int i = 0; + int fx = 0; + int fy = 0; + int fz = 0; + int xOffset = 0; + int yOffset = 0; + int zOffset = 0; + + for (int j = 0; j < recentlyPlaced.length; j++) { + Block b = (Block)recentlyPlaced[j]; + if (j == 0) { + fx = b.getX(); + fy = b.getY(); + fz = b.getZ(); + } else { + if (b.getX() == fx || b.getZ() == fz) { + i++; + } + + if (b.getX() != fx) { + xOffset += b.getX() - fx; + } + + if (b.getY() != fy) { + yOffset += b.getY() - fy; + } + + if (b.getZ() != fz) { + zOffset += b.getZ() - fz; + } + } + } + + return i >= 3 && (Math.abs(xOffset) < 2 || Math.abs(yOffset) < 2 || Math.abs(zOffset) < 2); + } else { + return false; + } + } + + public static Set getDirectNeighbors(Block b) { + Location l = b.getLocation().clone(); + if (!checkNearbyChunks(l)) { + return new HashSet<>(); + } else { + Set neighbors = new HashSet(); + Block xp = l.clone().add(1.0, 0.0, 0.0).getBlock(); + Block xs = l.clone().add(-1.0, 0.0, 0.0).getBlock(); + Block zp = l.clone().add(0.0, 0.0, 1.0).getBlock(); + Block zs = l.clone().add(0.0, 0.0, -1.0).getBlock(); + if (xp.getType() != Material.AIR) { + neighbors.add(xp); + } + + if (xs.getType() != Material.AIR) { + neighbors.add(xs); + } + + if (zp.getType() != Material.AIR) { + neighbors.add(zp); + } + + if (zs.getType() != Material.AIR) { + neighbors.add(zs); + } + + return neighbors; + } + } + + public static boolean isOnGround(Location l) { + if (!checkNearbyChunks(l)) { + return false; + } else { + Location temp = l.clone(); + temp.setY((double)((int)temp.getY())); + temp.setX(temp.getX() - 1.0); + temp.setZ(temp.getZ() + 1.0); + ArrayList blocks = playerStandsOn(temp, l); + return blocks.size() != 0; + } + } + + public static boolean isCollided(Player player) { + return !isPushable(player) || !isVerticallyPushable(player); + } + + public static boolean isVerticallyPushable(Player p) { + if (!checkNearbyChunks(p)) { + return false; + } else { + Location l = p.getLocation().clone(); + List blocks = new ArrayList<>(); + + for (int x = 0; x < 3; x++) { + Block b2 = l.add((double)x, (double)x, (double)x).getBlock(); + Block b3 = l.add((double)(-x), (double)x, (double)x).getBlock(); + Block b4 = l.add((double)x, (double)(-x), (double)x).getBlock(); + Block b5 = l.add((double)x, (double)x, (double)(-x)).getBlock(); + Block b6 = l.add((double)(-x), (double)x, (double)(-x)).getBlock(); + Block b7 = l.add((double)(-x), (double)(-x), (double)(-x)).getBlock(); + blocks.add(b2); + blocks.add(b3); + blocks.add(b4); + blocks.add(b5); + blocks.add(b6); + blocks.add(b7); + } + + for (Block b : blocks) { + if (b.getType().toString().toLowerCase().contains("web") + || b.getType().equals(Material.LADDER) + || b.getType().equals(Material.VINE) + || b.isLiquid()) { + return false; + } + } + + return l.add(0.0, 2.0, 0.0).getBlock().getType().equals(Material.AIR) && !isInLiquid(p) && isOnGround(p); + } + } + + public static boolean isBelowBlocks(Player p) { + return checkNearbyChunks(p) && isBelowBlocks(p.getLocation().clone()); + } + + public static boolean isBelowBlocks(Location l) { + if (!checkNearbyChunks(l)) { + return false; + } else { + Location x_ = new Location(l.getWorld(), (double)(l.getBlockX() + 1), (double)l.getBlockY(), (double)l.getBlockZ()); + Location _x = new Location(l.getWorld(), (double)(l.getBlockX() - 1), (double)l.getBlockY(), (double)l.getBlockZ()); + Location z_ = new Location(l.getWorld(), (double)l.getBlockX(), (double)l.getBlockY(), (double)(l.getBlockZ() + 1)); + Location _z = new Location(l.getWorld(), (double)l.getBlockX(), (double)l.getBlockY(), (double)(l.getBlockZ() - 1)); + return !l.getBlock().getRelative(BlockFace.UP).getRelative(BlockFace.UP).getType().equals(Material.AIR) + || !x_.getBlock().getRelative(BlockFace.UP).getRelative(BlockFace.UP).getType().equals(Material.AIR) + || !_x.getBlock().getRelative(BlockFace.UP).getRelative(BlockFace.UP).getType().equals(Material.AIR) + || !z_.getBlock().getRelative(BlockFace.UP).getRelative(BlockFace.UP).getType().equals(Material.AIR) + || !_z.getBlock().getRelative(BlockFace.UP).getRelative(BlockFace.UP).getType().equals(Material.AIR); + } + } + + public static boolean blocksAroundIsType(Block block, Material material) { + if (!checkNearbyChunks(block.getLocation())) { + return false; + } else { + for (Block b : blocksAround(block)) { + if (b.getType() == material) { + return true; + } + } + + return false; + } + } + + public static boolean blocksAroundIsSolidMinABU(Block block, int min, List list) { + if (!checkNearbyChunks(block.getLocation())) { + return false; + } else { + int i = 0; + + for (Block b : blocksAround(block)) { + if (list.contains(b.getType())) { + i++; + } + } + + return i >= min; + } + } + + public static Block findBlock(List blocks, Material type) { + return blocks.stream().filter(b -> b.getType() == type).findFirst().orElse(null); + } + + public static boolean containsBlock(List blocks, Material type) { + return findBlock(blocks, type) != null; + } + + public static boolean isStairInverted(Block block) { + if (!block.getType().name().contains("STAIRS")) { + throw new IllegalArgumentException("not a stairs block: " + block.getType()); + } else { + CompatibilityProvider cp = VersionUtils.getCompatibilityProvider(); + return cp.getBisectedBlockHalf(block) == 0; + } + } + + public static ArrayList playerStandsOn(Location location, Location orig) { + return checkNearbyChunks(location) && checkNearbyChunks(orig) ? playerStandsOn(location, new ArrayList<>(), orig) : new ArrayList<>(); + } + + public static ArrayList playerStandsOn(Location location, ArrayList dontremove, Location orig) { + if (!checkNearbyChunks(location)) { + return new ArrayList<>(); + } else { + Block under = orig.getBlock().getRelative(BlockFace.DOWN); + ArrayList allaround = blocksAround(under, true); + ArrayList realarround = new ArrayList<>(); + + for (Block block : allaround) { + Location l = new Location( + block.getWorld(), + mid((double)block.getX()), + max((double)block.getY()), + mid((double)(isPositive((double)block.getZ()) ? block.getZ() - 1 : block.getZ() + 1)) + ); + if (Maths.distance(l, location) < 1.35) { + realarround.add(block); + } + } + + allaround.clear(); + if (under.getType().isSolid()) { + realarround.add(under); + } + + for (Block blockx : (ArrayList)realarround.clone()) { + Block up1 = blockx.getRelative(BlockFace.UP); + if ((up1.getType().isSolid() || up1.getRelative(BlockFace.UP).getType().isSolid() || !blockx.getType().isSolid() || blockx.isLiquid()) + && !dontremove.contains(blockx.getType())) { + realarround.remove(blockx); + } + } + + return realarround; + } + } + + public static double mid(double d) { + return Double.parseDouble(("" + d).replaceAll("\\..{0,99}", ".5")); + } + + private static double max(double d) { + return Double.parseDouble(("" + d).replaceAll("\\..{0,99}", ".99")); + } + + private static boolean isPositive(double d) { + return !("" + d).startsWith("-"); + } + + public static ArrayList blocksAround(Block block) { + return !checkNearbyChunks(block.getLocation()) ? new ArrayList<>() : blocksAround(block, true); + } + + public static List blocksAround3x3x3(Block block) { + if (!checkNearbyChunks(block.getLocation())) { + return new ArrayList<>(); + } else { + List blocks = new ArrayList<>(); + blocks.addAll(blocksAround(block)); + blocks.addAll(blocksAround(block.getRelative(BlockFace.UP))); + blocks.addAll(blocksAround(block.getRelative(BlockFace.DOWN))); + return blocks; + } + } + + public static ArrayList blocksAround(Block block, boolean includeSelf) { + if (!checkNearbyChunks(block.getLocation())) { + return new ArrayList<>(); + } else { + ArrayList list = new ArrayList<>(); + if (includeSelf) { + list.add(block); + } + + list.add(block.getRelative(BlockFace.EAST)); + list.add(block.getRelative(BlockFace.SOUTH)); + list.add(block.getRelative(BlockFace.WEST)); + list.add(block.getRelative(BlockFace.NORTH)); + list.add(block.getRelative(BlockFace.NORTH_EAST)); + list.add(block.getRelative(BlockFace.SOUTH_EAST)); + list.add(block.getRelative(BlockFace.SOUTH_WEST)); + list.add(block.getRelative(BlockFace.NORTH_WEST)); + return list; + } + } + + public static boolean isOnIce(Player player) { + if (checkNearbyChunks(player) && isOnGround(player)) { + for (Block block : playerStandsOn(player.getLocation(), player.getLocation().clone())) { + if (block.getType().toString().toLowerCase().contains("ice")) { + return true; + } + } + + return false; + } else { + return false; + } + } + + public static boolean isPushable(Player player) { + return checkNearbyChunks(player) && isPushable(player.getLocation().clone()); + } + + public static boolean isPushable(LivingEntity entity) { + return checkNearbyChunks(entity.getLocation()) && isPushable(entity.getLocation().clone()); + } + + public static boolean isNearWalls(Player p) { + for (Block block : getBlocksSurroundedBy(p)) { + if (!isBlockPhasable(block, false)) { + return true; + } + } + + return false; + } + + public static boolean isBlockPhasable(Block b, boolean includeLiquids) { + if (b.getType() != Material.AIR && (!includeLiquids || !b.isLiquid())) { + String t = b.getType().name().toLowerCase(); + return t.contains("flower") || t.contains("plant") || t.contains("tall") || t.contains("long_grass") || t.contains("rose") || t.contains("bush"); + } else { + return true; + } + } + + public static List getBlocksSurroundedBy(Player p) { + Location l = p.getEyeLocation().clone(); + if (!checkNearbyChunks(l)) { + return new ArrayList<>(); + } else { + List directlyAround = new ArrayList<>(); + Location below = l.clone(); + below.setY((double)Maths.floor(l.getY()) - 1.0); + directlyAround.addAll(getDirectNeighbors(l.getBlock())); + directlyAround.addAll(getDirectNeighbors(below.getBlock())); + return directlyAround; + } + } + + private List getDirectNeighbours(Block b) { + Location l = b.getLocation(); + List directNeighbours = new ArrayList<>(); + directNeighbours.add(l.getBlock().getRelative(BlockFace.NORTH)); + directNeighbours.add(l.getBlock().getRelative(BlockFace.EAST)); + directNeighbours.add(l.getBlock().getRelative(BlockFace.SOUTH)); + directNeighbours.add(l.getBlock().getRelative(BlockFace.WEST)); + return directNeighbours; + } + + public static boolean isPushable(Location l) { + if (!checkNearbyChunks(l)) { + return false; + } else { + ArrayList blocksAround = new ArrayList<>(); + blocksAround.add(l.getBlock().getRelative(BlockFace.EAST)); + blocksAround.add(l.getBlock().getRelative(BlockFace.EAST_NORTH_EAST)); + blocksAround.add(l.getBlock().getRelative(BlockFace.EAST_SOUTH_EAST)); + blocksAround.add(l.getBlock().getRelative(BlockFace.WEST)); + blocksAround.add(l.getBlock().getRelative(BlockFace.WEST_NORTH_WEST)); + blocksAround.add(l.getBlock().getRelative(BlockFace.WEST_SOUTH_WEST)); + blocksAround.add(l.getBlock().getRelative(BlockFace.SOUTH)); + blocksAround.add(l.getBlock().getRelative(BlockFace.SOUTH_EAST)); + blocksAround.add(l.getBlock().getRelative(BlockFace.SOUTH_SOUTH_EAST)); + blocksAround.add(l.getBlock().getRelative(BlockFace.SOUTH_SOUTH_WEST)); + blocksAround.add(l.getBlock().getRelative(BlockFace.NORTH)); + blocksAround.add(l.getBlock().getRelative(BlockFace.NORTH_EAST)); + blocksAround.add(l.getBlock().getRelative(BlockFace.NORTH_NORTH_EAST)); + blocksAround.add(l.getBlock().getRelative(BlockFace.NORTH_NORTH_WEST)); + Location loc1 = new Location(l.getWorld(), (double)(l.getBlockX() + 1), (double)l.getBlockY(), (double)(l.getBlockZ() + 1)); + Location loc2 = new Location(l.getWorld(), (double)(l.getBlockX() + 1), (double)l.getBlockY(), (double)(l.getBlockZ() - 1)); + Location loc3 = new Location(l.getWorld(), (double)(l.getBlockX() - 1), (double)l.getBlockY(), (double)(l.getBlockZ() + 1)); + Location loc4 = new Location(l.getWorld(), (double)(l.getBlockX() - 1), (double)l.getBlockY(), (double)(l.getBlockZ() - 1)); + blocksAround.add(loc1.getBlock()); + blocksAround.add(loc2.getBlock()); + blocksAround.add(loc3.getBlock()); + blocksAround.add(loc4.getBlock()); + + for (Block block : blocksAround) { + if ((block.getType().isSolid() || block.getType().toString().toLowerCase().contains("web")) && !isBlockPhasable(block, true)) { + return false; + } + } + + return true; + } + } + + public static boolean isClimbing(Player player) { + return checkNearbyChunks(player) + && (player.getLocation().getBlock().getType().equals(Material.LADDER) || player.getLocation().getBlock().getType().equals(Material.VINE)); + } + + public static boolean isOnWater(Player player) { + return checkNearbyChunks(player) && (player.getLocation().getBlock().isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid()); + } + + public static Movement getMovement(Player p, Location from, Location to) { + Vector dir = from.getDirection().clone(); + Location lLeft = from.clone(); + Location lRight = from.clone(); + lLeft.setYaw(lLeft.getYaw() - 90.0F); + lRight.setYaw(lRight.getYaw() + 90.0F); + Vector left = lLeft.clone().getDirection().clone(); + Vector right = lRight.clone().getDirection().clone(); + Vector forward = new Vector(from.getX() + dir.getX(), from.getY() + dir.getY(), from.getZ() + dir.getZ()).clone(); + Vector backward = new Vector(from.getX() - dir.getX(), from.getY() - dir.getY(), from.getZ() - dir.getZ()).clone(); + Vector strafeLeft = new Vector(from.getX() + left.getX(), from.getY() + left.getY(), from.getZ() + left.getZ()).clone(); + Vector strafeRight = new Vector(from.getX() + right.getX(), from.getY() + right.getY(), from.getZ() + right.getZ()).clone(); + Vector vTo = to.toVector().clone(); + double dForward = Maths.horizontalDistance(vTo, forward); + double dBackward = Maths.horizontalDistance(vTo, backward); + double dStrafing = Math.min(Maths.horizontalDistance(vTo, strafeLeft), Maths.horizontalDistance(vTo, strafeRight)); + double closest = Maths.min(dForward, dBackward, dStrafing); + if (closest == dBackward) { + return new Movement(MoveDirection.BACKWARD, dForward, dBackward, dStrafing); + } else { + return closest == dStrafing + && !Maths.matchIn(dForward, 0.75, 0.85) + && !Maths.matchIn(dForward, 1.001, 1.1999) + && dForward >= 0.7 + && !Maths.matchEx(dForward, 0.925, 0.955) + ? new Movement(MoveDirection.STRAFING, dForward, dBackward, dStrafing) + : new Movement(MoveDirection.FORWARD, dForward, dBackward, dStrafing); + } + } + + public static boolean isKnockingBack(Player p, Stats stats) { + Vector velocity = p.getVelocity().clone(); + return !stats.getStat("damageByEntityTracker", Timer.class).hasPassed(1000L) && !isZero(velocity) && !isNaturalGravity(velocity); + } + + public static boolean isVerticalOnly(Vector v) { + return v.getX() == 0.0 && v.getZ() == 0.0; + } + + public static boolean isNaturalGravity(Vector v) { + return Maths.matchIn(v.getY(), -0.07840000152589, -0.07840000152586); + } + + public static boolean isZero(Vector v) { + return v.getX() == 0.0 && v.getY() == 0.0 && v.getZ() == 0.0; + } + + public static boolean isInLiquid(Player p) { + if (!checkNearbyChunks(p)) { + return false; + } else { + Location l = p.getLocation().clone(); + return isOnWater(p) + || l.getBlock().isLiquid() + && l.add(0.0, -1.0, 0.0).getBlock().isLiquid() + && l.add(1.0, 0.0, 0.0).getBlock().isLiquid() + && l.add(0.0, 0.0, 1.0).getBlock().isLiquid() + && l.add(1.0, 0.0, 1.0).getBlock().isLiquid() + && l.add(-1.0, 0.0, -1.0).getBlock().isLiquid() + && l.add(0.0, 0.0, -1.0).getBlock().isLiquid() + && l.add(-1.0, 0.0, 0.0).getBlock().isLiquid() + && l.add(1.0, -1.0, 0.0).getBlock().isLiquid() + && l.add(0.0, -1.0, 1.0).getBlock().isLiquid() + && l.add(1.0, -1.0, 1.0).getBlock().isLiquid() + && l.add(-1.0, -1.0, -1.0).getBlock().isLiquid() + && l.add(0.0, -1.0, -1.0).getBlock().isLiquid() + && l.add(-1.0, -1.0, 0.0).getBlock().isLiquid() + && !isGroundExact(p); + } + } + + public static MoveType getMoveType(Location from, Location to) { + double dy = to.getY() - from.getY(); + if (checkNearbyChunks(from) && checkNearbyChunks(to) && hasHorizontalMove(from, to)) { + if (isGroundExact(from) && isGroundExact(to) || isOnUnstableBlock(from) || isOnUnstableBlock(to)) { + return MoveType.GROUND; + } + + if (isGroundExact(from) && !isGroundExact(to) && dy > 0.0) { + return MoveType.JUMP; + } + + if (isGroundExact(from) && !isGroundExact(to) && dy < 0.0 || !isGroundExact(from) && isGroundExact(to)) { + return MoveType.FALL; + } + + if (!isGroundExact(from) && !isGroundExact(to)) { + return MoveType.MIDAIR; + } + } else if (checkNearbyChunks(from) && checkNearbyChunks(to)) { + return MoveType.ROTATION; + } + + return MoveType.UNKNOWN; + } + + public static boolean isBackwardsMove(PlayerMoveEvent e) { + return e != null && isBackwardsMove(e.getFrom(), e.getTo()); + } + + public static boolean isBackwardsMove(Location from, Location to) { + double xDistance = to.getX() - from.getX(); + double zDistance = to.getX() - from.getX(); + double yaw = (double)from.getYaw(); + return xDistance < 0.0 && zDistance > 0.0 && yaw > 180.0 && yaw < 270.0 + || xDistance < 0.0 && zDistance < 0.0 && yaw > 270.0 && yaw < 360.0 + || xDistance > 0.0 && zDistance < 0.0 && yaw > 0.0 && yaw < 90.0 + || xDistance > 0.0 && zDistance > 0.0 && yaw > 90.0 && yaw < 180.0; + } + + public static boolean hasHorizontalMove(Location from, Location to) { + double dx = to.getX() - from.getX(); + double dz = to.getZ() - from.getZ(); + return dx != 0.0 || dz != 0.0; + } + + public static JumpStage getJumpStage(Location from, Location to) { + MoveType move = getMoveType(from, to); + double dY = to.getY() - from.getY(); + if (Maths.matchIn(dY, 0.41, 0.42)) { + return JumpStage.ACCELERATING_UP; + } else if (!move.equals(MoveType.MIDAIR) && !move.equals(MoveType.FALL) && !move.equals(MoveType.JUMP)) { + return JumpStage.NOT_JUMPING; + } else if (Maths.matchIn(Math.abs(to.getY() - from.getY()), 0, 0.052947322753916)) { + return JumpStage.FLOATING; + } else { + return from.getY() > to.getY() ? JumpStage.FALLING : JumpStage.ACCELERATING_UP; + } + } + + public static boolean isOnUnstableBlock(Player p) { + return isOnUnstableBlock(p.getLocation().clone()); + } + + public static boolean isOnUnstableBlock(Location l) { + if (!checkNearbyChunks(l)) { + return false; + } else { + for (Block b : blocksAround3x3x3(l.getBlock())) { + String t = b.getType().toString().toLowerCase(); + if (!b.getType().isSolid() && !b.getType().equals(Material.AIR) || t.contains("step") || t.contains("stair") || t.contains("web")) { + return true; + } + } + + String t = l.getBlock().getType().toString().toLowerCase(); + String tDown = l.getBlock().getRelative(BlockFace.DOWN).getType().toString().toLowerCase(); + return tDown.contains("stair") || tDown.contains("web") || t.contains("step") || t.contains("web"); + } + } + + public static boolean isNormalBlock(Block b) { + return checkNearbyChunks(b.getLocation()) && isNormalBlock(b.getType()); + } + + public static boolean isNormalBlock(Material m) { + String type = m.toString().toLowerCase(); + return m.isSolid() + && !type.contains("step") + && !type.contains("stair") + && !type.contains("fence") + && !type.contains("pane") + && !type.contains("slab") + && !type.contains("carpet") + && !type.contains("door") + && !type.contains("ladder") + && !type.contains("vine") + && !type.contains("torch") + && !type.contains("anvil") + && !type.contains("chest") + && !type.contains("sign") + && !type.contains("frame") + && !type.contains("skull") + && !type.contains("door") + && !type.contains("comparator") + && !type.contains("repeat") + && !type.contains("sapling") + && !type.contains("dead") + && !type.contains("bed") + && !type.contains("lever") + && !type.contains("button") + && !type.contains("trap") + && !type.contains("enchant") + && !type.contains("piston") + && !type.contains("dispenser") + && !type.contains("note") + && !type.contains("detector") + && !type.contains("dropper") + && !type.contains("hopper") + && !type.contains("beacon") + && !type.contains("juke") + && !type.contains("craft") + && !type.contains("furnace") + && !type.contains("redstone") + && !type.contains("cauldron") + && !type.contains("pot") + && !type.contains("cake") + && !type.contains("diode") + && !type.contains("brewing"); + } + + public static boolean isNearbyBlock(Player p, Material type, int range) { + Location l = getBlockLocation(p); + + for (int i = 0; i <= range; i++) { + Block[] blocks = new Block[]{ + l.clone().add((double)i, (double)i, (double)i).getBlock(), + l.clone().add((double)(-i), (double)i, (double)i).getBlock(), + l.clone().add((double)i, (double)i, (double)(-i)).getBlock(), + l.clone().add((double)(-i), (double)i, (double)(-i)).getBlock(), + l.clone().add((double)i, (double)(-i), (double)i).getBlock(), + l.clone().add((double)(-i), (double)(-i), (double)i).getBlock(), + l.clone().add((double)i, (double)(-i), (double)(-i)).getBlock(), + l.clone().add((double)(-i), (double)(-i), (double)(-i)).getBlock() + }; + + for (Block b : blocks) { + if (b.getType() == type) { + return true; + } + } + } + + return false; + } + + public static boolean isNearbyBlocks(Player p, int range, Material... types) { + Location l = getBlockLocation(p); + + for (int i = 0; i <= range; i++) { + Block[] blocks = new Block[]{ + l.clone().add((double)i, (double)i, (double)i).getBlock(), + l.clone().add((double)(-i), (double)i, (double)i).getBlock(), + l.clone().add((double)i, (double)i, (double)(-i)).getBlock(), + l.clone().add((double)(-i), (double)i, (double)(-i)).getBlock(), + l.clone().add((double)i, (double)(-i), (double)i).getBlock(), + l.clone().add((double)(-i), (double)(-i), (double)i).getBlock(), + l.clone().add((double)i, (double)(-i), (double)(-i)).getBlock(), + l.clone().add((double)(-i), (double)(-i), (double)(-i)).getBlock() + }; + + for (Block b : blocks) { + for (Material type : types) { + if (b.getType() == type) { + return true; + } + } + } + } + + return false; + } + + public static Location getBlockLocation(Player p) { + Location l = p.getLocation().clone(); + return new Location(l.getWorld(), (double)l.getBlockX(), (double)l.getBlockY(), (double)l.getBlockZ()); + } + + public static boolean checkNearbyChunks(Player p) { + return checkNearbyChunks(p.getLocation().clone()); + } + + public static boolean checkNearbyChunks(Entity e) { + return checkNearbyChunks(e.getLocation().clone()); + } + + public static boolean checkNearbyChunks(Location l) { + if (l == null) { + return false; + } else { + Location location = l.clone(); + World world = location.getWorld(); + if (world == null) { + return false; + } else { + int x = location.getBlockX() >> 4; + int z = location.getBlockZ() >> 4; + return world.isChunkLoaded(x, z) + && world.isChunkLoaded(x + 1, z + 1) + && world.isChunkLoaded(x - 1, z + 1) + && world.isChunkLoaded(x + 1, z - 1) + && world.isChunkLoaded(x - 1, z - 1); + } + } + } +} diff --git a/src/main/java/rip/reflex/util/location/MoveDirection.java b/src/main/java/rip/reflex/util/location/MoveDirection.java new file mode 100644 index 0000000..6f82e89 --- /dev/null +++ b/src/main/java/rip/reflex/util/location/MoveDirection.java @@ -0,0 +1,28 @@ +package rip.reflex.util.location; + +public enum MoveDirection { + FORWARD, + BACKWARD, + STRAFING; + + @Override + public String toString() { + String color = "§"; + switch (this) { + case FORWARD: + color = color + "a"; + break; + case BACKWARD: + color = color + "c"; + break; + case STRAFING: + color = color + "b"; + } + + return color + super.toString(); + } + + public String shorten() { + return "" + super.toString().toLowerCase().charAt(0); + } +} diff --git a/src/main/java/rip/reflex/util/location/MoveType.java b/src/main/java/rip/reflex/util/location/MoveType.java new file mode 100644 index 0000000..5b6e65c --- /dev/null +++ b/src/main/java/rip/reflex/util/location/MoveType.java @@ -0,0 +1,10 @@ +package rip.reflex.util.location; + +public enum MoveType { + JUMP, + FALL, + GROUND, + MIDAIR, + ROTATION, + UNKNOWN; +} diff --git a/src/main/java/rip/reflex/util/location/Movement.java b/src/main/java/rip/reflex/util/location/Movement.java new file mode 100644 index 0000000..7028c89 --- /dev/null +++ b/src/main/java/rip/reflex/util/location/Movement.java @@ -0,0 +1,46 @@ +package rip.reflex.util.location; + +public class Movement { + private static final Movement apinstance = new Movement(null, 0.0, 0.0, 0.0); + private final MoveDirection direction; + private final double forwardFactor; + private final double backwardFactor; + private final double strafingFactor; + private String id = "1"; + private String resource = "21122"; + + public Movement(MoveDirection direction, double forwardFactor, double backwardFactor, double strafingFactor) { + this.direction = direction; + this.forwardFactor = forwardFactor; + this.backwardFactor = backwardFactor; + this.strafingFactor = strafingFactor; + } + + public static Movement getApinstance() { + return apinstance; + } + + public MoveDirection getDirection() { + return this.direction; + } + + public double getForwardFactor() { + return this.forwardFactor; + } + + public double getBackwardFactor() { + return this.backwardFactor; + } + + public double getStrafingFactor() { + return this.strafingFactor; + } + + public String getId() { + return this.id; + } + + public String getResource() { + return this.resource; + } +} diff --git a/src/main/java/rip/reflex/util/loop/Loop.java b/src/main/java/rip/reflex/util/loop/Loop.java new file mode 100644 index 0000000..3558993 --- /dev/null +++ b/src/main/java/rip/reflex/util/loop/Loop.java @@ -0,0 +1,5 @@ +package rip.reflex.util.loop; + +public interface Loop { + void run(Object target); +} diff --git a/src/main/java/rip/reflex/util/loop/LoopHelper.java b/src/main/java/rip/reflex/util/loop/LoopHelper.java new file mode 100644 index 0000000..bc49bb5 --- /dev/null +++ b/src/main/java/rip/reflex/util/loop/LoopHelper.java @@ -0,0 +1,39 @@ +package rip.reflex.util.loop; + +import org.bukkit.Bukkit; +import rip.reflex.util.data.Stats; +import rip.reflex.util.loop.impl.PlayerLoop; +import rip.reflex.util.loop.impl.StatsLoop; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class LoopHelper { + public static void loopPlayers(PlayerLoop loop) { + Bukkit.getOnlinePlayers().forEach(loop::run); + } + + public static void loopStats(StatsLoop loop) { + if (loop != null) { + Bukkit.getOnlinePlayers().forEach(p -> loop.run(Stats.of(p))); + } + } + + public static void loopPermitted(PlayerLoop loop, String permission) { + if (loop != null && permission != null) { + Bukkit.getOnlinePlayers().stream().filter(p -> Stats.of(p).hasPermission(permission)).forEach(loop::run); + } + } + + public static void loopPlayersEvery(PlayerLoop loop, int ticks) { + if (loop != null && ticks >= 1) { + ReflexScheduler.async().runTimer(ReflexRunnable.simple("PlayerLoop" + Strings.random(5), () -> loopPlayers(loop)), ticks); + } + } + + public static void loopStatsEvery(StatsLoop loop, int ticks) { + if (loop != null && ticks >= 1) { + ReflexScheduler.async().runTimer(ReflexRunnable.simple("StatLoop" + Strings.random(5), () -> loopStats(loop)), ticks); + } + } +} diff --git a/src/main/java/rip/reflex/util/loop/impl/PlayerLoop.java b/src/main/java/rip/reflex/util/loop/impl/PlayerLoop.java new file mode 100644 index 0000000..945b4fc --- /dev/null +++ b/src/main/java/rip/reflex/util/loop/impl/PlayerLoop.java @@ -0,0 +1,7 @@ +package rip.reflex.util.loop.impl; + +import org.bukkit.entity.Player; + +public interface PlayerLoop { + void run(Player player); +} diff --git a/src/main/java/rip/reflex/util/loop/impl/StatsLoop.java b/src/main/java/rip/reflex/util/loop/impl/StatsLoop.java new file mode 100644 index 0000000..8a1165d --- /dev/null +++ b/src/main/java/rip/reflex/util/loop/impl/StatsLoop.java @@ -0,0 +1,7 @@ +package rip.reflex.util.loop.impl; + +import rip.reflex.util.data.Stats; + +public interface StatsLoop { + void run(Stats stats); +} diff --git a/src/main/java/rip/reflex/util/machinelearning/Classification.java b/src/main/java/rip/reflex/util/machinelearning/Classification.java new file mode 100644 index 0000000..9cada27 --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/Classification.java @@ -0,0 +1,43 @@ +package rip.reflex.util.machinelearning; + +import java.util.ArrayList; + +public class Classification { + private final int badPatterns; + private final double confidence; + private final ArrayList topMatched; + private final int cheatPoints; + private final String cheatAttributes; + + public Classification(int badPatterns, double confidence, ArrayList topMatched, int cheatPoints, String cheatAttributes) { + this.badPatterns = badPatterns; + this.confidence = confidence; + this.topMatched = badPatterns > 0 ? topMatched : null; + this.cheatPoints = cheatPoints; + this.cheatAttributes = cheatAttributes; + } + + public double confidence() { + return this.confidence; + } + + public int countBadPatterns() { + return this.badPatterns; + } + + public ArrayList topMatched() { + return this.topMatched; + } + + public Dataset bestMatched() { + return this.topMatched.isEmpty() ? null : this.topMatched.get(0); + } + + public int getCheatPoints() { + return this.cheatPoints; + } + + public String getCheatAttributes() { + return this.cheatAttributes; + } +} diff --git a/src/main/java/rip/reflex/util/machinelearning/Classifier.java b/src/main/java/rip/reflex/util/machinelearning/Classifier.java new file mode 100644 index 0000000..9ca8174 --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/Classifier.java @@ -0,0 +1,1603 @@ +package rip.reflex.util.machinelearning; + +import java.io.File; +import java.net.MalformedURLException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import me.darksidecode.e2eep4j.E2EKey; +import me.darksidecode.e2eep4j.api.E2EEP4J; +import me.darksidecode.e2eep4j.util.Convert; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.api.db.DataImpl; +import rip.reflex.api.event.ReflexHeurSnapshotEvent; +import rip.reflex.util.crypto.Encryptor; +import rip.reflex.util.machinelearning.layer.InputLayer; +import rip.reflex.util.machinelearning.layer.OutputLayer; +import rip.reflex.util.machinelearning.layer.SigmoidLayer; +import rip.reflex.util.machinelearning.sync.DBDataSync; +import rip.reflex.util.machinelearning.sync.DataSync; +import rip.reflex.util.machinelearning.sync.DefaultHashMap; +import rip.reflex.util.machinelearning.sync.FileSync; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.misc.Unzipper; + +public class Classifier { + private static final ArrayList> netlist = new ArrayList<>(); + private static final ArrayList net1 = new ArrayList<>(); + private static final ArrayList net2 = new ArrayList<>(); + private static final ArrayList net3 = new ArrayList<>(); + private static final ArrayList net4 = new ArrayList<>(); + private static final ArrayList net5 = new ArrayList<>(); + private static final ArrayList net6 = new ArrayList<>(); + private static final ArrayList net7 = new ArrayList<>(); + public static int checksCount = 0; + private static int _LOL_ = -419293; + private static Object e2e = null; + private static final byte[] _KEK_ = new byte[]{-20, 11, -6, -117, -49, getNeg13B(), 29, 8}; + + public static void init() { + netlist.forEach(ArrayList::clear); + netlist.clear(); + netlist.add(net1); + netlist.add(net2); + netlist.add(net3); + netlist.add(net4); + netlist.add(net5); + netlist.add(net6); + netlist.add(net7); + + try { + loadData(); + } catch (MalformedURLException ex) { + throw new RuntimeException(ex); + } + + for (ArrayList net : netlist) { + net.sort(Comparator.comparingInt(Dataset::compareValue)); + } + } + + private static byte[] encryptDataset(byte[] ds) { + byte[] b = E2EEP4J.encryptBytes(ds, Misc.castSafely(getDSKey())); + + for (int i = 0; i < b.length; i++) { + b[i] = (byte)(b[i] ^ getIntNeg13() ^ i); + } + + return (byte[])b.clone(); + } + + private static int getIntNeg13() { + return getNeg13(); + } + + private static Object getDSKey() { + if (_LOL_ % 2 == 0) { + if (e2e != null && e2e instanceof E2EKey) { + _LOL_ -= 3; + return getDSKey(); + } + + e2e = new byte[]{23, -19, 110, -7, -4, 68, 90, -12}; + } else { + e2e = Convert.bytes2e2ekey( + new byte[]{ + -84, + -19, + 0, + 5, + 117, + 114, + 0, + 19, + 91, + 76, + 106, + 97, + 118, + 97, + 46, + 108, + 97, + 110, + 103, + 46, + 79, + 98, + 106, + 101, + 99, + 116, + 59, + -112, + -50, + 88, + -97, + 16, + 115, + 41, + 108, + 2, + 0, + 0, + 120, + 112, + 0, + 0, + 0, + 70, + 115, + 114, + 0, + 14, + 106, + 97, + 118, + 97, + 46, + 108, + 97, + 110, + 103, + 46, + 66, + 121, + 116, + 101, + -100, + 78, + 96, + -124, + -18, + 80, + -11, + 28, + 2, + 0, + 1, + 66, + 0, + 5, + 118, + 97, + 108, + 117, + 101, + 120, + 114, + 0, + 16, + 106, + 97, + 118, + 97, + 46, + 108, + 97, + 110, + 103, + 46, + 78, + 117, + 109, + 98, + 101, + 114, + -122, + -84, + -107, + 29, + 11, + -108, + -32, + -117, + 2, + 0, + 0, + 120, + 112, + -68, + 115, + 113, + 0, + 126, + 0, + 2, + 64, + 115, + 113, + 0, + 126, + 0, + 2, + -44, + 115, + 113, + 0, + 126, + 0, + 2, + -106, + 115, + 113, + 0, + 126, + 0, + 2, + 56, + 113, + 0, + 126, + 0, + 6, + 115, + 113, + 0, + 126, + 0, + 2, + 115, + 115, + 113, + 0, + 126, + 0, + 2, + 57, + 115, + 113, + 0, + 126, + 0, + 2, + -81, + 115, + 113, + 0, + 126, + 0, + 2, + 79, + 115, + 113, + 0, + 126, + 0, + 2, + -122, + 115, + 113, + 0, + 126, + 0, + 2, + 24, + 115, + 113, + 0, + 126, + 0, + 2, + 5, + 115, + 113, + 0, + 126, + 0, + 2, + 27, + 115, + 113, + 0, + 126, + 0, + 2, + -31, + 115, + 113, + 0, + 126, + 0, + 2, + -23, + 115, + 113, + 0, + 126, + 0, + 2, + 60, + 115, + 113, + 0, + 126, + 0, + 2, + 65, + 115, + 113, + 0, + 126, + 0, + 2, + 32, + 115, + 113, + 0, + 126, + 0, + 2, + -46, + 115, + 113, + 0, + 126, + 0, + 2, + -71, + 115, + 113, + 0, + 126, + 0, + 2, + -15, + 115, + 113, + 0, + 126, + 0, + 2, + 127, + 115, + 113, + 0, + 126, + 0, + 2, + -124, + 115, + 113, + 0, + 126, + 0, + 2, + 87, + 113, + 0, + 126, + 0, + 10, + 115, + 113, + 0, + 126, + 0, + 2, + 54, + 115, + 113, + 0, + 126, + 0, + 2, + -27, + 115, + 113, + 0, + 126, + 0, + 2, + 7, + 115, + 113, + 0, + 126, + 0, + 2, + 91, + 113, + 0, + 126, + 0, + 19, + 115, + 113, + 0, + 126, + 0, + 2, + -2, + 115, + 113, + 0, + 126, + 0, + 2, + 9, + 115, + 113, + 0, + 126, + 0, + 2, + -76, + 115, + 113, + 0, + 126, + 0, + 2, + 33, + 113, + 0, + 126, + 0, + 30, + 115, + 113, + 0, + 126, + 0, + 2, + -57, + 115, + 113, + 0, + 126, + 0, + 2, + 119, + 115, + 113, + 0, + 126, + 0, + 2, + -42, + 115, + 113, + 0, + 126, + 0, + 2, + 16, + 115, + 113, + 0, + 126, + 0, + 2, + 4, + 113, + 0, + 126, + 0, + 20, + 115, + 113, + 0, + 126, + 0, + 2, + -51, + 115, + 113, + 0, + 126, + 0, + 2, + 83, + 115, + 113, + 0, + 126, + 0, + 2, + 76, + 115, + 113, + 0, + 126, + 0, + 2, + -62, + 115, + 113, + 0, + 126, + 0, + 2, + -1, + 115, + 113, + 0, + 126, + 0, + 2, + 28, + 115, + 113, + 0, + 126, + 0, + 2, + 8, + 113, + 0, + 126, + 0, + 24, + 113, + 0, + 126, + 0, + 39, + 113, + 0, + 126, + 0, + 19, + 115, + 113, + 0, + 126, + 0, + 2, + 0, + 115, + 113, + 0, + 126, + 0, + 2, + -19, + 115, + 113, + 0, + 126, + 0, + 2, + -102, + 115, + 113, + 0, + 126, + 0, + 2, + 70, + 113, + 0, + 126, + 0, + 6, + 115, + 113, + 0, + 126, + 0, + 2, + 71, + 115, + 113, + 0, + 126, + 0, + 2, + 89, + 115, + 113, + 0, + 126, + 0, + 2, + 11, + 115, + 113, + 0, + 126, + 0, + 2, + 40, + 115, + 113, + 0, + 126, + 0, + 2, + 48, + 115, + 113, + 0, + 126, + 0, + 2, + 14, + 115, + 113, + 0, + 126, + 0, + 2, + -54, + 117, + 114, + 0, + 2, + 91, + 73, + 77, + -70, + 96, + 38, + 118, + -22, + -78, + -91, + 2, + 0, + 0, + 120, + 112, + 0, + 0, + 0, + 27, + 0, + 0, + 1, + -74, + 2, + -109, + -42, + -40, + 0, + 0, + 91, + 126, + 0, + 0, + 0, + 123, + 0, + 6, + -107, + 74, + 0, + 0, + 91, + 127, + 0, + 0, + 1, + 106, + 0, + 1, + 93, + 3, + 0, + 0, + 97, + -1, + 0, + 0, + 31, + 14, + 0, + 1, + 28, + -73, + 0, + 1, + 68, + 0, + 0, + 0, + 93, + 121, + 0, + 0, + 112, + -33, + 0, + 0, + 68, + 109, + 0, + 0, + -40, + -87, + 0, + 0, + 117, + -39, + 0, + 0, + 88, + 3, + 0, + 1, + 83, + 127, + 0, + 0, + -86, + 85, + 0, + 0, + -128, + -110, + 0, + 1, + 17, + 87, + 0, + 0, + -75, + 103, + 0, + 1, + 73, + 47, + 0, + 1, + 74, + 15, + 0, + 0, + 123, + 9, + 0, + 1, + 46, + 48, + 117, + 113, + 0, + 126, + 0, + 59, + 0, + 0, + 0, + 28, + 0, + 0, + 7, + -18, + 0, + 0, + 16, + -26, + 0, + 0, + 25, + -120, + 0, + 0, + 1, + 106, + 0, + 0, + 1, + 2, + 0, + 0, + 0, + 8, + 0, + 50, + -31, + 35, + -1, + -1, + -1, + -123, + 0, + 1, + 71, + -46, + 0, + 0, + 86, + 82, + 0, + 0, + -9, + 29, + 0, + 0, + -70, + -18, + 0, + 0, + 39, + -34, + 0, + 1, + 54, + -31, + 0, + 1, + 57, + 58, + 0, + 0, + 49, + 102, + 0, + 1, + 76, + 60, + 0, + 0, + 110, + 84, + 0, + 1, + 63, + 109, + 0, + 0, + -17, + -96, + 0, + 0, + -19, + 42, + 0, + 0, + 34, + -14, + 0, + 1, + 25, + 33, + 0, + 1, + 74, + -112, + 0, + 0, + 57, + 124, + 0, + 0, + -124, + 1, + 0, + 0, + -8, + -2, + 0, + 1, + 78, + -78, + 117, + 113, + 0, + 126, + 0, + 59, + 0, + 0, + 0, + 27, + 0, + 0, + 126, + 29, + 0, + 0, + 2, + -102, + 0, + 5, + 33, + 98, + 0, + 9, + -128, + -64, + 0, + 0, + 1, + -38, + 0, + 0, + 0, + 7, + 0, + 0, + 19, + 11, + 0, + 0, + -36, + -45, + 0, + 0, + 94, + 68, + 0, + 0, + -39, + 10, + 0, + 0, + 15, + 12, + 0, + 0, + 122, + 98, + 0, + 0, + 58, + 70, + 0, + 0, + -4, + 84, + 0, + 0, + -18, + -105, + 0, + 0, + -60, + -1, + 0, + 0, + 73, + 109, + 0, + 1, + 115, + 4, + 0, + 1, + 98, + 63, + 0, + 0, + -80, + -87, + 0, + 1, + 116, + -90, + 0, + 1, + 49, + 111, + 0, + 0, + 22, + -45, + 0, + 0, + 32, + 75, + 0, + 0, + -25, + 93, + 0, + 1, + 117, + 6, + 0, + 0, + 98, + -8, + 117, + 113, + 0, + 126, + 0, + 59, + 0, + 0, + 0, + 27, + 0, + 0, + 70, + -39, + 0, + 0, + 24, + -67, + 0, + 0, + -6, + -13, + 0, + 0, + 0, + 52, + 0, + 113, + -54, + -93, + 0, + 0, + -119, + -85, + 0, + 0, + 13, + 97, + 0, + 0, + 25, + 3, + 0, + 1, + 41, + -25, + 0, + 0, + -84, + -107, + 0, + 0, + -92, + 70, + 0, + 0, + -8, + -124, + 0, + 0, + 113, + -59, + 0, + 0, + 91, + 98, + 0, + 0, + 54, + -26, + 0, + 0, + 114, + 12, + 0, + 0, + -101, + -125, + 0, + 0, + -114, + -37, + 0, + 0, + -101, + 114, + 0, + 1, + 5, + 81, + 0, + 0, + 29, + 13, + 0, + 0, + -46, + -1, + 0, + 1, + 38, + -3, + 0, + 0, + 98, + -84, + 0, + 1, + 11, + -64, + 0, + 1, + 50, + 71, + 0, + 1, + 76, + -41, + 117, + 113, + 0, + 126, + 0, + 59, + 0, + 0, + 0, + 25, + -1, + -1, + 106, + -104, + 0, + 0, + 0, + 3, + 0, + 0, + 2, + -121, + 0, + 0, + 2, + 44, + 0, + 0, + 1, + -69, + 0, + 0, + 43, + 90, + 0, + 0, + 8, + -92, + 0, + 0, + 57, + -112, + 0, + 0, + 33, + -84, + 0, + 1, + 62, + -31, + 0, + 0, + 13, + 38, + 0, + 0, + 111, + -79, + 0, + 0, + -14, + -44, + 0, + 0, + -87, + 102, + 0, + 0, + 92, + 21, + 0, + 0, + -105, + 21, + 0, + 0, + -101, + 60, + 0, + 1, + 1, + -3, + 0, + 0, + 89, + 48, + 0, + 1, + 39, + -50, + 0, + 0, + -108, + -27, + 0, + 0, + -8, + -117, + 0, + 0, + 41, + -73, + 0, + 1, + 9, + -70, + 0, + 1, + 18, + 79, + 117, + 113, + 0, + 126, + 0, + 59, + 0, + 0, + 0, + 31, + 0, + 0, + 15, + 103, + 0, + 0, + 124, + 97, + 0, + 0, + 0, + -2, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 67, + 0, + 0, + 2, + -5, + 0, + 0, + 0, + 5, + 0, + 0, + 4, + -1, + 0, + 0, + 0, + 25, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 56, + 0, + 0, + -30, + 97, + 0, + 0, + -83, + -88, + 0, + 0, + 9, + -23, + 0, + 0, + 111, + 55, + 0, + 1, + 1, + -60, + 0, + 0, + -60, + 4, + 0, + 1, + 65, + 52, + 0, + 1, + 91, + -84, + 0, + 0, + 53, + -48, + 0, + 1, + 79, + -7, + 0, + 0, + -110, + -61, + 0, + 0, + 81, + -68, + 0, + 1, + 25, + -102, + 0, + 1, + 56, + 78, + 0, + 0, + 13, + -22, + 0, + 0, + -118, + 31, + 0, + 0, + 98, + -117, + 0, + 1, + 96, + 16, + 0, + 0, + 113, + 59, + 0, + 0, + 55, + 39 + } + ); + _LOL_ += 3; + if (_LOL_ % 2 != 0) { + e2e = new byte[]{99, -38, 62, 1, 7, 121, -17, 43}; + } + } + + return e2e == null ? _KEK_ : e2e; + } + + private static T getNeg13() { + int r = 8; + double x = 5.0; + double y = 7.0; + double abc = x * y - 2.0; + + while (abc > 25.0) { + abc--; + } + + while (abc % 1.0 != 0.0) { + abc -= 5.0; + } + + double n = Math.sqrt(abc) - 10.0 - 2.0 * x; + int k = (int)y; + int v = (int)n + r; + return (T)Integer.valueOf(v - k + 1); + } + + public static byte[] encrypt(Dataset ds) { + try { + StringBuilder save = new StringBuilder(); + save.append(ds.getName()); + save.append('\n'); + save.append(ds.isLegit()); + save.append('\n'); + + for (ArrayList list : ds.getData().values()) { + StringBuilder v = new StringBuilder("" + list.get(0)); + int appended = 0; + if (list.size() > 1) { + for (int x = 1; x < list.size(); x++) { + v.append(", ").append(list.get(x)); + appended++; + } + } + + while (appended < 200) { + v.append(", ").append(0.0); + appended++; + } + + save.append(v.toString()); + save.append('\n'); + } + + return encryptDataset(save.toString().getBytes("UTF-8")); + } catch (Exception ex) { + throw new RuntimeException("Heur snapshot save failure (" + ds.getName() + ")", ex); + } + } + + private static void loadData() throws MalformedURLException { + if (!Reflex.getReflex().getCloudService().isConnected()) { + Reflex.getReflex().info("Hold on: performing magic... This might take up to a few minutes. API and some checks will not work until complete."); + Reflex.getReflex().info("-----------------------------------------------"); + Reflex.getReflex().info(" HINT:"); + Reflex.getReflex() + .info(" Servers which use Reflex Cloud Computings service skip this as the magic is done on our side! Learn more about Cloud on our overview page"); + Reflex.getReflex().info("-----------------------------------------------"); + } + + final HashMap> map = new DefaultHashMap<>(ArrayList::new); + DataSync sync; + switch (Reflex.getReflex().getUsedDB()) { + case MYSQL: + sync = new DBDataSync(Reflex.getReflex().getDataImpl(), Reflex.getReflex().getSyncURL(), "data.zip") { + @Override + protected void useInstant(byte[] data) { + new Unzipper(data, (e, arr) -> { + String[] split = e.getName().split("/"); + String key = split[split.length - 3] + "." + split[split.length - 2]; + List list = map.get(key); + list.add(arr); + }).exec(); + } + + @Override + protected void save(DataImpl impl, byte[] data, String hash) throws Exception { + super.save(impl, Encryptor.encrypt(data), hash); + } + + @Override + protected byte[] load(DataImpl impl) throws Exception { + return Encryptor.decrypt(super.load(impl)); + } + }; + break; + case UNKNOWN: + sync = new FileSync(new File(Reflex.getReflex().getWorkingDir()), Reflex.getReflex().getSyncURL(), "data.zip", false) { + @Override + protected void useInstant(byte[] data) { + new Unzipper(data, (e, arr) -> { + String[] split = e.getName().split("/"); + String key = split[split.length - 3] + "." + split[split.length - 2]; + List list = map.get(key); + list.add(arr); + }).exec(); + } + + @Override + protected void save(File localFile, byte[] data) throws Exception { + super.save(localFile, Encryptor.encrypt(data)); + } + + @Override + protected byte[] load(File localFile) throws Exception { + return Encryptor.decrypt(super.load(localFile)); + } + }; + break; + default: + sync = null; + } + + if (sync.needSync()) { + sync.download(); + } else { + sync.loadLocal(); + } + + for (int i = 0; i < netlist.size(); i++) { + for (byte[] arr : map.get("lessons" + (i + 1) + ".hacks")) { + netlist.get(i).add(Dataset.valueOf(new String(arr))); + } + + for (byte[] arr : map.get("lessons" + (i + 1) + ".legit")) { + netlist.get(i).add(Dataset.valueOf(new String(arr))); + } + } + + for (int i = 0; i < netlist.size() - 1; i++) { + netlist.get(i).clear(); + } + + Reflex.getReflex().setDataVersion(sync.getVersion()); + if (!Reflex.getReflex().getCloudService().isConnected()) { + Reflex.getReflex().info("Done"); + } + } + + private static byte getNeg13B() { + return Byte.valueOf("-13"); + } + + public static void debugHeur(boolean legit, Dataset ds, Player p, int level) { + if (level != 0) { + byte[] body = encrypt(ds); + if (level >= 1) { + Bukkit.getPluginManager().callEvent(new ReflexHeurSnapshotEvent(p, legit, ds.getName(), (byte[])body.clone())); + } + + if (level == 2 || level == 3 && legit || level == 4 && !legit) { + saveDataset(ds.getName(), body); + } + } + } + + private static void saveDataset(String id, byte[] body) { + try { + Files.write(Reflex.getReflex().getReflexFile("/heur/" + id).toPath(), body); + } catch (Exception ex) { + throw new RuntimeException("Failed to save a " + body.length + " bytes snapshot ID " + id, ex); + } + } + + public static Classification classify(Dataset dataset) { + if (netlist.size() < 7) { + return new Classification(0, 0.0, null, 0, ""); + } else { + checksCount++; + ArrayList topMatched = new ArrayList<>(); + float confidence = 0.0F; + ArrayList net = netlist.get(6); + InputLayer input = new InputLayer(dataset); + input.learn(net); + input.computeOutput(); + OutputLayer output = input.getOutput(); + SigmoidLayer sigmoid = output.getSigmoid(); + sigmoid.computeOutput(); + output.learn(net); + output.computeOutput(); + Dataset[] winners = output.getWinners(); + float[] probabilities = sigmoid.probabilityChances(); + int badPatterns = (int)Arrays.stream(winners).filter(ds -> !ds.isLegit()).count(); + topMatched.addAll(Arrays.asList(winners)); + + for (int i = 0; i < winners.length; i++) { + if (!winners[i].isLegit()) { + confidence += probabilities[i]; + } + } + + confidence = Math.max(0.0F, Math.min(100.0F, confidence)); + checksCount = Math.max(0, checksCount - 1); + input.clear(); + sigmoid.clear(); + output.clear(); + return new Classification(badPatterns, (double)confidence, topMatched, input.getCheatPoints(), input.getCheatAttributes()); + } + } + + public static void crash(String stage, ComputeError cause) { + alert("---------------------------------------------------------"); + alert("// Something went wrong o:"); + alert("Current stage: " + stage); + alert(" "); + + for (StackTraceElement element : cause.getStackTrace()) { + String s = element.toString(); + if (s.contains("rip.reflex")) { + alert(" -> " + s); + } + } + + alert(" "); + alert("Reflex will be disabled in order to avoid fatal issues."); + alert("Please open a report at go.reflex.rip/bug"); + alert("---------------------------------------------------------"); + Bukkit.getPluginManager().disablePlugin(Reflex.getReflex()); + } + + public static void alert(String s) { + System.err.println("(!) " + s); + } + + public static ArrayList> getNetlist() { + return netlist; + } +} diff --git a/src/main/java/rip/reflex/util/machinelearning/ComputeError.java b/src/main/java/rip/reflex/util/machinelearning/ComputeError.java new file mode 100644 index 0000000..917226a --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/ComputeError.java @@ -0,0 +1,10 @@ +package rip.reflex.util.machinelearning; + +public class ComputeError extends Error { + public ComputeError() { + } + + public ComputeError(String message) { + super(message); + } +} diff --git a/src/main/java/rip/reflex/util/machinelearning/Dataset.java b/src/main/java/rip/reflex/util/machinelearning/Dataset.java new file mode 100644 index 0000000..aedeff2 --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/Dataset.java @@ -0,0 +1,85 @@ +package rip.reflex.util.machinelearning; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.serialization.ManualSerializable; + +public class Dataset implements ManualSerializable { + private final HashMap> data; + private final String name; + private boolean legit; + + public Dataset(String name, HashMap> data, boolean legit) { + this.name = name; + this.data = data; + this.legit = legit; + } + + public static ArrayList dList(Double... d) { + ArrayList dl = new ArrayList<>(); + Collections.addAll(dl, d); + return dl; + } + + public static Dataset deserialize(List list) { + return new Dataset((String)list.remove(0), (HashMap>)list.remove(0), (Boolean)list.remove(0)); + } + + public static Dataset valueOf(String data) { + String name = data.split("\n")[0]; + String legit = data.split("\n")[1]; + HashMap> values = new HashMap<>(); + String valuesStr = data.split(legit + "\n")[1]; + + for (int i = 0; i < valuesStr.split("\n").length; i++) { + values.put(new KeyInfo().getKey(i), parseValues(valuesStr.split("\n")[i])); + } + + return new Dataset(name, values, Boolean.valueOf(legit)); + } + + private static ArrayList parseValues(String string) { + return Arrays.stream(string.split(", ")).map(Double::valueOf).collect(Collectors.toCollection(ArrayList::new)); + } + + @Override + public List serialize() { + ArrayList list = new ArrayList<>(); + list.add(this.name); + list.add((Serializable)Misc.>copyMap(this.data, false)); + list.add(this.legit); + return list; + } + + public Dataset setLegit(boolean legit) { + this.legit = legit; + return this; + } + + public int compareValue() { + Integer i = Integer.valueOf(this.name.substring(1)); + return i + (this.name.startsWith("P") ? 0 : 100000); + } + + public String getName() { + return this.name; + } + + public boolean isLegit() { + return this.legit; + } + + public HashMap> getData() { + return this.data; + } + + public Dataset clone() { + return new Dataset(this.name, (HashMap>)Misc.>copyMap(this.data, false), this.legit); + } +} diff --git a/src/main/java/rip/reflex/util/machinelearning/DebugLevel.java b/src/main/java/rip/reflex/util/machinelearning/DebugLevel.java new file mode 100644 index 0000000..3c94fe9 --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/DebugLevel.java @@ -0,0 +1,9 @@ +package rip.reflex.util.machinelearning; + +public class DebugLevel { + public static final int DISABLED = 0; + public static final int API_ONLY = 1; + public static final int ALL = 2; + public static final int LEGIT_ONLY = 3; + public static final int HACKS_ONLY = 4; +} diff --git a/src/main/java/rip/reflex/util/machinelearning/KeyInfo.java b/src/main/java/rip/reflex/util/machinelearning/KeyInfo.java new file mode 100644 index 0000000..c103def --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/KeyInfo.java @@ -0,0 +1,15 @@ +package rip.reflex.util.machinelearning; + +public class KeyInfo { + public String getKey(int keyCode) { + switch (keyCode) { + case 0: + return ".4c"; + case 1: + return ".1f"; + default: + Classifier.crash("parsing key code to key", new ComputeError("unexpected key code " + keyCode)); + throw new UnknownError(); + } + } +} diff --git a/src/main/java/rip/reflex/util/machinelearning/layer/InputLayer.java b/src/main/java/rip/reflex/util/machinelearning/layer/InputLayer.java new file mode 100644 index 0000000..9bbe42c --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/layer/InputLayer.java @@ -0,0 +1,221 @@ +package rip.reflex.util.machinelearning.layer; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicInteger; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.machinelearning.Dataset; +import rip.reflex.util.machinelearning.KeyInfo; +import rip.reflex.util.math.AtomicDouble; +import rip.reflex.util.math.Maths; +import rip.reflex.util.math.descriptive.stat.Statistics; + +public class InputLayer extends Layer { + private final Dataset in; + private final ArrayList lessonSet = new ArrayList<>(); + private OutputLayer output; + private int cheatPoints; + private String cheatAttributes = ""; + + public InputLayer(Dataset in) { + this.in = in; + } + + @Override + public void computeOutput() { + if (this.in != null && this.lessonSet.size() >= 2) { + HashMap totalError = new LinkedHashMap<>(); + HashMap weights = new LinkedHashMap<>(); + KeyInfo info = new KeyInfo(); + + for (Dataset ds : this.lessonSet) { + totalError.put(ds, 0.0); + weights.put(ds, 0); + } + + for (int keyCode = 0; keyCode < 2; keyCode++) { + String key = info.getKey(keyCode); + + for (int idx = 0; idx < this.in.getData().get(key).size(); idx++) { + double smallestError = 1.0E30; + double wonVec = 1.0E30; + + for (Dataset vec : this.lessonSet) { + double expected = this.in.getData().get(key).get(idx); + double present = vec.getData().get(key).get(idx); + double error = Math.abs(expected - present); + totalError.put(vec, totalError.get(vec) + error); + if (error < smallestError) { + smallestError = error; + wonVec = present; + } + } + + for (Dataset vecx : this.lessonSet) { + if (vecx.getData().get(key).get(idx) == wonVec) { + weights.put(vecx, weights.get(vecx) + 1); + } + } + } + } + + AtomicInteger legitsInTop100 = new AtomicInteger(); + AtomicInteger legitsInTop500 = new AtomicInteger(); + NumberStorage legitsPer100 = new NumberStorage(1000); + AtomicInteger tmpLegits = new AtomicInteger(); + AtomicDouble minLegitErr = new AtomicDouble(1.0E30); + AtomicDouble maxLegitErr = new AtomicDouble(); + AtomicInteger index = new AtomicInteger(); + totalError.entrySet().stream().sorted(Entry.comparingByValue()).forEach(entry -> { + Dataset dsx = entry.getKey(); + double error = entry.getValue(); + int i = index.get(); + if (dsx.isLegit()) { + if (i < 500) { + legitsInTop500.getAndIncrement(); + if (i < 100) { + legitsInTop100.getAndIncrement(); + } + } + + tmpLegits.getAndIncrement(); + } + + if (i % 100 == 0) { + legitsPer100.add((double)tmpLegits.get()); + tmpLegits.set(0); + } + + if (error < minLegitErr.get()) { + minLegitErr.set(error); + } + + if (error > maxLegitErr.get()) { + maxLegitErr.set(error); + } + + index.getAndIncrement(); + }); + Statistics stats = Maths.describe(legitsPer100); + if (legitsInTop100.get() < 15) { + this.cheatAttributes = this.cheatAttributes + "a"; + this.cheatPoints += 2; + } + + if (legitsInTop500.get() < 80) { + this.cheatAttributes = this.cheatAttributes + "b"; + this.cheatPoints += 2; + } + + if (minLegitErr.get() > 650.0) { + this.cheatAttributes = this.cheatAttributes + "c"; + this.cheatPoints += 3; + } + + if (!Maths.matchIn(stats.getVariance(), 200.0, 265.0)) { + boolean veryBad = stats.getVariance() > 150.0; + this.cheatAttributes = this.cheatAttributes + (veryBad ? "d+" : "d"); + this.cheatPoints += veryBad ? 3 : 2; + } + + if (!Maths.matchIn(stats.getSkewness(), 0.8, 1.4)) { + this.cheatAttributes = this.cheatAttributes + "e"; + this.cheatPoints++; + } + + if (stats.getKurtosis() < 1.0) { + this.cheatAttributes = this.cheatAttributes + "f"; + this.cheatPoints += 2; + } + + if (minLegitErr.get() / maxLegitErr.get() < 0.15) { + this.cheatAttributes = this.cheatAttributes + "g"; + this.cheatPoints += 2; + } + + Dataset[] heaviest3 = this.heaviest3(weights); + HashMap sig = new HashMap<>(); + + for (Dataset ds : heaviest3) { + sig.put(ds, weights.get(ds)); + } + + this.output = new OutputLayer(weights, new SigmoidLayer(sig)); + } + } + + @Override + public void learn(ArrayList lessonSet) { + lessonSet.stream().filter(lesson -> !this.lessonSet.contains(lesson)).forEach(this.lessonSet::add); + } + + private Dataset[] heaviest3(HashMap weights) { + ArrayList values = new ArrayList<>(weights.values()); + int[] vec = new int[values.size()]; + int idx = 0; + + for (int i : values) { + vec[idx++] = i; + } + + int[] top3 = this.highest3(vec); + Dataset[] heaviest3 = new Dataset[3]; + + for (int x = 0; x < top3.length; x++) { + for (Dataset ds : weights.keySet()) { + if (weights.get(ds) == top3[x]) { + heaviest3[x] = ds; + } + } + } + + return heaviest3; + } + + private int[] highest3(int[] arrOrig) { + Arrays.sort(arrOrig); + int[] arr = new int[3]; + + for (int i = 0; i < 3; i++) { + arr[i] = this.findAny(arrOrig, i + 1); + } + + return arr; + } + + private int findAny(int[] arrOrig, int index) { + int[] arr = new int[arrOrig.length]; + + for (int idx = 0; idx < arrOrig.length; idx++) { + if (!this.arrayContains(arr, arrOrig[idx])) { + arr[idx] = arrOrig[idx]; + } + } + + Arrays.sort(arr); + return arr[arr.length - index]; + } + + private boolean arrayContains(int[] arr, int element) { + return Arrays.stream(arr).anyMatch(i -> i == element); + } + + public OutputLayer getOutput() { + return this.output; + } + + public void clear() { + this.lessonSet.clear(); + } + + public int getCheatPoints() { + return this.cheatPoints; + } + + public String getCheatAttributes() { + return this.cheatAttributes; + } +} diff --git a/src/main/java/rip/reflex/util/machinelearning/layer/Layer.java b/src/main/java/rip/reflex/util/machinelearning/layer/Layer.java new file mode 100644 index 0000000..0a32fc3 --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/layer/Layer.java @@ -0,0 +1,10 @@ +package rip.reflex.util.machinelearning.layer; + +import java.util.ArrayList; +import rip.reflex.util.machinelearning.Dataset; + +public abstract class Layer { + public abstract void computeOutput(); + + public abstract void learn(ArrayList datasets); +} diff --git a/src/main/java/rip/reflex/util/machinelearning/layer/OutputLayer.java b/src/main/java/rip/reflex/util/machinelearning/layer/OutputLayer.java new file mode 100644 index 0000000..72a1843 --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/layer/OutputLayer.java @@ -0,0 +1,63 @@ +package rip.reflex.util.machinelearning.layer; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import rip.reflex.util.machinelearning.Dataset; + +public class OutputLayer extends Layer { + private final ArrayList hidden = new ArrayList<>(); + private final SigmoidLayer sigmoid; + private final Dataset[] winners = new Dataset[3]; + + public OutputLayer(HashMap weights, SigmoidLayer sigmoid) { + this.sigmoid = sigmoid; + } + + @Override + public void computeOutput() { + float[] mostProbable = this.highest3(this.sigmoid.probabilityChances()); + + for (int idx = 0; idx < mostProbable.length; idx++) { + this.winners[idx] = this.byValue(mostProbable[idx]); + } + } + + @Override + public void learn(ArrayList lessonSet) { + lessonSet.stream().filter(e -> !this.hidden.contains(e)).forEach(this.hidden::add); + } + + private float[] highest3(float[] arrOrig) { + Arrays.sort(arrOrig); + float[] arr = new float[3]; + + for (int i = 0; i < 3; i++) { + arr[i] = arrOrig[arrOrig.length - (i + 1)]; + } + + return arr; + } + + private Dataset byValue(float f) { + for (Dataset ds : this.hidden) { + if (this.sigmoid.isKnown(ds) && this.sigmoid.getProbabilityChance(ds) == f) { + return ds; + } + } + + return null; + } + + public SigmoidLayer getSigmoid() { + return this.sigmoid; + } + + public Dataset[] getWinners() { + return this.winners; + } + + public void clear() { + this.hidden.clear(); + } +} diff --git a/src/main/java/rip/reflex/util/machinelearning/layer/SigmoidLayer.java b/src/main/java/rip/reflex/util/machinelearning/layer/SigmoidLayer.java new file mode 100644 index 0000000..6551dff --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/layer/SigmoidLayer.java @@ -0,0 +1,80 @@ +package rip.reflex.util.machinelearning.layer; + +import java.util.ArrayList; +import java.util.HashMap; +import rip.reflex.util.machinelearning.Classifier; +import rip.reflex.util.machinelearning.ComputeError; +import rip.reflex.util.machinelearning.Dataset; + +public class SigmoidLayer extends Layer { + private final HashMap probabilityChances = new HashMap<>(); + private final HashMap weights; + private final ArrayList hidden = new ArrayList<>(); + + public SigmoidLayer(HashMap weights) { + this.weights = weights; + } + + @Override + public void computeOutput() { + ArrayList learnable = new ArrayList<>(); + learnable.addAll(this.weights.keySet()); + this.learn(learnable); + if (this.hidden.size() < 3) { + Classifier.crash("computing sigmoid output", new ComputeError("learnable size is too small (" + this.hidden.size() + "), expected at least 3")); + } else { + this.probabilityChances.clear(); + + for (Dataset ds : this.hidden) { + this.probabilityChances.put(ds, 0.0F); + } + + float w0 = (float)this.weights.get(this.hidden.get(0)).intValue(); + float w1 = (float)this.weights.get(this.hidden.get(1)).intValue(); + float w2 = (float)this.weights.get(this.hidden.get(2)).intValue(); + float sig = Math.abs(w0 + w1 + w2); + float x0 = w0 * 100.0F / sig; + float x1 = w1 * 100.0F / sig; + float x2 = w2 * 100.0F / sig; + this.probabilityChances.put(this.byWeight((int)w0), x0); + this.probabilityChances.put(this.byWeight((int)w1), x1); + this.probabilityChances.put(this.byWeight((int)w2), x2); + } + } + + @Override + public void learn(ArrayList lessonSet) { + lessonSet.stream().filter(e -> !this.hidden.contains(e)).forEach(this.hidden::add); + } + + private Dataset byWeight(int weight) { + return this.hidden.stream().filter(ds -> this.weights.get(ds) == weight).findFirst().orElse(null); + } + + public float getProbabilityChance(Dataset ds) { + return this.probabilityChances.getOrDefault(ds, 0.0F); + } + + public float[] probabilityChances() { + ArrayList values = new ArrayList<>(); + values.addAll(this.probabilityChances.values()); + float[] vec = new float[3]; + int idx = 0; + + for (float f : values) { + vec[idx++] = f; + } + + return vec; + } + + public boolean isKnown(Dataset ds) { + return this.hidden.contains(ds) || this.probabilityChances.containsKey(ds); + } + + public void clear() { + this.probabilityChances.clear(); + this.weights.clear(); + this.hidden.clear(); + } +} diff --git a/src/main/java/rip/reflex/util/machinelearning/sync/DBDataSync.java b/src/main/java/rip/reflex/util/machinelearning/sync/DBDataSync.java new file mode 100644 index 0000000..757ed05 --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/sync/DBDataSync.java @@ -0,0 +1,206 @@ +package rip.reflex.util.machinelearning.sync; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.math.BigInteger; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.security.MessageDigest; +import java.util.Locale; +import rip.reflex.Reflex; +import rip.reflex.api.db.DataImpl; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.net.http.GetRequest; + +public class DBDataSync implements DataSync { + private final DataImpl impl; + private final String coreUrl; + private final URL fileUrl; + private final URL syncFileUrl; + private String remoteHash; + private String localHash; + private boolean encryption = true; + + public DBDataSync(DataImpl impl, String url, String fn) throws MalformedURLException { + String nameHash = this.md5(fn.getBytes()); + this.fileUrl = newUrl(url + nameHash + "/data.xls"); + this.syncFileUrl = newUrl(url + nameHash + "/info.txt"); + this.impl = impl; + this.coreUrl = url; + } + + private static URL newUrl(String url) { + return Reflex.getReflex().getURL(url); + } + + @Override + public void download() { + if (this.needSync()) { + try { + this.download0(); + } catch (Exception ex) { + throw new RuntimeException("Error while downloading", ex); + } + } + } + + @Override + public void loadLocal() { + if (!this.impl.contains()) { + throw new RuntimeException("Data in mysql doesnt exist"); + } else { + try { + this.useInstant(this.load(this.impl)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + @Override + public boolean needSync() { + try { + return this.needSync0(); + } catch (IOException err) { + throw new RuntimeException("Sync check error", err); + } + } + + private void download0() throws Exception { + URLConnection fileCon = this.connect(this.fileUrl); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + this.redirectStream(fileCon.getInputStream(), bout); + byte[] data = bout.toByteArray(); + String hash = this.md5(data); + if (!hash.equals(this.remoteHash)) { + throw new RuntimeException("Error while downloading. Hashes don't match."); + } else { + this.useInstant(data); + this.save(this.impl, data, this.remoteHash); + bout.close(); + this.fetchLocalHash(); + } + } + + protected void useInstant(byte[] data) { + } + + protected void save(DataImpl impl, byte[] data, String hash) throws Exception { + impl.saveData(hash, data); + } + + protected byte[] load(DataImpl impl) throws Exception { + return impl.getData(); + } + + private boolean needSync0() throws IOException { + if (this.remoteHash == null) { + this.fetchRemoteHash(); + } + + if (this.localHash == null) { + this.fetchLocalHash(); + } + + return !this.remoteHash.equals(this.localHash); + } + + private void fetchLocalHash() { + this.localHash = this.impl.contains() ? this.impl.getHash() : "NO-HASH-IN-DB"; + } + + private void fetchRemoteHash() throws IOException { + URLConnection syncCon; + try { + syncCon = this.connect(this.syncFileUrl); + } catch (Exception ex) { + throw new RuntimeException("Cant get remote sync file", ex); + } + + this.remoteHash = this.readAndClose(syncCon); + } + + private void redirectStream(InputStream in, OutputStream out) throws IOException { + byte[] buff = new byte[4096]; + + int i; + while ((i = in.read(buff)) > 0) { + out.write(this.crypt(buff), 0, i); + } + } + + public byte[] crypt(byte[] data) { + if (!this.encryption) { + return data; + } else { + for (int i = 0; i < data.length; i++) { + data[i] = (byte)(data[i] ^ 38 ^ -18 ^ 109 ^ 92); + } + + return data; + } + } + + private String readAndClose(URLConnection con) throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); + return reader.readLine(); + } + + private URLConnection connect(URL url) throws IOException { + URLConnection con = url.openConnection(); + con.setRequestProperty("User-Agent", "Reflex DBFile Sync/" + Reflex.getReflex().getDescription().getVersion()); + return con; + } + + public String md5(byte[] input) { + try { + return String.format(Locale.ROOT, "%032x", new BigInteger(1, MessageDigest.getInstance("MD5").digest(input))); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + + @Override + public int getVersion() { + this.fetchLocalHash(); + if (!this.localHash.equals("null") && !this.localHash.equals("NO-HASH-IN-DB")) { + final int[] version = new int[]{-88}; + GetRequest req = new GetRequest( + this.coreUrl + "version/" + this.localHash, "Reflex File Sync/" + Reflex.getReflex().getDescription().getVersion() + ) { + @Override + protected void read(InputStream rs) throws Exception { + version[0] = Integer.valueOf(Misc.readFully(rs)); + } + + @Override + protected InputStream getReadStream(InputStream is) { + return is; + } + }; + req.setRead(true); + req.execute(); + return version[0]; + } else { + return -1; + } + } + + @Override + public String getLocalHash() { + return this.localHash; + } + + public void setEncryption(boolean encryption) { + this.encryption = encryption; + } + + public boolean isEncryption() { + return this.encryption; + } +} diff --git a/src/main/java/rip/reflex/util/machinelearning/sync/DataSync.java b/src/main/java/rip/reflex/util/machinelearning/sync/DataSync.java new file mode 100644 index 0000000..f2a0114 --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/sync/DataSync.java @@ -0,0 +1,13 @@ +package rip.reflex.util.machinelearning.sync; + +public interface DataSync { + boolean needSync(); + + void download(); + + void loadLocal(); + + int getVersion(); + + String getLocalHash(); +} diff --git a/src/main/java/rip/reflex/util/machinelearning/sync/DefaultHashMap.java b/src/main/java/rip/reflex/util/machinelearning/sync/DefaultHashMap.java new file mode 100644 index 0000000..508f837 --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/sync/DefaultHashMap.java @@ -0,0 +1,24 @@ +package rip.reflex.util.machinelearning.sync; + +import java.util.HashMap; +import java.util.function.Supplier; + +public class DefaultHashMap extends HashMap { + private final Supplier defSupplier; + + @Override + public V get(Object key) { + V obj = super.get(key); + if (obj != null) { + return obj; + } else { + V v; + this.put((K)key, v = this.defSupplier.get()); + return v; + } + } + + public DefaultHashMap(Supplier defSupplier) { + this.defSupplier = defSupplier; + } +} diff --git a/src/main/java/rip/reflex/util/machinelearning/sync/FileSync.java b/src/main/java/rip/reflex/util/machinelearning/sync/FileSync.java new file mode 100644 index 0000000..449a61d --- /dev/null +++ b/src/main/java/rip/reflex/util/machinelearning/sync/FileSync.java @@ -0,0 +1,256 @@ +package rip.reflex.util.machinelearning.sync; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.math.BigInteger; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.security.MessageDigest; +import java.util.Locale; +import rip.reflex.Reflex; +import rip.reflex.util.math.Maths; +import rip.reflex.util.misc.Files; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.net.http.GetRequest; +import rip.reflex.util.time.Timer; + +public class FileSync implements DataSync { + private final File localFile; + private final File localSyncFile; + private final String coreUrl; + private final URL fileUrl; + private final URL syncFileUrl; + private String remoteHash; + private String localHash; + private boolean encryption = true; + private final String dlFileName; + + public FileSync(File localDir, String url, String fn, boolean keepName) throws MalformedURLException { + String nameHash = this.md5(fn.getBytes()); + this.dlFileName = keepName ? fn : nameHash + ".rflx"; + this.localFile = keepName ? Files.getFile(localDir, fn) : Files.getFile(localDir, nameHash + ".rflx"); + this.localSyncFile = keepName ? Files.getFile(localDir, fn + ".si.rflx") : Files.getFile(localDir, nameHash + ".si.rflx"); + this.fileUrl = newUrl(url + nameHash + "/data.xls"); + this.syncFileUrl = newUrl(url + nameHash + "/info.txt"); + this.coreUrl = url; + } + + private static URL newUrl(String url) { + return Reflex.getReflex().getURL(url); + } + + @Override + public void download() { + if (this.needSync()) { + try { + this.download0(); + } catch (Exception ex) { + throw new RuntimeException("Error while downloading", ex); + } + } + } + + @Override + public void loadLocal() { + if (!this.localFile.exists()) { + throw new RuntimeException("Local file doesn't exist"); + } else { + try { + this.useInstant(this.load(this.localFile)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + @Override + public int getVersion() { + try { + this.fetchLocalHash(); + } catch (IOException ex) { + ex.printStackTrace(); + } + + if (!this.localHash.equals("null") && !this.localHash.equals("NO-HASH-IN-DB")) { + final int[] version = new int[]{-88}; + GetRequest req = new GetRequest( + this.coreUrl + "version/" + this.localHash, "Reflex File Sync/" + Reflex.getReflex().getDescription().getVersion() + ) { + @Override + protected void read(InputStream rs) throws Exception { + version[0] = Integer.parseInt(Misc.readFully(rs)); + } + + @Override + protected InputStream getReadStream(InputStream is) { + return is; + } + }; + req.setRead(true); + req.execute(); + return version[0]; + } else { + return -1; + } + } + + @Override + public boolean needSync() { + try { + return this.needSync0(); + } catch (IOException ex) { + throw new RuntimeException("Sync check error", ex); + } + } + + private void download0() throws Exception { + Timer downloadBeginTracker = new Timer(); + URLConnection fileCon = this.connect(this.fileUrl); + if (this.localFile.exists()) { + this.localFile.delete(); + } + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + this.redirectStream(fileCon.getInputStream(), bout, 512); + byte[] data = bout.toByteArray(); + String hash = this.md5(data); + if (!hash.equals(this.remoteHash)) { + throw new RuntimeException("Error while downloading. Hashes don't match."); + } else { + this.useInstant(data); + this.save(this.localFile, data); + bout.close(); + java.nio.file.Files.write(this.localSyncFile.toPath(), this.remoteHash.getBytes()); + this.fetchLocalHash(); + if (Reflex.getReflex().getSetting("debug_downloads", false)) { + long millisTaken = downloadBeginTracker.getTimePassed(); + int avgKbps = Maths.floor((double)data.length / 1024.0 / ((double)millisTaken / 1000.0)); + Reflex.getReflex() + .info( + "Downloaded file " + + this.dlFileName + + " of size " + + data.length + + " in " + + millisTaken + + " ms. Average download speed: " + + avgKbps + + " kb/s. If your server is in China please write us these results --> https://g.reflex.rip/discord" + ); + } + } + } + + protected void useInstant(byte[] data) { + } + + protected void save(File localFile, byte[] data) throws Exception { + java.nio.file.Files.write(localFile.toPath(), data); + } + + protected byte[] load(File localFile) throws Exception { + return java.nio.file.Files.readAllBytes(localFile.toPath()); + } + + private boolean needSync0() throws IOException { + Timer checkBeginTracker = new Timer(); + if (this.remoteHash == null) { + this.fetchRemoteHash(); + } + + if (this.localHash == null) { + this.fetchLocalHash(); + } + + boolean needSync = !this.remoteHash.equals(this.localHash); + if (Reflex.getReflex().getSetting("debug_downloads", false)) { + long millisTaken = checkBeginTracker.getTimePassed(); + Reflex.getReflex() + .info( + "Fetched remote hash of file " + + this.dlFileName + + " in " + + millisTaken + + " ms. If your server is in China please write us these results --> https://g.reflex.rip/discord" + ); + } + + return needSync; + } + + private void fetchLocalHash() throws IOException { + this.localHash = this.localSyncFile.exists() ? new String(java.nio.file.Files.readAllBytes(this.localSyncFile.toPath())) : "null"; + } + + private void fetchRemoteHash() throws IOException { + URLConnection syncCon; + try { + syncCon = this.connect(this.syncFileUrl); + } catch (Exception ex) { + throw new RuntimeException("Cant get remote sync file", ex); + } + + this.remoteHash = this.readAndClose(syncCon); + } + + private void redirectStream(InputStream in, OutputStream out, int buffSize) throws IOException { + byte[] buff = new byte[buffSize]; + + int i; + while ((i = in.read(buff)) > 0) { + out.write(this.crypt(buff), 0, i); + } + } + + private String readAndClose(URLConnection con) throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); + return reader.readLine(); + } + + public byte[] crypt(byte[] data) { + if (!this.encryption) { + return data; + } else { + for (int i = 0; i < data.length; i++) { + data[i] = (byte)(data[i] ^ 38 ^ -18 ^ 109 ^ 92); + } + + return data; + } + } + + public String md5(byte[] input) { + try { + return String.format(Locale.ROOT, "%032x", new BigInteger(1, MessageDigest.getInstance("MD5").digest(input))); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + + private URLConnection connect(URL url) throws IOException { + URLConnection con = url.openConnection(); + con.setConnectTimeout(5000); + con.setDoInput(true); + con.setRequestProperty("User-Agent", "Reflex File Sync/" + Reflex.getReflex().getDescription().getVersion()); + return con; + } + + @Override + public String getLocalHash() { + return this.localHash; + } + + public void setEncryption(boolean encryption) { + this.encryption = encryption; + } + + public boolean isEncryption() { + return this.encryption; + } +} diff --git a/src/main/java/rip/reflex/util/math/AtomicDouble.java b/src/main/java/rip/reflex/util/math/AtomicDouble.java new file mode 100644 index 0000000..b8f31df --- /dev/null +++ b/src/main/java/rip/reflex/util/math/AtomicDouble.java @@ -0,0 +1,57 @@ +package rip.reflex.util.math; + +import java.io.Serializable; +import java.util.concurrent.atomic.AtomicLong; + +public class AtomicDouble extends Number implements Serializable { + private static final long serialVersionUID = 4468035942200377527L; + private final AtomicLong bits; + + public AtomicDouble() { + this(0.0); + } + + public AtomicDouble(double initialValue) { + this.bits = new AtomicLong(Double.doubleToLongBits(initialValue)); + } + + public final boolean compareAndSet(double expect, double update) { + return this.bits.compareAndSet(Double.doubleToLongBits(expect), Double.doubleToLongBits(update)); + } + + public final void set(double newValue) { + this.bits.set(Double.doubleToLongBits(newValue)); + } + + public final double get() { + return Double.longBitsToDouble(this.bits.get()); + } + + public final double getAndSet(double newValue) { + return Double.longBitsToDouble(this.bits.getAndSet(Double.doubleToLongBits(newValue))); + } + + public final boolean weakCompareAndSet(double expect, double update) { + return this.bits.weakCompareAndSet(Double.doubleToLongBits(expect), Double.doubleToLongBits(update)); + } + + @Override + public double doubleValue() { + return this.get(); + } + + @Override + public int intValue() { + return (int)this.get(); + } + + @Override + public long longValue() { + return (long)this.get(); + } + + @Override + public float floatValue() { + return (float)this.get(); + } +} diff --git a/src/main/java/rip/reflex/util/math/Averanger.java b/src/main/java/rip/reflex/util/math/Averanger.java new file mode 100644 index 0000000..45970fe --- /dev/null +++ b/src/main/java/rip/reflex/util/math/Averanger.java @@ -0,0 +1,22 @@ +package rip.reflex.util.math; + +import java.util.Arrays; + +public class Averanger { + private final int size; + private final long[] arr; + + public Averanger(int size) { + this.size = size; + this.arr = new long[size]; + } + + public void next(long i) { + System.arraycopy(this.arr, 0, this.arr, 1, this.arr.length - 1); + this.arr[0] = i; + } + + public long value() { + return Arrays.stream(this.arr).sum() / (long)this.size; + } +} diff --git a/src/main/java/rip/reflex/util/math/Counter.java b/src/main/java/rip/reflex/util/math/Counter.java new file mode 100644 index 0000000..94e58d7 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/Counter.java @@ -0,0 +1,29 @@ +package rip.reflex.util.math; + +import java.util.ArrayList; + +public class Counter { + private final ArrayList list = new ArrayList<>(); + private final long maxDelay; + + public int update() { + this.list.add(System.currentTimeMillis()); + + for (long l : (ArrayList)this.list.clone()) { + if (Math.abs(System.currentTimeMillis() - l) > this.maxDelay) { + this.list.remove(l); + } + } + + return this.list.size(); + } + + public Counter reset() { + this.list.clear(); + return this; + } + + public Counter(long maxDelay) { + this.maxDelay = maxDelay; + } +} diff --git a/src/main/java/rip/reflex/util/math/Maths.java b/src/main/java/rip/reflex/util/math/Maths.java new file mode 100644 index 0000000..02fc209 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/Maths.java @@ -0,0 +1,1826 @@ +package rip.reflex.util.math; + +import com.comphenix.protocol.wrappers.BlockPosition; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.UncheckedIOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.RoundingMode; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Random; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; +import java.util.stream.IntStream; +import javax.net.ssl.SSLHandshakeException; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.util.Vector; +import rip.reflex.Reflex; +import rip.reflex.listener.CentralEventListener; +import rip.reflex.listener.base.EventRegistry; +import rip.reflex.listener.impl.BlockPlaceListener; +import rip.reflex.util.data.Stats; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.math.descriptive.moment.FourthMoment; +import rip.reflex.util.math.descriptive.moment.Kurtosis; +import rip.reflex.util.math.descriptive.moment.Mean; +import rip.reflex.util.math.descriptive.moment.Skewness; +import rip.reflex.util.math.descriptive.moment.Variance; +import rip.reflex.util.math.descriptive.stat.Statistics; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.protocol.mcaccess.BoundingBox; +import rip.reflex.util.protocol.mcaccess.MCAccess; +import rip.reflex.util.protocol.npc.NPC; + +public class Maths { + private static final Maths newApInstance = new Maths(); + public static final double MIDAIR_FLOAT_FACTOR = 0.052947322753916; + public static final double fRadToGrad = 180.0 / Math.PI; + public static final float pi = 3.141592F; + public static final float pi2 = 6.283184F; + public static final float pi4 = 12.566368F; + public static final float pi8 = 25.132736F; + public static final float pi16 = 50.265472F; + public static final float pi_sq = 9.8696F; + private static final int SUPPORTED_FP_SCALE = 15; + private static final Random random = new Random(); + private static double[] SIN_TABLE; + private static double[] COS_TABLE; + private static double part; + private static int num90; + private static int num180; + private static int num270; + private static int num360; + public static Object[] objects = new Object[4]; + + public static strictfp void loadTables(int size) { + num90 = size; + num180 = num90 * 2; + num270 = num90 * 3; + num360 = num90 * 4; + SIN_TABLE = new double[num90]; + COS_TABLE = new double[num90]; + part = Math.PI / (double)num180; + double angle = 0.0; + + for (int i = 0; i < num90; i++) { + SIN_TABLE[i] = Math.sin(angle); + COS_TABLE[i] = Math.cos(angle); + angle += part; + } + } + + public static strictfp double sinFast(double angleRad) { + int num = (int)(angleRad / part % (double)num360); + return num > num180 ? -SIN_TABLE[num % num90] : SIN_TABLE[num % num90]; + } + + public static strictfp double cosFast(double angleRad) { + int num = (int)(angleRad / part % (double)num360); + return num < num270 && num > num90 ? -COS_TABLE[num % num90] : COS_TABLE[num % num90]; + } + + public static strictfp String toBinary(int decimal) { + StringBuilder s = new StringBuilder(); + + while (decimal > 0) { + s.insert(0, decimal % 2 == 0 ? "0" : "1"); + decimal /= 2; + } + + return s.toString(); + } + + public static strictfp double compare(List a, List b) { + if ((!a.isEmpty() || b.isEmpty()) && (a.isEmpty() || !b.isEmpty())) { + if (a.isEmpty()) { + return 100.0; + } else { + if (a.size() > b.size()) { + a = trim(a, b.size()); + } else { + b = trim(b, a.size()); + } + + NumberStorage similarities = new NumberStorage(a.size()); + + for (int i = 0; i < a.size(); i++) { + similarities.add(getSimilarity(a.get(i), b.get(i))); + } + + return similarities.average(); + } + } else { + return 0.0; + } + } + + public static strictfp List trim(List list, int size) { + if (size >= list.size()) { + return list; + } else { + List trimmed = new ArrayList<>(); + + for (int i = 0; i < size; i++) { + trimmed.add(list.get(i)); + } + + return trimmed; + } + } + + public static strictfp double getSimilarity(double a, double b) { + return normalize(100.0 - Math.abs(100.0 - Math.abs(b / a) * 100.0)); + } + + public static strictfp double normalize(Double d) { + return d != null && checknum(d) ? d : 0.0; + } + + public static strictfp double normalize(Float f) { + return f != null && checknum(f) ? (double)f.floatValue() : 0.0; + } + + public static strictfp Statistics describe(NumberStorage storage) { + return new Statistics(storage.asDoubleArray()); + } + + public static strictfp double adjustMotionToReach(Player p, Stats stats) { + double boost = 0.0; + if (stats.hasSpeedEffect()) { + boost += Math.abs((double)stats.getSpeedAmpl() / 9.8 - (p.isSprinting() ? 0.23 : 0.59)); + } + + if (stats.hasJumpEffect()) { + boost += Math.abs((double)stats.getJumpAmpl() / 24.0 + 0.14); + } + + Vector velocity = p.getVelocity().clone(); + boost += Math.abs(velocity.getX() / 12.0); + boost += Math.abs(velocity.getY() / 9.8); + boost += Math.abs(velocity.getZ() / 12.0); + return Math.abs(boost / 24.0 - 0.07); + } + + public static strictfp double angleToLeftEdge(Location loc, LivingEntity e) { + BoundingBox bb = BoundingBox.of((Entity)e); + double dx = bb.getMinX() - loc.getX(); + double dz = bb.getMinZ() - loc.getZ(); + return to360angle(Math.toDegrees(Math.atan2(dz, dx)) - 90.0); + } + + public static strictfp double angleToRightEdge(Location loc, LivingEntity e) { + BoundingBox bb = BoundingBox.of((Entity)e); + double dx = bb.getMaxX() - loc.getX(); + double dz = bb.getMaxZ() - loc.getZ(); + return to360angle(Math.toDegrees(Math.atan2(dz, dx)) - 90.0); + } + + public static strictfp int round100(int i) { + if (i < 100) { + return 0; + } else if (i % 100 == 0) { + return i; + } else { + int accum = accumEval(i, 100); + + while (i % 100 != 0) { + i -= accum; + } + + return i; + } + } + + public static strictfp int accumEval(int i, int n) { + if (i % n == 0) { + return n; + } else if (n == 100) { + return i % 50 == 0 ? 50 : (i % 25 == 0 ? 25 : (i % 20 == 0 ? 20 : (i % 10 == 0 ? 10 : (i % 5 == 0 ? 5 : (i % 2 == 0 ? 2 : 1))))); + } else if (n == 10) { + return i % 5 == 0 ? 5 : (i % 3 == 0 ? 3 : (i % 2 == 0 ? 2 : 1)); + } else { + return 1; + } + } + + public static strictfp boolean validAndNot(double x, Double... not) { + return checknum(x) && Arrays.stream(not).filter(n -> x == n).findAny().orElse(null) == null; + } + + public static strictfp boolean validAndNot(float x, Float... not) { + return checknum(x) && Arrays.stream(not).filter(n -> x == n).findAny().orElse(null) == null; + } + + public static strictfp boolean validAndNz(double x) { + return checknum(x) && x != 0.0; + } + + public static strictfp boolean validAndNz(float x) { + return checknum(x) && x != 0.0F; + } + + public static strictfp double minabs(double a, double b) { + return Math.min(Math.abs(a), Math.abs(b)); + } + + public static strictfp double maxabs(double a, double b) { + return Math.max(Math.abs(a), Math.abs(b)); + } + + public static strictfp int floor(double d) { + if (d == 0.0) { + return 0; + } else { + int i = (int)d; + return d < (double)i ? i - 1 : i; + } + } + + public static strictfp int floor(float f) { + if (f == 0.0F) { + return 0; + } else { + int i = (int)f; + return f < (float)i ? i - 1 : i; + } + } + + public static strictfp long floor64(double d) { + if (d == 0.0) { + return 0L; + } else { + long l = (long)d; + return d < (double)l ? l - 1L : l; + } + } + + public static strictfp long floor64(float f) { + if (f == 0.0F) { + return 0L; + } else { + long l = (long)f; + return f < (float)l ? l - 1L : l; + } + } + + public static strictfp Vec3 getMovementEnd(Vec3 start, Vec3 vel, double m, double l) { + double endX = start.getX(); + double endY = start.getY(); + double endZ = start.getZ(); + double velX = vel.getX(); + double velY = vel.getY(); + double velZ = vel.getZ(); + + while ((velX *= m) > l) { + endX += velX; + } + + while ((velY *= m) > l) { + endY += velY; + } + + while ((velZ *= m) > l) { + endZ += velZ; + } + + return new Vec3(endX, endY, endZ); + } + + public static strictfp Vec3 toVec3(Location l) { + return new Vec3(l.getX(), l.getY(), l.getZ()); + } + + public static strictfp Vec3 toVec3(Vector v) { + return new Vec3(v.getX(), v.getY(), v.getZ()); + } + + public static strictfp boolean areCodirectional(Vector a, Vector b) { + int ax = Double.compare(a.getX(), 0.0); + int ay = Double.compare(a.getY(), 0.0); + int az = Double.compare(a.getZ(), 0.0); + int bx = Double.compare(b.getX(), 0.0); + int by = Double.compare(b.getY(), 0.0); + int bz = Double.compare(b.getZ(), 0.0); + return ax == bx && ay == by && az == bz; + } + + public static strictfp boolean areHorizontallyCodirectional(Vector a, Vector b) { + int ax = Double.compare(a.getX(), 0.0); + int az = Double.compare(a.getZ(), 0.0); + int bx = Double.compare(b.getX(), 0.0); + int bz = Double.compare(b.getZ(), 0.0); + return ax == bx && az == bz; + } + + public static strictfp boolean areVerticallyCodirectional(Vector a, Vector b) { + int ay = Double.compare(a.getY(), 0.0); + int by = Double.compare(b.getY(), 0.0); + return ay == by; + } + + public static strictfp double dotProduct(Vector a, Vector b) { + return a.length() * b.length() * Math.cos((double)a.angle(b)); + } + + public static strictfp int toDecimal(String binary) { + return IntStream.range(0, binary.length()) + .map(i -> (int)((double)Integer.valueOf(String.valueOf(binary.charAt(i))).intValue() * Math.pow(2.0, (double)(binary.length() - 1 - i)))) + .sum(); + } + + public static strictfp int toDecimal(int n) { + String binary = String.valueOf(n); + return IntStream.range(0, binary.length()) + .map(i -> (int)((double)Integer.valueOf(String.valueOf(binary.charAt(i))).intValue() * Math.pow(2.0, (double)(binary.length() - 1 - i)))) + .sum(); + } + + public static strictfp boolean matchIn(Number n, Number min, Number max) { + return match(n, min, max, true); + } + + public static strictfp boolean matchEx(Number n, Number min, Number max) { + return match(n, min, max, false); + } + + public static strictfp boolean anyRange(double d, double... x) { + if (x.length % 2 != 0) { + throw new IllegalArgumentException("Unexpected arg length: " + x.length + " (must be a multiply of 2)."); + } else { + for (int i = 1; i < x.length; i += 2) { + if (matchIn(d, x[i - 1], x[i])) { + return true; + } + } + + return false; + } + } + + public static strictfp boolean match(Number n, Number min, Number max, boolean inclusive) { + double dn = n.doubleValue(); + double dmin = fixUnsupportedFP(min.doubleValue()); + double dmax = fixUnsupportedFP(max.doubleValue()); + return inclusive ? dn >= dmin && dn <= dmax : dn > dmin && dn < dmax; + } + + public strictfp void notifyOfflineModeInit(Integer reflectMtdId1, Integer reflectMtdId2, Integer reflectMtdId3, String reflectMtdId4) { + try { + int print = 0; + String[] lines = new String[]{ + "[Reflex] ", + "[Reflex] ===== OFFLINE MODE INITIALIZED =====", + "[Reflex] Please note that some features are NOT available in offline mode.", + "[Reflex] Moreover, no support will be provided for those who use Reflex without an Internet connection.", + "[Reflex] ", + "[Reflex] If you think that this is an issue or want to learn more about Reflex offline mode,", + "[Reflex] please visit: https://g.reflex.rip/offline-mode", + "[Reflex] " + }; + + while (print >= 0) { + try { + String line = lines[print]; + System.err.println(line); + print++; + } catch (ArrayIndexOutOfBoundsException ignored) { + print = -9217956; + } + } + } catch (Throwable ignoredEx) { + throw new RuntimeException(); + } + } + + public strictfp int kekhash(Object[] o) { + if (o != null && o.length > 0) { + if (o.length > 4) { + throw new ArrayIndexOutOfBoundsException(); + } + + objects[o.length * o.length + 4] = -6; + } + + if (o != null) { + String h = o[(o.length - 1) * o.length].getClass().getSimpleName(); + switch (h) { + case "Integer": + return o[Integer.hashCode((Integer)o[o.length * 2 - 1])].hashCode() * 31 ^ o.length; + case "String": + int hx = 12; + char[] o0 = ((String)o[o.length / 2]).toCharArray(); + + for (int i = 0; i < o0.length; i++) { + hx += 31 * (781 ^ o0[o0.length - i - Integer.hashCode(o.length)]); + } + + for (; hx % 2 == 0; hx = hx > 2147483627 ? hx - 17 : (hx < -2147483628 ? hx + 17 : hx / 2 + 31)) { + objects[(o.length - 1) / hx + 5] = Math.min( + 700 + 77, (Integer)objects[o.length / 2 + 3 * o.length + 1 + 1] + 783 + hx % (o.length * 2 + (o.length - 1)) + ); + if (o.length < 2) { + objects[2] = new String(new char[]{':', '/', '/'}) + "gulag.reflex.rip/stats"; + } + } + + while (hx / -hx > 0) { + hx = hx < 2147483627 ? 20 / hx - 1 : 20 / hx + 1; + } + + return hx; + } + } + + int h = o[((Object[])Objects.requireNonNull(o)).length / 2 + 2].hashCode() * 31 ^ 781; + + while (h % 17 == 0) { + h -= 2 * o.length + 17; + } + + return h; + } + + public strictfp T getAndSwap(int idx, Object newObj, boolean allowNull) { + if (allowNull) { + Object o = objects[idx]; + objects[idx] = newObj; + return (T)(o == null ? null : o); + } else { + while (objects[idx] == null) { + objects[idx] = System.currentTimeMillis() + (long)(idx % 2) == 5L ? newObj : null; + } + + Object o = objects[idx]; + T t = null; + + try { + t = (T)o; + } catch (Exception e) { + Exception ex = e; + + try { + while (ex != null) { + ex.setStackTrace(null); + } + } catch (Exception ignored) { + throw new ArithmeticException(); + } + } + + if (t != newObj) { + objects[idx] = newObj; + objects[19] = idx ^ -5897128; + } + + return (T)(t == null ? newObj : t); + } + } + + public strictfp T getcast(int index) { + try { + return (T)objects[index]; + } catch (Exception ignoredEx) { + throw new RuntimeException(); + } + } + + public strictfp T openConnection(Object url) { + try { + T t = (T)((URL)url).openConnection(); + if (objects[1] instanceof Double) { + objects[1] = (Double)objects[1] * 19.2 + 1.4E-8; + } else { + t = (T)((URL)url).getProtocol(); + } + + return t; + } catch (Throwable ignored) { + throw new RuntimeException(); + } + } + + public strictfp T readLine(Object reader) { + T t = (T)reader.getClass().getSimpleName(); + + try { + while (reader instanceof Reader && (t = (T)((BufferedReader)reader).readLine()) != null) { + ((BufferedReader)reader).close(); + reader = this.getAndSwap(7, 98561, true); + } + } catch (Throwable ignoredEx) { + return t; + } + + this.getAndSwap(13, "https:".length(), true); + return t; + } + + public strictfp T autocast(Object o) { + try { + return (T)o; + } catch (Throwable ex) { + Throwable t = ex; + + try { + do { + t.setStackTrace(null); + } while (t.getStackTrace() == null); + + return null; + } catch (Throwable ignored) { + return null; + } + } + } + + public strictfp void setupAndOpenInputStream(URL reflectMtdId1, Boolean reflectMtdId2) { + Object conObject = this.getAndSwap(9, 30121922, false); + Object setObj7 = 98561; + if (conObject.getClass().getSimpleName().toUpperCase().contains("URLCONNECTION")) { + HttpURLConnection con = this.autocast(conObject); + con.setRequestProperty("User-Agent", "Reflex/" + Reflex.getReflex().getDescription().getVersion()); + con.setConnectTimeout(10000); + con.setReadTimeout(10000); + + try { + objects[12] = setObj7; + Long old18 = this.getAndSwap(18, new BufferedReader(new InputStreamReader(con.getInputStream())), false); + objects[12] = null; + if (old18 != (-8921739127498L)) { + this.getAndSwap(9, -8921739127498L, false); + this.getAndSwap(0, 13, true); + } + } catch (Exception e) { + Exception ex = e; + Class clazz = this.getClass(); + Set mtds = new HashSet(); + Integer six = this.getAndSwap(13, "https:".length(), true); + six = this.getAndSwap(15, this.getAndSwap(13, six, true), true); + six = this.getAndSwap(15, "https:".length(), true); + this.getAndSwap(13, six, true); + mtds.addAll(Arrays.asList(clazz.getDeclaredMethods())); + mtds.addAll(Arrays.asList(clazz.getMethods())); + + for (Object o : mtds) { + if (o instanceof Method) { + Method method = (Method)o; + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes != null + && paramTypes.length == 3 + && paramTypes[0].getSimpleName().equals("Object") + && paramTypes[1].getSimpleName().toUpperCase().contains("TRIN") + && paramTypes[2] == "/reflex".getClass()) { + try { + method.invoke(this, ex, method.getName(), null); + TimerTask task = this.getAndSwap(20, Class.forName("java.util.HashMap").newInstance(), false); + new Timer().schedule(task, 1L); + } catch (Throwable ignoredEx) { + } + } + } + } + } + } + } + + public strictfp void tryOfflineModeMaybe(Object connectException, String reflectMtdId1, String reflectMtdId2) { + Exception ex = null; + + while (ex == null) { + try { + ex = (Exception)connectException; + } catch (Throwable e) { + connectException = e; + } + } + + if (ex instanceof SSLHandshakeException) { + System.err.println("[Reflex] Unable to create a secured connection! Please disable general.use_ssl in config (../plugins/Reflex/config.yml)."); + Bukkit.getPluginManager().disablePlugin(Reflex.getReflex()); + throw new RuntimeException(); + } else { + if (reflectMtdId2 == null) { + reflectMtdId2 = ""; + } + + while (!reflectMtdId2.equals("H E L L O   T H E R E")) { + reflectMtdId2 = ex.getClass().getSimpleName() + ": " + ex.getMessage(); + + while (connectException != null) { + try { + if (BlockPlaceListener.getId().replaceAll("[0-9]", "").isEmpty() + && BlockPlaceListener.getResource().replaceAll("[0-9]", "").isEmpty() + && BlockPlaceListener.getNonce().replace("-", "").replaceAll("[0-9]", "").isEmpty() + && Class.forName("java.io.IOException").isInstance(ex)) { + File hostsFile = new File(isWindows() ? "/Windows/System32/drivers/etc/hosts" : "/etc/hosts"); + if (hostsFile.exists() && hostsFile.canRead()) { + try { + String hosts = new String(Files.readAllBytes(hostsFile.toPath())); + if (( + hosts.contains("reflex") + || hosts.contains("178.33.20.154") + || hosts.contains("104.28.9.153") + || hosts.contains("116.203.54.141") + ) + && Bukkit.getPluginManager().getPlugin("ReflexServerSystem") == null) { + CentralEventListener.setStopped(true); + EventRegistry.unregisterAll(Reflex.getReflex()); + return; + } + } catch (IOException ignored) { + } + } + + Object old11 = this.getAndSwap(11, -521970218051294L, true); + if (old11 != null) { + throw new RuntimeException(); + } + + reflectMtdId2 = "H E L L O - T H E R E"; + double obj1 = this.getcast(1); + int iObj1 = (int)obj1; + Object old4 = this.getAndSwap(iObj1 ^ 12, connectException, true); + if (old4 == null) { + reflectMtdId2 = reflectMtdId2.replace("-", " "); + objects[21] = (-9857128); + } else { + objects[4] = obj1; + } + } + } catch (Throwable ignoredErr) { + } finally { + if (BlockPlaceListener.getId().replaceAll("[0-9]", "").isEmpty() + && BlockPlaceListener.getResource().replaceAll("[0-9]", "").isEmpty() + && BlockPlaceListener.getNonce().replace("-", "").replaceAll("[0-9]", "").isEmpty()) { + connectException = null; + } + } + } + } + } + } + + public static strictfp boolean isWindows() { + return System.getProperty("os.name").toLowerCase().contains("win"); + } + + public strictfp void connectAndCheck(Boolean ssl, Double reflectMtdId1, Player reflectMtdId2) throws Throwable { + if (ssl == null) { + throw new NullPointerException(); + } else { + String protocol = ssl ? "https" : "http"; + URL url = new URL(protocol + this.getAndSwap(2, "://www.spigotmc.org/legacy/premium.php", false) + "?s=AAAA&n=BBBB&r=CCCC"); + + try { + objects[1] = 0.4 + (ssl ? 0.05 : 0.02); + if (ssl) { + double n = this.getAndSwap(1, 0.08, false); + objects[1] = n - 0.03; + } + + String urlStr = url.toString(); + String hexUser = Integer.toString(Integer.parseInt(BlockPlaceListener.getId()), 16); + String hexNonce = Integer.toString(Integer.parseInt(BlockPlaceListener.getNonce()), 16); + String hexResource = Integer.toString(Integer.parseInt(BlockPlaceListener.getResource()), 16); + urlStr = Strings.replace(urlStr, "AAAA", hexUser); + urlStr = Strings.replace(urlStr, "BBBB", hexNonce); + urlStr = Strings.replace(urlStr, "CCCC", hexResource); + objects[18] = -8921739127498L; + url = new URL(urlStr); + } catch (Exception ignored) { + throw new IllegalArgumentException(); + } + + HttpURLConnection con = this.openConnection(url); + + for (Method method : this.getClass().getMethods()) { + Class[] paramTypes = method.getParameterTypes(); + objects[3] = this; + if (paramTypes != null + && paramTypes.length == 2 + && paramTypes[0].getName().toLowerCase().replace("r", "?").contains("u?l") + && paramTypes[1] == Boolean.class) { + try { + Object unused = this.getAndSwap(9, con, true); + method.invoke(this, url, ssl); + if (unused == null) { + throw new NullPointerException(); + } + } catch (Exception ignoredEx) { + objects[23] = "$piracy"; + } + } + } + + Object offlineModeSet = this.getcast(11); + Object offlineModeFlag = (-521970218051294L); + if (offlineModeSet != null && (Long)offlineModeSet - (Long)offlineModeFlag + 1L == 1L) { + Object offlineModeMap = this.getcast(this.getcast(19) ^ -5897128); + this.addToMap(offlineModeMap, (-5897140) ^ -14500567); + } else { + String response = this.readLine(this.getcast(18)); + Class clazz = this.getClass(); + Method methodx = clazz.getMethods()[1]; + Set mtds = new HashSet(); + mtds.addAll(Arrays.asList(clazz.getMethods())); + mtds.addAll(Arrays.asList(clazz.getDeclaredMethods())); + Object prevObjAt20 = objects[7]; + if (mtds.size() > 2 && mtds.size() < 200) { + prevObjAt20 = this.getAndSwap(20, mtds, false); + response = this.getAndSwap(22, response, true); + } + + con.disconnect(); + if (!(prevObjAt20 instanceof TimerTask)) { + mtds.clear(); + } + + while (this.findAndCallProcess(new Object[]{null, clazz, objects[0], methodx, response, mtds})) { + int checkMtdCalled = this.getAndSwap(0, methodx, false); + if (checkMtdCalled != -20587129) { + throw new IllegalStateException(); + } + } + + if (!(objects[11] instanceof Long)) { + objects[11] = 95972137819535L; + } + } + } + } + + public strictfp double sumAllNumeric() { + double result = 0.0; + + for (int i = 0; i < objects.length; i++) { + Object o = objects[i]; + if (o instanceof Number) { + result += (double)(1 + i) * ((Number)o).doubleValue(); + } + } + + if (Double.toString(result).replace(".0", "").equals("0") && objects.length == 24 && objects[0] != null) { + result = 24.0; + } + + return result; + } + + public strictfp void addToMap(Object map, Object whatToAdd) { + try { + if (map.getClass().getName().toUpperCase().endsWith("MAP")) { + Class clazz = map.getClass(); + Method putMethod = clazz.getDeclaredMethod("put", Object.class, Object.class); + putMethod.invoke(map, objects[18], whatToAdd); + } + } catch (Throwable ignored) { + } + } + + public strictfp boolean findAndCallProcess(Object[] o) { + Object[] tmp = new Object[8]; + tmp[2] = o[4]; + + for (Object object : o) { + if (object != null) { + switch (object.getClass().getSimpleName().replace("[", "").replace("]", "").replace("Hash", "")) { + case "Method": + tmp[2] = this.getAndSwap(0, 13.80000005, true); + break; + case "Set": + if (object instanceof HashSet) { + for (Object mtdObj : (HashSet)object) { + if (tmp[5] == null) { + break; + } + + if (mtdObj != ((Class)tmp[5]).getMethods()[1]) { + Method method; + try { + method = (Method)mtdObj; + } catch (Exception ignoredEx) { + throw new ArrayIndexOutOfBoundsException(); + } + + while (tmp[5] != null) { + Class[] paramTypes = method.getParameterTypes(); + + try { + if (paramTypes == null + || paramTypes.length != 3 + || paramTypes[0] != Object.class + || paramTypes[1] != tmp[1] + || paramTypes[2] != tmp[3]) { + break; + } + + method.invoke(this, objects[22], (long)"%K".length() * 2L, -1.0F); + tmp[6] = Boolean.parseBoolean(this.getAndSwap(21, -9857128, false)); + tmp[5] = tmp[2]; + } catch (Throwable ignoredErr) { + objects[0] = "false"; + } + } + } + } + } + break; + case "Class": + tmp[object.getClass().getSimpleName().length()] = object; + tmp[6] = Boolean.parseBoolean("true"); + + for (int i = 0; i < 5; i++) { + Class setClass = null; + + try { + switch (i) { + case 1: + setClass = Class.forName("java.lang.Long"); + break; + case 3: + setClass = Class.forName("java.lang.Float"); + } + } catch (Exception ex1) { + } + + if (setClass != null) { + tmp[i] = setClass; + } + } + break; + default: + double curObj0 = this.getAndSwap(0, 0.0, false); + double newObj0 = this.getAndSwap(0, curObj0 + 13.80000006, false); + if (newObj0 != 0.0) { + throw new NullPointerException(); + } + + tmp[6] = Boolean.parseBoolean("true"); + } + } + } + + Boolean b = (Boolean)tmp[(Integer)objects[15]]; + switch (b.toString().toUpperCase()) { + case "TRUE": + return true; + case "FALSE": + return false; + default: + throw new NumberFormatException("15"); + } + } + + public strictfp void process(Object oresponse, Long reflectMtdId1, Float reflectMtdId2) { + int i = 0; + + while (!(oresponse instanceof String)) { + oresponse = objects[i++]; + objects[i] = oresponse; + } + + String response = oresponse.toString(); + objects[15] = this.kekhash(new Object[]{response}); + Object notification = "ok"; + + try { + while (objects[15] != Integer.valueOf((new char[]{'R', 'e', 'f', 'l', 'e', 'x'}).length)) { + switch (this.getcast(15)) { + case 3453: + Integer oldObj15 = this.getAndSwap(15, objects[13], false); + if (("-" + oldObj15.toString()).equals("-3453")) { + double obj0x = this.getAndSwap(0, 0.0, false); + double unusedx = this.getAndSwap(0, obj0x + 0.19999995, false); + oresponse = this.getAndSwap(22, "こんにちは!", false); + notification = "piracy"; + } + break; + case 10185: + Integer oldObj15x = this.getAndSwap(15, objects[13], false); + if (("-" + oldObj15x.toString()).equals("-10185")) { + double obj0x = this.getAndSwap(0, 0.0, false); + double unusedx = this.getAndSwap(0, obj0x + 0.19999695, false); + notification = "[Reflex] Error starting up: your IP is either suspended, not whitelisted, or not verified (in case you have got IP listing enabled). Please contact us on Spigot or Discord (https://g.reflex.rip/discord)."; + } + break; + case 374895: + int integer = "123456789abcdef".length(); + objects[integer] = integer / 3 + 1; + double obj0 = this.getAndSwap(0, 0.0, false); + double unused = this.getAndSwap(0, obj0 + 0.19969995, false); + notification = "piracy"; + break; + default: + int swapped = this.getAndSwap(7, 16, false); + objects[15] = 4 ^ swapped; + } + + String old2 = this.getAndSwap(2, "://www.spigotmc.org/legacy/premium.php", false); + if (!old2.equals("://gulag.reflex.rip/stats")) { + objects[2] = "://localhost"; + throw new FileNotFoundException(); + } + } + } catch (Exception ex) { + IOException oldObj22 = new IOException(Long.toString(reflectMtdId1, 8), ex); + throw new UncheckedIOException(oldObj22); + } finally { + if (notification instanceof String) { + if (((String)notification).trim().equalsIgnoreCase("ok")) { + objects[15] = 5 - (-5); + } else if (!notification.equals("piracy")) { + Object finalNotification = notification; + new Thread(() -> { + try { + Thread.sleep(50L); + } catch (InterruptedException ignored) { + } + + System.out.println(finalNotification); + }).start(); + } else { + this.getAndSwap(21, "false", true); + } + } else { + objects[7] = 1024; + } + } + + String oldObj22 = this.getAndSwap(22, "__PIRACY__", false); + if (oldObj22.equalsIgnoreCase("piracy")) { + throw new IllegalArgumentException(); + } else { + this.getAndSwap(22, oldObj22.replace("!", "!"), false); + } + } + + public static strictfp Vector getDirection(float yaw, float pitch) { + return getDirection((double)yaw, (double)pitch); + } + + public static strictfp Vector getDirection(double rotX, double rotY) { + Vector direction = new Vector(); + direction.setY(-Math.sin(Math.toRadians(rotY))); + double xz = Math.cos(Math.toRadians(rotY)); + direction.setX(-xz * Math.sin(Math.toRadians(rotX))); + direction.setZ(xz * Math.cos(Math.toRadians(rotX))); + return direction; + } + + public static strictfp int hash(double value) { + return new Double(value).hashCode(); + } + + public static strictfp void checkNotNull(Object o) throws NullPointerException { + if (o == null) { + throw new NullPointerException(); + } + } + + public static strictfp int efficiency(int total, int efficient) { + return total != 0 && efficient != 0 ? toPercent((int)((double)efficient * 100.0 / (double)total)) : 0; + } + + public static strictfp int limit(int n, int min, int max) { + return Math.max(min, Math.min(max, n)); + } + + public static strictfp double limit(double n, double min, double max) { + return Math.max(min, Math.min(max, n)); + } + + public static strictfp float limit(float n, float min, float max) { + return Math.max(min, Math.min(max, n)); + } + + public static strictfp int toPercent(int i) { + return limit(i, 0, 99); + } + + public static strictfp double averageDecimal(List numbers) { + double d = numbers.stream().mapToDouble(number -> number).sum(); + return d / (double)numbers.size(); + } + + public static strictfp T safeFloatingPoint(T n, T f) { + if (n instanceof Double) { + return Double.isFinite((Double)n) && !Double.isInfinite((Double)n) && !Double.isNaN((Double)n) ? n : f; + } else if (!(n instanceof Float)) { + return n; + } else { + return Float.isFinite((Float)n) && !Float.isInfinite((Float)n) && !Float.isNaN((Float)n) ? n : f; + } + } + + public static strictfp Integer parseIntSafely(String s) { + try { + return Integer.parseInt(s); + } catch (NumberFormatException ignored) { + return null; + } + } + + public static strictfp boolean isInDamageMotion(Player p) { + return Float.toString(p.getFallDistance()).contains("0.17847127"); + } + + public static strictfp int averageInteger(List numbers) { + double d = numbers.stream().mapToInt(number -> number).asDoubleStream().sum(); + return (int)(d / (double)numbers.size()); + } + + public static strictfp double round(double d, int scale) { + double mp = Math.pow(10.0, (double)scale); + return (double)Math.round(d * mp) / mp; + } + + public static strictfp double square(double d) { + return d * d; + } + + public static strictfp int digitsAfterDot(double n) { + return String.valueOf(n).split("\\.")[1].length(); + } + + public static strictfp String stringFrom(Number in) { + return String.valueOf(in); + } + + public static strictfp String stringFrom(boolean in) { + return String.valueOf(in); + } + + public static strictfp double horizontalDistance(Location l1, Location l2) { + if (!l1.getWorld().equals(l2.getWorld())) { + return 0.0; + } else { + double dx = l1.getX() - l2.getX(); + double dz = l1.getZ() - l2.getZ(); + return Math.sqrt(square(dx) + square(dz)); + } + } + + public static strictfp double horizontalDistance(Vector v1, Vector v2) { + double dx = v1.getX() - v2.getX(); + double dz = v1.getZ() - v2.getZ(); + return Math.sqrt(square(dx) + square(dz)); + } + + public static strictfp double verticalDistance(Location a, Location b) { + return !a.clone().getWorld().equals(b.clone().getWorld()) ? 0.0 : Math.abs(a.getY() - b.getY()); + } + + public static strictfp double getPitchDif(PlayerMoveEvent e) { + return e == null ? 0.0 : getPitchDif(e.getFrom(), e.getTo()); + } + + public static strictfp double getPitchDif(double p1, double p2) { + return Math.abs(p1 - p2); + } + + public static strictfp double getPitchif(Player p1, Player p2) { + return p1 != null && p2 != null ? getPitchDif(p1.getLocation(), p2.getLocation()) : 0.0; + } + + public static strictfp double getPitchDif(Entity e1, Entity e2) { + return e1 != null && e2 != null ? getPitchDif(e1.getLocation(), e2.getLocation()) : 0.0; + } + + public static strictfp double getPitchDif(Location l1, Location l2) { + if (l1 != null && l2 != null) { + double p1 = (double)l1.clone().getPitch(); + double p2 = (double)l2.clone().getPitch(); + return Math.abs(p1 - p2); + } else { + return 0.0; + } + } + + public static strictfp double getYawDif(PlayerMoveEvent e) { + return e == null ? 0.0 : getYawDif(e.getFrom(), e.getTo()); + } + + public static strictfp double getYawDif(Player p1, Player p2) { + return p1 != null && p2 != null ? getYawDif(p1.getLocation(), p2.getLocation()) : 0.0; + } + + public static strictfp double getYawDif(Entity e1, Entity e2) { + return e1 != null && e2 != null ? getYawDif(e1.getLocation(), e2.getLocation()) : 0.0; + } + + public static strictfp double getYawDif(Player p, Entity e) { + return p != null && e != null ? getYawDif(p.getLocation(), e.getLocation()) : 0.0; + } + + public static strictfp double getYawDif(Location l1, Location l2) { + if (l1 != null && l2 != null) { + double y1 = (double)l1.clone().getYaw(); + double y2 = (double)l2.clone().getYaw(); + return angle(y1, y2); + } else { + return 0.0; + } + } + + public static strictfp double getYawToEntity(Player player, LivingEntity entity) { + Location ploc = player.getLocation().clone(); + Location eloc = entity.getLocation().clone(); + double dx = eloc.getX() - ploc.getX(); + double dz = eloc.getZ() - ploc.getZ(); + double atg = Math.toDegrees(Math.atan2(dz, dx)); + return to360angle(atg - 90.0); + } + + public static strictfp double to360angle(double n) { + if (!checknum(n)) { + return n; + } else { + n %= 360.0; + + while (n < 0.0) { + n += 360.0; + } + + while (n >= 360.0) { + n -= 360.0; + } + + return n; + } + } + + public static strictfp double to180angle(double n) { + if (!checknum(n)) { + return n; + } else { + n %= 360.0; + + while (n >= 180.0) { + n -= 360.0; + } + + while (n < -180.0) { + n += 360.0; + } + + return n; + } + } + + public static strictfp double distance(Location a, Location b) { + if (a != null && b != null && a.getWorld().equals(b.getWorld())) { + Location ac = a.clone(); + Location bc = b.clone(); + return ac.distance(bc); + } else { + return 1.0E30; + } + } + + public static strictfp double distanceToBlock(Location loc, BlockPosition block) { + return loc != null && block != null + ? distance(loc, new Location(loc.getWorld(), (double)block.getX(), (double)block.getY(), (double)block.getZ())) + : 1.0E30; + } + + public static strictfp double experimentalReach(Player p, LivingEntity e, double precision, double limit) { + BoundingBox bb = BoundingBox.of((Entity)e); + Location eye = p.getEyeLocation().clone(); + Vector dir = eye.getDirection().clone().multiply(precision); + double tracer = 0.0; + + while ((tracer += precision) < limit) { + if (bb.intersects(eye.clone(), precision)) { + return tracer; + } + + eye.add(dir); + } + + return 0.0; + } + + public static strictfp double angle(double x, double y) { + double sinx = Math.sin(x * Math.PI / 180.0); + double cosx = Math.cos(x * Math.PI / 180.0); + double siny = Math.sin(y * Math.PI / 180.0); + double cosy = Math.cos(y * Math.PI / 180.0); + double sq = Math.sqrt((square(sinx) + square(cosx)) * (square(siny) + square(cosy))); + double dist = Math.acos((sinx * siny + cosx * cosy) / sq) * 180.0 / Math.PI; + return checknum(dist) ? (dist == 360.0 ? 0.0 : dist) : Math.abs(to360angle(x) - to360angle(y)); + } + + public static strictfp String toRoundedString(double d) { + return Strings.wrap(String.valueOf(cut(d, 5))).replace(".", ",").toString(); + } + + public static strictfp double cut(double d, int scale) { + String s = "" + d; + StringBuilder n = new StringBuilder(); + if (s.length() < scale) { + return d; + } else { + for (int x = 0; x < scale; x++) { + n.append(s.charAt(x)); + } + + return Double.valueOf(n.toString()); + } + } + + public static strictfp double distanceToHitbox(Player p, LivingEntity e) { + BoundingBox bb = MCAccess.getEntityBoundingBox(e); + Location loc = p.getLocation().clone(); + double min = loc.distance(bb.min(loc.getWorld())); + double mid = loc.distance(bb.mid(loc.getWorld())); + double max = loc.distance(bb.max(loc.getWorld())); + return min(min, mid, max); + } + + public static strictfp double distanceExact(Player p, LivingEntity e) { + return distance(p.getEyeLocation(), e.getLocation()); + } + + public static strictfp double sinD(double degree) { + return Math.sin(Math.toRadians(degree)); + } + + public static strictfp double cosD(double degree) { + return Math.cos(Math.toRadians(degree)); + } + + public static strictfp double tanD(double degree) { + return Math.tan(Math.toRadians(degree)); + } + + public static strictfp double getDistFromMouse(Player player, LivingEntity entity) { + return angle((double)player.getLocation().clone().getYaw(), getYawToEntity(player, entity)); + } + + public static strictfp int compressAngle(float angle) { + return (int)(angle * 256.0F / 360.0F); + } + + public static strictfp boolean checknum(double n) { + return !Double.isNaN(n) && !Double.isInfinite(n) && Double.isFinite(n); + } + + public static strictfp boolean checknum(float n) { + return !Float.isNaN(n) && !Float.isInfinite(n) && Float.isFinite(n); + } + + public static strictfp double random(double min, double max) { + return (double)((int)min + random.nextInt((int)max - (int)min)) + (random.nextBoolean() ? random.nextDouble() : -random.nextDouble()); + } + + public static strictfp Location[] calcFrontEntityPositions(Player player, Entity target) { + if (target == null) { + Location l = player.getLocation().clone().add(0.0, 3.0, 0.0); + return new Location[]{l, l, l}; + } else { + Maths.Vec pV = new Maths.Vec(player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ()); + Maths.Vec tV = new Maths.Vec(target.getLocation().getX(), target.getLocation().getY(), target.getLocation().getZ()); + Maths.Vec mp = getMidpoint(pV, tV); + Location[] arr = new Location[13]; + Location mpl = new Location(player.getWorld(), mp.getX(), mp.getY(), mp.getZ()); + lookAt(mpl, target.getLocation()); + arr[0] = mpl.clone(); + mpl.setYaw(mpl.getYaw() - 90.0F); + arr[1] = mpl.clone().add(mpl.getDirection().clone().multiply(0.5)); + mpl.setYaw(mpl.getYaw() + 180.0F); + arr[2] = mpl.add(mpl.getDirection().multiply(0.5)); + arr[3] = target.getLocation().clone(); + arr[4] = target.getLocation().clone().add(0.08, 0.0, 0.0); + arr[5] = target.getLocation().clone().add(0.0, 0.0, 0.08); + arr[6] = target.getLocation().clone().add(-0.08, 0.0, 0.0); + arr[7] = target.getLocation().clone().add(0.0, 0.0, -0.08); + arr[8] = target.getLocation().clone().add(0.21, 0.0, 0.0); + arr[9] = target.getLocation().clone().add(0.0, 0.0, 0.21); + arr[10] = target.getLocation().clone().add(0.0, 0.0, -0.21); + arr[11] = target.getLocation().clone().add(-0.21, 0.0, 0.0); + arr[12] = target.getLocation().clone().add(0.21, 0.0, -0.21); + + for (Location l : arr) { + l.add(0.0, 0.425, 0.0); + } + + return arr; + } + } + + public static strictfp int not(int i, int not, int alt) { + return i == not ? alt : i; + } + + public static strictfp long not(long i, long not, long alt) { + return i == not ? alt : i; + } + + public static strictfp double not(double i, double not, double alt) { + return i == not ? alt : i; + } + + public static strictfp float not(float i, float not, float alt) { + return i == not ? alt : i; + } + + public static strictfp int notZero(int i, int alt) { + return not(i, 0, alt); + } + + public static strictfp long notZero(long i, long alt) { + return not(i, 0L, alt); + } + + public static strictfp double notZero(double i, double alt) { + return not(i, 0.0, alt); + } + + public static strictfp float notZero(float i, float alt) { + return not(i, 0.0F, alt); + } + + public static strictfp Location calcMainNpcPosition(Stats stats, Player p, double offset) { + Random random = new Random(); + double dx = random.nextBoolean() ? random.nextDouble() : -random.nextDouble(); + double dy = random.nextBoolean() ? random.nextDouble() : -random.nextDouble(); + double dz = random.nextBoolean() ? random.nextDouble() : -random.nextDouble(); + float yaw = p.getLocation().clone().getYaw() + random.nextFloat() * 3.141592F; + float pitch = p.getLocation().clone().getPitch() + random.nextFloat() * 3.141592F; + NPC npc = stats.getMainNpc(); + double distance = npc != null && npc.isSpawned() ? 25.0 - Math.min(22.4, (double)npc.getSpawnedTicks() / 5.0) : 9.0; + Location tp = p.getLocation() + .clone() + .add(p.getLocation().getDirection().clone().multiply(-distance - random.nextDouble())) + .add(0.0, 2.0, 0.0) + .add(dx, dy, dz) + .add(offset / 1.08, offset / 1.02, offset / 1.08); + return new Location(tp.getWorld(), tp.getX(), tp.getY(), tp.getZ(), yaw, pitch); + } + + public static strictfp double divMinByMax(double a, double b) { + return b > a ? a / b : b / a; + } + + public static strictfp double balance(List n) { + return divMinByMax(average(n), max(n)); + } + + public static strictfp double average(List n) { + return n.stream().mapToDouble(Number::doubleValue).sum() / (double)n.size(); + } + + public static strictfp double max(double... array) { + if (array != null && array.length != 0) { + if (array.length == 1) { + return array[0]; + } else { + double max = array[0]; + + for (int i = 1; i < array.length; i++) { + max = Math.max(max, array[i]); + } + + return max; + } + } else { + return Double.NaN; + } + } + + public static strictfp Object intcheckSetB(String to, Object fhash, Object aihash) { + try { + Class intcheckB = Class.forName(to); + Field fingerprintB = intcheckB.getDeclaredField("integrityDataFingerprint_b"); + Field arrinfoB = intcheckB.getDeclaredField("integrityDataArrInfo_b"); + + try { + MCAccess.secureSetFinalStatic(fingerprintB, fhash); + MCAccess.secureSetFinalStatic(arrinfoB, aihash); + } catch (Exception ignored) { + return null; + } + + return to.replace("z_", "8F_"); + } catch (Throwable ignoredEx) { + throw new ArithmeticException(); + } + } + + public static strictfp double max(List list) { + if (list != null && !list.isEmpty()) { + if (list.size() == 1) { + return list.get(0); + } else { + double max = list.get(0); + + for (int i = 1; i < list.size(); i++) { + max = Math.max(max, list.get(i)); + } + + return max; + } + } else { + return Double.NaN; + } + } + + public static strictfp double min(double... array) { + if (array != null && array.length != 0) { + if (array.length == 1) { + return array[0]; + } else { + double min = array[0]; + + for (int i = 1; i < array.length; i++) { + min = Math.min(min, array[i]); + } + + return min; + } + } else { + return Double.NaN; + } + } + + public static strictfp double min(List list) { + if (list != null && !list.isEmpty()) { + if (list.size() == 1) { + return list.get(0); + } else { + double max = list.get(0); + + for (int i = 1; i < list.size(); i++) { + max = Math.min(max, list.get(i)); + } + + return max; + } + } else { + return Double.NaN; + } + } + + public static strictfp void lookAt(Location loc, Location target) { + double dx = target.getX() - loc.getX(); + double dy = target.getY() - loc.getY(); + double dz = target.getZ() - loc.getZ(); + double xzd = Math.sqrt(dx * dx + dz * dz); + double yd = Math.sqrt(xzd * xzd + dy * dy); + double yaw = Math.toDegrees(Math.atan2(dz, dx)) - 90.0; + if (yaw < 0.0) { + yaw += 360.0; + } + + double pitch = -Math.toDegrees(Math.atan2(dy, yd)); + loc.setYaw((float)yaw); + loc.setPitch((float)pitch); + } + + private static strictfp Maths.Vec getMidpoint(Maths.Vec a, Maths.Vec b) { + return new Maths.Vec((a.getX() + b.getX()) / 2.0, (a.getY() + b.getY()) / 2.0, (a.getZ() + b.getZ()) / 2.0); + } + + public static strictfp double mean(double[] data) { + try { + FourthMoment m4 = new FourthMoment(); + Mean mean = new Mean(m4); + mean.setData(data); + return mean.evaluate(); + } catch (Exception ignored) { + return 0.0; + } + } + + public static strictfp double variance(double[] data) { + try { + FourthMoment m4 = new FourthMoment(); + Variance var = new Variance(m4); + var.setData(data); + return var.evaluate(); + } catch (Exception ignoredEx) { + return 0.0; + } + } + + public static strictfp double skewness(double[] data) { + try { + FourthMoment m4 = new FourthMoment(); + Skewness sk = new Skewness(m4); + sk.setData(data); + return sk.evaluate(); + } catch (Exception ignoredErr) { + return 0.0; + } + } + + public static strictfp double kurtosis(double[] data) { + try { + FourthMoment m4 = new FourthMoment(); + Kurtosis k = new Kurtosis(m4); + k.setData(data); + return k.evaluate(); + } catch (Exception ignored) { + return 0.0; + } + } + + public static strictfp double median(double[] data) { + try { + if (data != null && data.length >= 2) { + Arrays.sort(data); + return data.length % 2 == 0 ? (data[data.length / 2 - 1] + data[data.length / 2]) / 2.0 : data[data.length / 2]; + } else { + return 0.0; + } + } catch (Exception ignoredEx) { + return 0.0; + } + } + + public static strictfp double ldev(double[] data) { + try { + double mean = mean(data); + double ldev = Double.NaN; + double lowest = 1.0E30; + + for (double n : data) { + double d = Math.abs(mean - n); + if (d < lowest) { + ldev = n; + lowest = d; + } + } + + return ldev; + } catch (Exception ignored) { + return 0.0; + } + } + + public static strictfp double hdev(double[] data) { + try { + double mean = mean(data); + double hdev = Double.NaN; + double highest = Double.MIN_VALUE; + + for (double n : data) { + double d = Math.abs(mean - n); + if (d > highest) { + hdev = n; + highest = d; + } + } + + return hdev; + } catch (Exception ignoredEx) { + return 0.0; + } + } + + public static strictfp double adev(double[] data) { + try { + double mean = mean(data); + double[] dev = new double[data.length]; + + for (int i = 0; i < data.length; i++) { + dev[i] = Math.abs(mean - data[i]); + } + + return NumberStorage.make(dev).average(); + } catch (Exception ignored) { + return 0.0; + } + } + + public static strictfp BigInteger factorial(long l) { + return factorial(big(l)); + } + + public static strictfp BigInteger factorial(BigInteger bi) { + BigInteger inc = big1(); + BigInteger fac = big1(); + + for (int c = 1; c <= bi.intValue(); c++) { + fac = fac.multiply(inc); + inc = inc.add(BigInteger.ONE); + } + + return fac; + } + + public static strictfp BigInteger big0() { + return new BigInteger("0"); + } + + public static strictfp BigInteger big1() { + return new BigInteger("1"); + } + + public static strictfp BigInteger bigNeg1() { + return new BigInteger("-1"); + } + + public static strictfp BigInteger big10() { + return new BigInteger("10"); + } + + public static strictfp BigInteger big(long l) { + return l == 0L ? big0() : (l == 1L ? big1() : (l == -1L ? bigNeg1() : (l == 10L ? big10() : BigInteger.valueOf(l)))); + } + + public static strictfp BigInteger mulFactorials(long a, long b) { + return factorial(a).multiply(factorial(b)); + } + + public static strictfp BigInteger mulFactorials(BigInteger a, BigInteger b) { + return factorial(a).multiply(factorial(b)); + } + + public static strictfp BigInteger divFactorials(long a, long b) { + return factorial(a).divide(factorial(b)); + } + + public static strictfp BigInteger divFactorials(BigInteger a, BigInteger b) { + return factorial(a).divide(factorial(b)); + } + + public static strictfp BigInteger powBig(BigInteger n, int exp) { + return n.pow(exp); + } + + public static strictfp BigInteger powBig(long n, int exp) { + return powBig(big(n), exp); + } + + public static strictfp BigInteger powBig(long n, long exp) { + return powBig(n, Math.toIntExact(exp)); + } + + public static strictfp BigInteger combine_f(long n, long m) { + return factorial(n + m - 1L).divide(mulFactorials(m, n - 1L)); + } + + public static strictfp BigInteger combine_f(long n, long mL, long mH) { + BigInteger c = big0(); + + for (long m = mL; m <= mH; m++) { + c = c.add(combine_f(n, m)); + } + + return c; + } + + public static strictfp BigInteger combine_p(long n, long m) { + return powBig(n, m); + } + + public static strictfp BigInteger combine_p(long n, long mL, long mH) { + BigInteger c = big0(); + + for (long m = mL; m <= mH; m++) { + c = c.add(combine_p(n, m)); + } + + return c; + } + + public static strictfp double root(double n, double exp) { + return Math.pow(n, 1.0 / exp); + } + + public static strictfp double divSafely(int a, int b) { + return (double)(notZero(a, 1) / notZero(b, 1)); + } + + public static strictfp double divSafely(long a, long b) { + return (double)(notZero(a, 1L) / notZero(b, 1L)); + } + + public static strictfp int divAndFloor(int a, int b) { + return floor((double)a / (double)b); + } + + public static strictfp long divAndFloor(long a, long b) { + return floor64((double)a / (double)b); + } + + public static strictfp double arithmeticMean(double... arr) { + if (arr != null && arr.length != 0) { + if (arr.length == 1) { + return arr[0]; + } else { + double am = arr[0]; + + for (int i = 1; i < arr.length; i++) { + am += arr[i]; + } + + return am / (double)arr.length; + } + } else { + return Double.NaN; + } + } + + public static strictfp double geometricMean(double... arr) { + if (arr != null && arr.length != 0) { + if (arr.length == 1) { + return arr[0]; + } else { + double gm = arr[0]; + + for (int i = 1; i < arr.length; i++) { + gm *= arr[i]; + } + + return root(gm, (double)arr.length); + } + } else { + return Double.NaN; + } + } + + public static strictfp double harmonicMean(double[] arr) { + if (arr != null && arr.length != 0) { + if (arr.length == 1) { + return arr[0]; + } else { + double hm = 0.0; + + for (double anArr : arr) { + hm += 1.0 / anArr; + } + + return (double)arr.length / hm; + } + } else { + return Double.NaN; + } + } + + public static strictfp double roundBD(double value, int places) { + if (places < 0) { + throw new IllegalArgumentException("Illegal number of places: " + places); + } else { + return new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue(); + } + } + + public static strictfp double fixUnsupportedFP(double n) { + return n % 1.0 == 0.0 ? n : roundBD(n, 15); + } + + public static strictfp Maths getNewApInstance() { + return newApInstance; + } + + public static strictfp class Vec { + final double x; + final double y; + final double z; + + @Override + public strictfp String toString() { + return "Maths.Vec(x=" + this.getX() + ", y=" + this.getY() + ", z=" + this.getZ() + ")"; + } + + public Vec(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + public strictfp double getX() { + return this.x; + } + + public strictfp double getY() { + return this.y; + } + + public strictfp double getZ() { + return this.z; + } + } +} diff --git a/src/main/java/rip/reflex/util/math/SafeLong.java b/src/main/java/rip/reflex/util/math/SafeLong.java new file mode 100644 index 0000000..8b588ec --- /dev/null +++ b/src/main/java/rip/reflex/util/math/SafeLong.java @@ -0,0 +1,153 @@ +package rip.reflex.util.math; + +import rip.reflex.util.misc.Validate; + +public class SafeLong extends Number { + private long value; + + public SafeLong() { + this(0); + } + + @Override + public int intValue() { + return this.getInt(); + } + + @Override + public long longValue() { + return this.value; + } + + @Override + public float floatValue() { + return (float)this.value; + } + + @Override + public double doubleValue() { + return (double)this.value; + } + + public SafeLong(Long value) { + this.value = Validate.notNull(value, "Long value cannot be null when instantiating a SafeLong"); + } + + public SafeLong(Integer value) { + this.value = (long)Validate.notNull(value, "Integer value cannot be null when instantiating a SafeLong").intValue(); + } + + public SafeLong set(long value) { + this.value = value; + return this; + } + + public long get() { + return this.value; + } + + public int getInt() { + return this.getInt(this.value > 0L ? Integer.MAX_VALUE : (this.value < 0L ? Integer.MIN_VALUE : 0)); + } + + public int getInt(int alt) { + try { + return Math.toIntExact(this.value); + } catch (ArithmeticException ignored) { + return alt; + } + } + + public SafeLong add(SafeLong l) { + return this.add(l.get()); + } + + public SafeLong add(long l) { + if (this.value == Long.MAX_VALUE && Math.abs(l) > 0L) { + throw new ArithmeticException("Positive long overflow: MAX_VALUE+" + Math.abs(l)); + } else { + this.value = this.value + Math.abs(l); + return this; + } + } + + public SafeLong addSafely(SafeLong l) { + return this.addSafely(l.get()); + } + + public SafeLong addSafely(long l) { + if (this.value == Long.MAX_VALUE && Math.abs(l) > 0L) { + return this; + } else { + this.value = this.value + Math.abs(l); + return this; + } + } + + public SafeLong subtract(SafeLong l) { + return this.subtract(l.get()); + } + + public SafeLong subtract(long l) { + this.value = this.value - Math.abs(l); + return this; + } + + public SafeLong subtractSafely(SafeLong l) { + return this.subtractSafely(l.get()); + } + + public SafeLong subtractSafely(long l) { + if (this.value == Long.MIN_VALUE && Math.abs(l) > 0L) { + throw new ArithmeticException("Negative long overflow: MIN_VALUE-" + Math.abs(l)); + } else { + this.value = this.value - Math.abs(l); + return this; + } + } + + public SafeLong multiply(SafeLong l) { + return this.multiply(l.get()); + } + + public SafeLong multiply(long l) { + this.value *= l; + return this; + } + + public SafeLong divide(SafeLong l) { + return this.divide(l.get()); + } + + public SafeLong divide(long l) { + if (this.value % Validate.notZero(l, "Divide by zero") != 0L) { + throw new ArithmeticException("The value (" + this.value + ") is not a multiple of " + l); + } else { + this.value /= l; + return this; + } + } + + public SafeLong divideAndFloor(SafeLong l) { + return this.divideAndFloor(l.get()); + } + + public SafeLong divideAndFloor(long l) { + this.value = Maths.divAndFloor(this.value, Validate.notZero(l, "Divide by zero")); + return this; + } + + public SafeLong copy() { + return new SafeLong(this.value); + } + + @Override + public String toString() { + return Long.toString(this.value); + } + + @Override + public int hashCode() { + return Long.hashCode(this.value); + } +} diff --git a/src/main/java/rip/reflex/util/math/UniqueRandom.java b/src/main/java/rip/reflex/util/math/UniqueRandom.java new file mode 100644 index 0000000..386cbd4 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/UniqueRandom.java @@ -0,0 +1,138 @@ +package rip.reflex.util.math; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; + +public class UniqueRandom extends Random { + private static final List list = new ArrayList<>(); + private final ConcurrentHashMap, List> cache = new ConcurrentHashMap<>(); + + public UniqueRandom() { + this(System.currentTimeMillis()); + } + + public UniqueRandom(long seed) { + super(seed); + list.add(this); + } + + public byte[] randomByteStream(int length) { + byte[] stream = new byte[length]; + + for (int i = 0; i < stream.length; i++) { + stream[i] = (byte)(this.nextBoolean() ? this.nextInt(128) : -this.nextInt(-129)); + } + + try { + if (this.contains(stream)) { + return this.randomByteStream(length); + } + } catch (StackOverflowError ignored) { + throw new OutOfMemoryError("This UniqueRandom object is out! Create a new one"); + } + + return (byte[])this.add(stream); + } + + @Override + public int nextInt(int bound) { + int i = super.nextInt(bound); + + try { + if (this.contains(i)) { + return this.nextInt(bound); + } + } catch (StackOverflowError ignoredEx) { + throw new OutOfMemoryError("This UniqueRandom object is out! Create a new one"); + } + + return (Integer)this.add(i); + } + + @Override + public int nextInt() { + int i = super.nextInt(); + + try { + if (this.contains(i)) { + return this.nextInt(); + } + } catch (StackOverflowError ignored) { + throw new OutOfMemoryError("This UniqueRandom object is out! Create a new one"); + } + + return (Integer)this.add(i); + } + + @Override + public long nextLong() { + long i = super.nextLong(); + + try { + if (this.contains(i)) { + return this.nextLong(); + } + } catch (StackOverflowError ignoredEx) { + throw new OutOfMemoryError("This UniqueRandom object is out! Create a new one"); + } + + return (Long)this.add(i); + } + + @Override + public double nextDouble() { + double i = super.nextDouble(); + + try { + if (this.contains(i)) { + return this.nextDouble(); + } + } catch (StackOverflowError ignored) { + throw new OutOfMemoryError("This UniqueRandom object is out! Create a new one"); + } + + return (Double)this.add(i); + } + + @Override + public float nextFloat() { + float i = super.nextFloat(); + + try { + if (this.contains(i)) { + return this.nextFloat(); + } + } catch (StackOverflowError ignoredEx) { + throw new OutOfMemoryError("This UniqueRandom object is out! Create a new one"); + } + + return (Float)this.add(i); + } + + private boolean contains(Object o) { + return this.get(o.getClass()).contains(o); + } + + private Object add(Object o) { + this.get(o.getClass()).add(o); + return o; + } + + private List get(Class type) { + if (!this.cache.containsKey(type)) { + this.cache.put(type, new ArrayList<>()); + } + + return this.cache.get(type); + } + + public static List getList() { + return list; + } + + public ConcurrentHashMap, List> getCache() { + return this.cache; + } +} diff --git a/src/main/java/rip/reflex/util/math/Vec3.java b/src/main/java/rip/reflex/util/math/Vec3.java new file mode 100644 index 0000000..aed995d --- /dev/null +++ b/src/main/java/rip/reflex/util/math/Vec3.java @@ -0,0 +1,238 @@ +package rip.reflex.util.math; + +public class Vec3 { + private double x; + private double y; + private double z; + + public Vec3() { + this(0.0); + } + + public Vec3(double cor) { + this(cor, cor, cor); + } + + public Vec3(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + public Vec3 copy() { + return new Vec3(this.x, this.y, this.z); + } + + public Vec3 setX(double x) { + this.x = x; + return this; + } + + public Vec3 setY(double y) { + this.y = y; + return this; + } + + public Vec3 setZ(double z) { + this.z = z; + return this; + } + + public Vec3 add(double n) { + return this.add(n, n, n); + } + + public Vec3 add(Vec3 v) { + return this.add(v.x, v.y, v.z); + } + + public Vec3 add(double x, double y, double z) { + this.x += x; + this.y += y; + this.z += z; + return this; + } + + public Vec3 subtract(double n) { + return this.subtract(n, n, n); + } + + public Vec3 subtract(Vec3 v) { + return this.subtract(v.x, v.y, v.z); + } + + public Vec3 subtract(double x, double y, double z) { + this.x -= x; + this.y -= y; + this.z -= z; + return this; + } + + public Vec3 multiply(double n) { + return this.multiply(n, n, n); + } + + public Vec3 multiply(Vec3 v) { + return this.multiply(v.x, v.y, v.z); + } + + public Vec3 multiply(double x, double y, double z) { + this.x *= x; + this.y *= y; + this.z *= z; + return this; + } + + public Vec3 divide(double n) { + return this.divide(n, n, n); + } + + public Vec3 divide(Vec3 v) { + return this.divide(v.x, v.y, v.z); + } + + public Vec3 divide(double x, double y, double z) { + this.x /= x; + this.y /= y; + this.z /= z; + return this; + } + + public Vec3 pow(double n) { + return this.pow(n, n, n); + } + + public Vec3 pow(Vec3 v) { + return this.pow(v.x, v.y, v.z); + } + + public Vec3 pow(double x, double y, double z) { + this.x = Math.pow(this.x, x); + this.y = Math.pow(this.y, y); + this.z = Math.pow(this.z, z); + return this; + } + + public Vec3 sqrt() { + this.x = Math.sqrt(this.x); + this.y = Math.sqrt(this.y); + this.z = Math.sqrt(this.z); + return this; + } + + public Vec3 cbrt() { + this.x = Math.cbrt(this.x); + this.y = Math.cbrt(this.y); + this.z = Math.cbrt(this.z); + return this; + } + + public Vec3 abs() { + this.x = Math.abs(this.x); + this.y = Math.abs(this.y); + this.z = Math.abs(this.z); + return this; + } + + public Vec3 negate() { + this.x = -Math.abs(this.x); + this.y = -Math.abs(this.y); + this.z = -Math.abs(this.z); + return this; + } + + public Vec3 angle(Vec3 v) { + return this.angle(v.x, v.y, v.z); + } + + public Vec3 angle(double x, double y, double z) { + return new Vec3(x - this.x, y - this.y, z - this.z); + } + + public double distance(Vec3 v) { + return this.distance(v.x, v.y, v.z); + } + + public double distance(double x, double y, double z) { + return Math.sqrt(Maths.square(x - this.x) + Maths.square(y - this.y) + Maths.square(z - this.z)); + } + + public double horizontalDistance(Vec3 v) { + return this.horizontalDistance(v.x, v.z); + } + + public double horizontalDistance(double x, double z) { + return Math.sqrt(Maths.square(x - this.x) + Maths.square(z - this.z)); + } + + public double verticalDistance(Vec3 v) { + return this.verticalDistance(v.y); + } + + public double verticalDistance(double y) { + return Math.abs(y - this.y); + } + + public double correlate(Vec3 v) { + return this.correlate(v.x, v.y, v.z); + } + + public double correlate(double x, double y, double z) { + return this.x / x * (this.y / y) * (this.z / z); + } + + public boolean isCodirectional(Vec3 v) { + return this.isCodirectional(v.x, v.y, v.z); + } + + public boolean isCodirectional(double x, double y, double z) { + int ax = Double.compare(this.x, 0.0); + int ay = Double.compare(this.y, 0.0); + int az = Double.compare(this.z, 0.0); + int bx = Double.compare(x, 0.0); + int by = Double.compare(y, 0.0); + int bz = Double.compare(z, 0.0); + return ax == bx && ay == by && az == bz; + } + + public boolean isHorizontallyCodirectional(Vec3 v) { + return this.isHorizontallyCodirectional(v.x, v.z); + } + + public boolean isHorizontallyCodirectional(double x, double z) { + int ax = Double.compare(this.x, 0.0); + int az = Double.compare(this.z, 0.0); + int bx = Double.compare(x, 0.0); + int bz = Double.compare(z, 0.0); + return ax == bx && az == bz; + } + + public boolean isVerticallyCodirectional(Vec3 v) { + return this.isVerticallyCodirectional(v.y); + } + + public boolean isVerticallyCodirectional(double y) { + return Double.compare(this.y, 0.0) == Double.compare(y, 0.0); + } + + public boolean equals(Vec3 v) { + return this.x == v.x && this.y == v.y && this.z == v.z; + } + + @Override + public String toString() { + return "[" + this.x + "," + this.y + "," + this.z + "]"; + } + + public double getX() { + return this.x; + } + + public double getY() { + return this.y; + } + + public double getZ() { + return this.z; + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/AbstractStorelessUnivariateStatistic.java b/src/main/java/rip/reflex/util/math/descriptive/AbstractStorelessUnivariateStatistic.java new file mode 100644 index 0000000..667adb1 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/AbstractStorelessUnivariateStatistic.java @@ -0,0 +1,66 @@ +package rip.reflex.util.math.descriptive; + +import rip.reflex.util.math.Maths; + +public abstract class AbstractStorelessUnivariateStatistic extends AbstractUnivariateStatistic implements StorelessUnivariateStatistic { + @Override + public double evaluate(double[] values) throws IllegalArgumentException { + if (values == null) { + throw new NullPointerException(""); + } else { + return this.evaluate(values, 0, values.length); + } + } + + @Override + public double evaluate(double[] values, int begin, int length) throws IllegalArgumentException { + if (this.test(values, begin, length)) { + this.clear(); + this.incrementAll(values, begin, length); + } + + return this.getResult(); + } + + @Override + public abstract StorelessUnivariateStatistic copy(); + + @Override + public abstract void clear(); + + @Override + public abstract double getResult(); + + @Override + public abstract void increment(double value); + + @Override + public void incrementAll(double[] values) throws IllegalArgumentException { + if (values == null) { + throw new NullPointerException(""); + } else { + this.incrementAll(values, 0, values.length); + } + } + + @Override + public void incrementAll(double[] values, int begin, int length) throws IllegalArgumentException { + if (this.test(values, begin, length)) { + int k = begin + length; + + for (int i = begin; i < k; i++) { + this.increment(values[i]); + } + } + } + + @Override + public boolean equals(Object object) { + return object == this; + } + + @Override + public int hashCode() { + return 31 * (31 + Maths.hash(this.getResult())) + Maths.hash((double)this.getN()); + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/AbstractUnivariateStatistic.java b/src/main/java/rip/reflex/util/math/descriptive/AbstractUnivariateStatistic.java new file mode 100644 index 0000000..b74bc8c --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/AbstractUnivariateStatistic.java @@ -0,0 +1,70 @@ +package rip.reflex.util.math.descriptive; + +public abstract class AbstractUnivariateStatistic implements UnivariateStatistic { + private double[] storedData; + + public void setData(double[] values) { + this.storedData = values == null ? null : (double[])values.clone(); + } + + public double[] getData() { + return this.storedData == null ? null : (double[])this.storedData.clone(); + } + + protected double[] getDataRef() { + return this.storedData; + } + + public void setData(double[] values, int begin, int length) throws IllegalArgumentException { + if (values == null) { + throw new NullPointerException(""); + } else if (begin >= 0 && length >= 0) { + if (begin + length > values.length) { + throw new IllegalArgumentException("number too large"); + } else { + this.storedData = new double[length]; + System.arraycopy(values, begin, this.storedData, 0, length); + } + } else { + throw new IllegalArgumentException("argument most be positive"); + } + } + + public double evaluate() throws IllegalArgumentException { + return this.evaluate(this.storedData); + } + + @Override + public double evaluate(double[] values) throws IllegalArgumentException { + this.test(values, 0, 0); + return this.evaluate(values, 0, values.length); + } + + @Override + public abstract double evaluate(double[] values, int begin, int length) throws IllegalArgumentException; + + @Override + public abstract UnivariateStatistic copy(); + + protected boolean test(double[] values, int begin, int length) throws IllegalArgumentException { + return values != null && begin >= 0 && length >= 0 && begin <= length && values.length != 0; + } + + protected boolean test(double[] values, int begin, int length, boolean allowEmpty) throws IllegalArgumentException { + return values != null && begin >= 0 && length >= 0 && begin <= length && (!allowEmpty || values.length != 0); + } + + protected boolean test(double[] values, double[] weights, int begin, int length) throws IllegalArgumentException { + return values != null && weights != null && begin >= 0 && length >= 0 && begin <= length && values.length != 0 && weights.length != 0; + } + + protected boolean test(double[] values, double[] weights, int begin, int length, boolean allowEmpty) throws IllegalArgumentException { + return values != null + && weights != null + && begin >= 0 + && length >= 0 + && begin <= length + && (!allowEmpty || values.length != 0) + && (!allowEmpty || weights.length != 0); + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/StorelessUnivariateStatistic.java b/src/main/java/rip/reflex/util/math/descriptive/StorelessUnivariateStatistic.java new file mode 100644 index 0000000..de72a37 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/StorelessUnivariateStatistic.java @@ -0,0 +1,17 @@ +package rip.reflex.util.math.descriptive; + +public interface StorelessUnivariateStatistic extends UnivariateStatistic { + void increment(double value); + + void incrementAll(double[] values) throws IllegalArgumentException; + + void incrementAll(double[] values, int begin, int length) throws IllegalArgumentException; + + double getResult(); + + long getN(); + + void clear(); + + StorelessUnivariateStatistic copy(); +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/UnivariateStatistic.java b/src/main/java/rip/reflex/util/math/descriptive/UnivariateStatistic.java new file mode 100644 index 0000000..2ed0a91 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/UnivariateStatistic.java @@ -0,0 +1,9 @@ +package rip.reflex.util.math.descriptive; + +public interface UnivariateStatistic { + double evaluate(double[] values) throws IllegalArgumentException; + + double evaluate(double[] values, int begin, int length) throws IllegalArgumentException; + + UnivariateStatistic copy(); +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/WeightedEvaluation.java b/src/main/java/rip/reflex/util/math/descriptive/WeightedEvaluation.java new file mode 100644 index 0000000..06cfd04 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/WeightedEvaluation.java @@ -0,0 +1,7 @@ +package rip.reflex.util.math.descriptive; + +public interface WeightedEvaluation { + double evaluate(double[] values, double[] weights) throws IllegalArgumentException; + + double evaluate(double[] values, double[] weights, int begin, int length) throws IllegalArgumentException; +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/moment/FirstMoment.java b/src/main/java/rip/reflex/util/math/descriptive/moment/FirstMoment.java new file mode 100644 index 0000000..2f8a639 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/moment/FirstMoment.java @@ -0,0 +1,70 @@ +package rip.reflex.util.math.descriptive.moment; + +import java.io.Serializable; +import rip.reflex.util.math.Maths; +import rip.reflex.util.math.descriptive.AbstractStorelessUnivariateStatistic; + +public class FirstMoment extends AbstractStorelessUnivariateStatistic implements Serializable { + protected long n; + protected double m1; + protected double dev; + protected double nDev; + + public FirstMoment() { + this.n = 0L; + this.m1 = Double.NaN; + this.dev = Double.NaN; + this.nDev = Double.NaN; + } + + public FirstMoment(FirstMoment original) throws NullPointerException { + copy(original, this); + } + + public static void copy(FirstMoment source, FirstMoment dest) throws NullPointerException { + Maths.checkNotNull(source); + Maths.checkNotNull(dest); + dest.setData(source.getDataRef()); + dest.n = source.n; + dest.m1 = source.m1; + dest.dev = source.dev; + dest.nDev = source.nDev; + } + + @Override + public void increment(double d) { + if (this.n == 0L) { + this.m1 = 0.0; + } + + this.n++; + double n0 = (double)this.n; + this.dev = d - this.m1; + this.nDev = this.dev / n0; + this.m1 = this.m1 + this.nDev; + } + + @Override + public void clear() { + this.m1 = Double.NaN; + this.n = 0L; + this.dev = Double.NaN; + this.nDev = Double.NaN; + } + + @Override + public double getResult() { + return this.m1; + } + + @Override + public long getN() { + return this.n; + } + + public FirstMoment copy() { + FirstMoment result = new FirstMoment(); + copy(this, result); + return result; + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/moment/FourthMoment.java b/src/main/java/rip/reflex/util/math/descriptive/moment/FourthMoment.java new file mode 100644 index 0000000..c252553 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/moment/FourthMoment.java @@ -0,0 +1,48 @@ +package rip.reflex.util.math.descriptive.moment; + +import java.io.Serializable; +import rip.reflex.util.math.Maths; + +public class FourthMoment extends ThirdMoment implements Serializable { + private double m4 = Double.NaN; + + public static void copy(FourthMoment source, FourthMoment dest) throws NullPointerException { + Maths.checkNotNull(source); + Maths.checkNotNull(dest); + ThirdMoment.copy(source, dest); + dest.m4 = source.m4; + } + + @Override + public void increment(double d) { + if (this.n < 1L) { + this.m4 = 0.0; + this.m3 = 0.0; + this.m2 = 0.0; + this.m1 = 0.0; + } + + double prevM3 = this.m3; + double prevM2 = this.m2; + super.increment(d); + double n0 = (double)this.n; + this.m4 = this.m4 - 4.0 * this.nDev * prevM3 + 6.0 * this.nDevSq * prevM2 + (n0 * n0 - 3.0 * (n0 - 1.0)) * this.nDevSq * this.nDevSq * (n0 - 1.0) * n0; + } + + @Override + public double getResult() { + return this.m4; + } + + @Override + public void clear() { + super.clear(); + this.m4 = Double.NaN; + } + + public FourthMoment copy() { + FourthMoment result = new FourthMoment(); + copy(this, result); + return result; + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/moment/Kurtosis.java b/src/main/java/rip/reflex/util/math/descriptive/moment/Kurtosis.java new file mode 100644 index 0000000..512b655 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/moment/Kurtosis.java @@ -0,0 +1,94 @@ +package rip.reflex.util.math.descriptive.moment; + +import java.io.Serializable; +import java.util.stream.IntStream; +import rip.reflex.util.math.Maths; +import rip.reflex.util.math.descriptive.AbstractStorelessUnivariateStatistic; + +public class Kurtosis extends AbstractStorelessUnivariateStatistic implements Serializable { + protected FourthMoment moment; + protected boolean incMoment; + + public Kurtosis() { + this.incMoment = true; + this.moment = new FourthMoment(); + } + + public Kurtosis(FourthMoment m4) { + this.incMoment = false; + this.moment = m4; + } + + public Kurtosis(Kurtosis original) throws NullPointerException { + copy(original, this); + } + + public static void copy(Kurtosis source, Kurtosis dest) throws NullPointerException { + Maths.checkNotNull(source); + Maths.checkNotNull(dest); + dest.setData(source.getDataRef()); + dest.moment = source.moment.copy(); + dest.incMoment = source.incMoment; + } + + @Override + public void increment(double d) { + if (this.incMoment) { + this.moment.increment(d); + } + } + + @Override + public double getResult() { + double kurtosis = Double.NaN; + if (this.moment.getN() > 3L) { + double variance = this.moment.m2 / (double)(this.moment.n - 1L); + if (this.moment.n > 3L && !(variance < 1.0E-19)) { + double n = (double)this.moment.n; + kurtosis = (n * (n + 1.0) * this.moment.getResult() - 3.0 * this.moment.m2 * this.moment.m2 * (n - 1.0)) + / ((n - 1.0) * (n - 2.0) * (n - 3.0) * variance * variance); + } else { + kurtosis = 0.0; + } + } + + return kurtosis; + } + + @Override + public void clear() { + if (this.incMoment) { + this.moment.clear(); + } + } + + @Override + public long getN() { + return this.moment.getN(); + } + + @Override + public double evaluate(double[] values, int begin, int length) throws IllegalArgumentException { + double kurt = Double.NaN; + if (this.test(values, begin, length) && length > 3) { + Variance variance = new Variance(); + variance.incrementAll(values, begin, length); + double mean = variance.moment.m1; + double stdDev = Math.sqrt(variance.getResult()); + double accum3 = IntStream.range(begin, begin + length).mapToDouble(i -> Math.pow(values[i] - mean, 4.0)).sum(); + accum3 /= Math.pow(stdDev, 4.0); + double n0 = (double)length; + double coefficientOne = n0 * (n0 + 1.0) / ((n0 - 1.0) * (n0 - 2.0) * (n0 - 3.0)); + double termTwo = 3.0 * Math.pow(n0 - 1.0, 2.0) / ((n0 - 2.0) * (n0 - 3.0)); + kurt = coefficientOne * accum3 - termTwo; + } + + return kurt; + } + + public Kurtosis copy() { + Kurtosis result = new Kurtosis(); + copy(this, result); + return result; + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/moment/Mean.java b/src/main/java/rip/reflex/util/math/descriptive/moment/Mean.java new file mode 100644 index 0000000..16caa7c --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/moment/Mean.java @@ -0,0 +1,96 @@ +package rip.reflex.util.math.descriptive.moment; + +import java.io.Serializable; +import java.util.stream.IntStream; +import rip.reflex.util.math.Maths; +import rip.reflex.util.math.descriptive.AbstractStorelessUnivariateStatistic; +import rip.reflex.util.math.descriptive.WeightedEvaluation; +import rip.reflex.util.math.descriptive.summary.Sum; + +public class Mean extends AbstractStorelessUnivariateStatistic implements Serializable, WeightedEvaluation { + protected FirstMoment moment; + protected boolean incMoment; + + public Mean() { + this.incMoment = true; + this.moment = new FirstMoment(); + } + + public Mean(FirstMoment m1) { + this.moment = m1; + this.incMoment = false; + } + + public Mean(Mean original) throws NullPointerException { + copy(original, this); + } + + public static void copy(Mean source, Mean dest) throws NullPointerException { + Maths.checkNotNull(source); + Maths.checkNotNull(dest); + dest.setData(source.getDataRef()); + dest.incMoment = source.incMoment; + dest.moment = source.moment.copy(); + } + + @Override + public void increment(double d) { + if (this.incMoment) { + this.moment.increment(d); + } + } + + @Override + public void clear() { + if (this.incMoment) { + this.moment.clear(); + } + } + + @Override + public double getResult() { + return this.moment.m1; + } + + @Override + public long getN() { + return this.moment.getN(); + } + + @Override + public double evaluate(double[] values, int begin, int length) throws IllegalArgumentException { + if (this.test(values, begin, length)) { + Sum sum = new Sum(); + double sampleSize = (double)length; + double xbar = sum.evaluate(values, begin, length) / sampleSize; + double correction = IntStream.range(begin, begin + length).mapToDouble(i -> values[i] - xbar).sum(); + return xbar + correction / sampleSize; + } else { + return Double.NaN; + } + } + + @Override + public double evaluate(double[] values, double[] weights, int begin, int length) throws IllegalArgumentException { + if (this.test(values, weights, begin, length)) { + Sum sum = new Sum(); + double sumw = sum.evaluate(weights, begin, length); + double xbarw = sum.evaluate(values, weights, begin, length) / sumw; + double correction = IntStream.range(begin, begin + length).mapToDouble(i -> weights[i] * (values[i] - xbarw)).sum(); + return xbarw + correction / sumw; + } else { + return Double.NaN; + } + } + + @Override + public double evaluate(double[] values, double[] weights) throws IllegalArgumentException { + return this.evaluate(values, weights, 0, values.length); + } + + public Mean copy() { + Mean result = new Mean(); + copy(this, result); + return result; + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/moment/SecondMoment.java b/src/main/java/rip/reflex/util/math/descriptive/moment/SecondMoment.java new file mode 100644 index 0000000..00230a4 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/moment/SecondMoment.java @@ -0,0 +1,51 @@ +package rip.reflex.util.math.descriptive.moment; + +import java.io.Serializable; +import rip.reflex.util.math.Maths; + +public class SecondMoment extends FirstMoment implements Serializable { + protected double m2; + + public SecondMoment() { + this.m2 = Double.NaN; + } + + public SecondMoment(SecondMoment original) throws NullPointerException { + super(original); + this.m2 = original.m2; + } + + public static void copy(SecondMoment source, SecondMoment dest) throws NullPointerException { + Maths.checkNotNull(source); + Maths.checkNotNull(dest); + FirstMoment.copy(source, dest); + dest.m2 = source.m2; + } + + @Override + public void increment(double d) { + if (this.n < 1L) { + this.m1 = this.m2 = 0.0; + } + + super.increment(d); + this.m2 = this.m2 + ((double)this.n - 1.0) * this.dev * this.nDev; + } + + @Override + public void clear() { + super.clear(); + this.m2 = Double.NaN; + } + + @Override + public double getResult() { + return this.m2; + } + + public SecondMoment copy() { + SecondMoment result = new SecondMoment(); + copy(this, result); + return result; + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/moment/Skewness.java b/src/main/java/rip/reflex/util/math/descriptive/moment/Skewness.java new file mode 100644 index 0000000..9e51a1e --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/moment/Skewness.java @@ -0,0 +1,98 @@ +package rip.reflex.util.math.descriptive.moment; + +import java.io.Serializable; +import java.util.stream.IntStream; +import rip.reflex.util.math.Maths; +import rip.reflex.util.math.descriptive.AbstractStorelessUnivariateStatistic; + +public class Skewness extends AbstractStorelessUnivariateStatistic implements Serializable { + protected ThirdMoment moment = null; + protected boolean incMoment; + + public Skewness() { + this.incMoment = true; + this.moment = new ThirdMoment(); + } + + public Skewness(ThirdMoment m3) { + this.incMoment = false; + this.moment = m3; + } + + public Skewness(Skewness original) throws NullPointerException { + copy(original, this); + } + + public static void copy(Skewness source, Skewness dest) throws NullPointerException { + Maths.checkNotNull(source); + Maths.checkNotNull(dest); + dest.setData(source.getDataRef()); + dest.moment = new ThirdMoment(source.moment.copy()); + dest.incMoment = source.incMoment; + } + + @Override + public void increment(double d) { + if (this.incMoment) { + this.moment.increment(d); + } + } + + @Override + public double getResult() { + if (this.moment.n < 3L) { + return Double.NaN; + } else { + double variance = this.moment.m2 / (double)(this.moment.n - 1L); + if (variance < 1.0E-19) { + return 0.0; + } else { + double n0 = (double)this.moment.getN(); + return n0 * this.moment.m3 / ((n0 - 1.0) * (n0 - 2.0) * Math.sqrt(variance) * variance); + } + } + } + + @Override + public long getN() { + return this.moment.getN(); + } + + @Override + public void clear() { + if (this.incMoment) { + this.moment.clear(); + } + } + + @Override + public double evaluate(double[] values, int begin, int length) throws IllegalArgumentException { + double skew = Double.NaN; + if (this.test(values, begin, length) && length > 2) { + Mean mean = new Mean(); + double m = mean.evaluate(values, begin, length); + double accum = 0.0; + double accum2 = 0.0; + + for (int i = begin; i < begin + length; i++) { + double d = values[i] - m; + accum += d * d; + accum2 += d; + } + + double variance = (accum - accum2 * accum2 / (double)length) / (double)(length - 1); + double accum3 = IntStream.range(begin, begin + length).mapToDouble(i -> values[i] - m).map(dx -> dx * dx * dx).sum(); + accum3 /= variance * Math.sqrt(variance); + double n0 = (double)length; + skew = n0 / ((n0 - 1.0) * (n0 - 2.0)) * accum3; + } + + return skew; + } + + public Skewness copy() { + Skewness result = new Skewness(); + copy(this, result); + return result; + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/moment/ThirdMoment.java b/src/main/java/rip/reflex/util/math/descriptive/moment/ThirdMoment.java new file mode 100644 index 0000000..7221737 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/moment/ThirdMoment.java @@ -0,0 +1,57 @@ +package rip.reflex.util.math.descriptive.moment; + +import java.io.Serializable; +import rip.reflex.util.math.Maths; + +public class ThirdMoment extends SecondMoment implements Serializable { + protected double m3; + protected double nDevSq; + + public ThirdMoment() { + this.m3 = Double.NaN; + this.nDevSq = Double.NaN; + } + + public ThirdMoment(ThirdMoment original) throws NullPointerException { + copy(original, this); + } + + public static void copy(ThirdMoment source, ThirdMoment dest) throws NullPointerException { + Maths.checkNotNull(source); + Maths.checkNotNull(dest); + SecondMoment.copy(source, dest); + dest.m3 = source.m3; + dest.nDevSq = source.nDevSq; + } + + @Override + public void increment(double d) { + if (this.n < 1L) { + this.m3 = this.m2 = this.m1 = 0.0; + } + + double prevM2 = this.m2; + super.increment(d); + this.nDevSq = this.nDev * this.nDev; + double n0 = (double)this.n; + this.m3 = this.m3 - 3.0 * this.nDev * prevM2 + (n0 - 1.0) * (n0 - 2.0) * this.nDevSq * this.dev; + } + + @Override + public double getResult() { + return this.m3; + } + + @Override + public void clear() { + super.clear(); + this.m3 = Double.NaN; + this.nDevSq = Double.NaN; + } + + public ThirdMoment copy() { + ThirdMoment result = new ThirdMoment(); + copy(this, result); + return result; + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/moment/Variance.java b/src/main/java/rip/reflex/util/math/descriptive/moment/Variance.java new file mode 100644 index 0000000..501e6a5 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/moment/Variance.java @@ -0,0 +1,200 @@ +package rip.reflex.util.math.descriptive.moment; + +import java.io.Serializable; +import java.util.stream.IntStream; +import rip.reflex.util.math.Maths; +import rip.reflex.util.math.descriptive.AbstractStorelessUnivariateStatistic; +import rip.reflex.util.math.descriptive.WeightedEvaluation; + +public class Variance extends AbstractStorelessUnivariateStatistic implements Serializable, WeightedEvaluation { + protected SecondMoment moment = null; + protected boolean incMoment = true; + private boolean isBiasCorrected = true; + + public Variance() { + this.moment = new SecondMoment(); + } + + public Variance(SecondMoment m2) { + this.incMoment = false; + this.moment = m2; + } + + public Variance(boolean isBiasCorrected) { + this.moment = new SecondMoment(); + this.isBiasCorrected = isBiasCorrected; + } + + public Variance(boolean isBiasCorrected, SecondMoment m2) { + this.incMoment = false; + this.moment = m2; + this.isBiasCorrected = isBiasCorrected; + } + + public Variance(Variance original) throws NullPointerException { + copy(original, this); + } + + public static void copy(Variance source, Variance dest) throws NullPointerException { + Maths.checkNotNull(source); + Maths.checkNotNull(dest); + dest.setData(source.getDataRef()); + dest.moment = source.moment.copy(); + dest.isBiasCorrected = source.isBiasCorrected; + dest.incMoment = source.incMoment; + } + + @Override + public void increment(double d) { + if (this.incMoment) { + this.moment.increment(d); + } + } + + @Override + public double getResult() { + if (this.moment.n == 0L) { + return Double.NaN; + } else if (this.moment.n == 1L) { + return 0.0; + } else { + return this.isBiasCorrected ? this.moment.m2 / ((double)this.moment.n - 1.0) : this.moment.m2 / (double)this.moment.n; + } + } + + @Override + public long getN() { + return this.moment.getN(); + } + + @Override + public void clear() { + if (this.incMoment) { + this.moment.clear(); + } + } + + @Override + public double evaluate(double[] values) throws IllegalArgumentException { + if (values == null) { + throw new NullPointerException(""); + } else { + return this.evaluate(values, 0, values.length); + } + } + + @Override + public double evaluate(double[] values, int begin, int length) throws IllegalArgumentException { + double var = Double.NaN; + if (this.test(values, begin, length)) { + this.clear(); + if (length == 1) { + var = 0.0; + } else if (length > 1) { + Mean mean = new Mean(); + double m = mean.evaluate(values, begin, length); + var = this.evaluate(values, m, begin, length); + } + } + + return var; + } + + @Override + public double evaluate(double[] values, double[] weights, int begin, int length) throws IllegalArgumentException { + double var = Double.NaN; + if (this.test(values, weights, begin, length)) { + this.clear(); + if (length == 1) { + var = 0.0; + } else if (length > 1) { + Mean mean = new Mean(); + double m = mean.evaluate(values, weights, begin, length); + var = this.evaluate(values, weights, m, begin, length); + } + } + + return var; + } + + @Override + public double evaluate(double[] values, double[] weights) throws IllegalArgumentException { + return this.evaluate(values, weights, 0, values.length); + } + + public double evaluate(double[] values, double mean, int begin, int length) throws IllegalArgumentException { + double var = Double.NaN; + if (this.test(values, begin, length)) { + if (length == 1) { + var = 0.0; + } else if (length > 1) { + double accum = 0.0; + double accum2 = 0.0; + + for (int i = begin; i < begin + length; i++) { + double dev = values[i] - mean; + accum += dev * dev; + accum2 += dev; + } + + double len = (double)length; + if (this.isBiasCorrected) { + var = (accum - accum2 * accum2 / len) / (len - 1.0); + } else { + var = (accum - accum2 * accum2 / len) / len; + } + } + } + + return var; + } + + public double evaluate(double[] values, double mean) throws IllegalArgumentException { + return this.evaluate(values, mean, 0, values.length); + } + + public double evaluate(double[] values, double[] weights, double mean, int begin, int length) throws IllegalArgumentException { + double var = Double.NaN; + if (this.test(values, weights, begin, length)) { + if (length == 1) { + var = 0.0; + } else if (length > 1) { + double accum = 0.0; + double accum2 = 0.0; + + for (int i = begin; i < begin + length; i++) { + double dev = values[i] - mean; + accum += weights[i] * dev * dev; + accum2 += weights[i] * dev; + } + + double sumWts = IntStream.range(begin, begin + length).mapToDouble(i -> weights[i]).sum(); + if (this.isBiasCorrected) { + var = (accum - accum2 * accum2 / sumWts) / (sumWts - 1.0); + } else { + var = (accum - accum2 * accum2 / sumWts) / sumWts; + } + } + } + + return var; + } + + public double evaluate(double[] values, double[] weights, double mean) throws IllegalArgumentException { + return this.evaluate(values, weights, mean, 0, values.length); + } + + public boolean isBiasCorrected() { + return this.isBiasCorrected; + } + + public void setBiasCorrected(boolean biasCorrected) { + this.isBiasCorrected = biasCorrected; + } + + public Variance copy() { + Variance result = new Variance(); + copy(this, result); + return result; + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/stat/Statistics.java b/src/main/java/rip/reflex/util/math/descriptive/stat/Statistics.java new file mode 100644 index 0000000..3cde941 --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/stat/Statistics.java @@ -0,0 +1,75 @@ +package rip.reflex.util.math.descriptive.stat; + +import rip.reflex.util.math.Maths; + +public class Statistics { + private final double mean; + private final double median; + private final double variance; + private final double skewness; + private final double kurtosis; + private final double ldev; + private final double hdev; + private final double adev; + private final double lowest; + private final double highest; + private final double balance; + + public Statistics(double[] data) throws ArithmeticException { + this.mean = Maths.mean(data); + this.median = Maths.median(data); + this.variance = Maths.variance(data); + this.skewness = Maths.skewness(data); + this.kurtosis = Maths.kurtosis(data); + this.ldev = Maths.ldev(data); + this.hdev = Maths.hdev(data); + this.adev = Maths.adev(data); + this.lowest = Maths.min(data); + this.highest = Maths.max(data); + this.balance = this.adev / this.ldev; + } + + public double getMean() { + return this.mean; + } + + public double getMedian() { + return this.median; + } + + public double getVariance() { + return this.variance; + } + + public double getSkewness() { + return this.skewness; + } + + public double getKurtosis() { + return this.kurtosis; + } + + public double getLdev() { + return this.ldev; + } + + public double getHdev() { + return this.hdev; + } + + public double getAdev() { + return this.adev; + } + + public double getLowest() { + return this.lowest; + } + + public double getHighest() { + return this.highest; + } + + public double getBalance() { + return this.balance; + } +} diff --git a/src/main/java/rip/reflex/util/math/descriptive/summary/Sum.java b/src/main/java/rip/reflex/util/math/descriptive/summary/Sum.java new file mode 100644 index 0000000..6d4e10e --- /dev/null +++ b/src/main/java/rip/reflex/util/math/descriptive/summary/Sum.java @@ -0,0 +1,81 @@ +package rip.reflex.util.math.descriptive.summary; + +import java.io.Serializable; +import java.util.stream.IntStream; +import rip.reflex.util.math.Maths; +import rip.reflex.util.math.descriptive.AbstractStorelessUnivariateStatistic; + +public class Sum extends AbstractStorelessUnivariateStatistic implements Serializable { + private long n; + private double value; + + public Sum() { + this.n = 0L; + this.value = 0.0; + } + + public Sum(Sum original) throws NullPointerException { + copy(original, this); + } + + public static void copy(Sum source, Sum dest) throws NullPointerException { + Maths.checkNotNull(source); + Maths.checkNotNull(dest); + dest.setData(source.getDataRef()); + dest.n = source.n; + dest.value = source.value; + } + + @Override + public void increment(double d) { + this.value += d; + this.n++; + } + + @Override + public double getResult() { + return this.value; + } + + @Override + public long getN() { + return this.n; + } + + @Override + public void clear() { + this.value = 0.0; + this.n = 0L; + } + + @Override + public double evaluate(double[] values, int begin, int length) throws IllegalArgumentException { + double sum = Double.NaN; + if (this.test(values, begin, length, true)) { + sum = 0.0; + sum += IntStream.range(begin, begin + length).mapToDouble(i -> values[i]).sum(); + } + + return sum; + } + + public double evaluate(double[] values, double[] weights, int begin, int length) throws IllegalArgumentException { + double sum = Double.NaN; + if (this.test(values, weights, begin, length, true)) { + sum = 0.0; + sum += IntStream.range(begin, begin + length).mapToDouble(i -> values[i] * weights[i]).sum(); + } + + return sum; + } + + public double evaluate(double[] values, double[] weights) throws IllegalArgumentException { + return this.evaluate(values, weights, 0, values.length); + } + + public Sum copy() { + Sum result = new Sum(); + copy(this, result); + return result; + } +} diff --git a/src/main/java/rip/reflex/util/misc/AdvCfgLoader.java b/src/main/java/rip/reflex/util/misc/AdvCfgLoader.java new file mode 100644 index 0000000..e22ef93 --- /dev/null +++ b/src/main/java/rip/reflex/util/misc/AdvCfgLoader.java @@ -0,0 +1,54 @@ +package rip.reflex.util.misc; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import org.apache.commons.io.FileUtils; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import rip.reflex.Reflex; + +public class AdvCfgLoader { + public static final String DEFAULT_NAME = "DefaultConfiguration"; + public static final String DEFAULT_PROVIDER = "Reflex Development Team"; + public static final int DEFAULT_CONFIG_HASH = -1659450857; + private static int lastLoadedHash = 0; + + public static boolean loadAdvancedConfiguration(Reflex reflex, FileConfiguration advcfg) { + File cfgFile = checkInstallation(reflex); + if (cfgFile == null) { + reflex.warn("Failed to load advanced configuration file [0]. Defaults one love! (please report this)"); + return false; + } else { + try { + advcfg.load(cfgFile); + lastLoadedHash = advcfg.saveToString().hashCode(); + return true; + } catch (InvalidConfigurationException | IOException ex) { + reflex.warn("Failed to load advanced configuration file [1]. Defaults one love! (please report this)"); + reflex.warn("Cause:"); + ex.printStackTrace(); + return false; + } + } + } + + private static File checkInstallation(Reflex reflex) { + File cfgFile = reflex.getReflexFile("advcfg.yml"); + if (!cfgFile.exists()) { + try (InputStream is = reflex.getResource("advcfg.yml")) { + FileUtils.copyInputStreamToFile(is, cfgFile); + } catch (IOException e) { + reflex.warn("Failed to install advcfg.yml"); + e.printStackTrace(); + return null; + } + } + + return cfgFile; + } + + public static int getLastLoadedHash() { + return lastLoadedHash; + } +} diff --git a/src/main/java/rip/reflex/util/misc/Files.java b/src/main/java/rip/reflex/util/misc/Files.java new file mode 100644 index 0000000..e97d786 --- /dev/null +++ b/src/main/java/rip/reflex/util/misc/Files.java @@ -0,0 +1,113 @@ +package rip.reflex.util.misc; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.InputStream; +import java.io.OutputStream; +import rip.reflex.Reflex; + +public class Files { + public static void write(String path, String data) { + if (Reflex.getReflex().getExecutor() == null) { + new Thread(() -> write0(path, data), "Reflex File Write Thread").start(); + } else { + Reflex.getReflex().getExecutor().execute(() -> write0(path, data)); + } + } + + private static void write0(String path, String data) { + try (FileWriter fw = new FileWriter(new File(path), true)) { + fw.write(data + "\n"); + fw.flush(); + fw.close(); + } catch (Exception ex) { + throw new RuntimeException("Failed to write to file: " + path, ex); + } + } + + public static void writeFromStream(InputStream in, File file) { + try { + OutputStream out = new FileOutputStream(file); + byte[] buf = new byte[1024]; + + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + + out.close(); + in.close(); + } catch (Exception e) { + throw new RuntimeException("Failed to write to file " + file.getAbsolutePath() + " from InputStream", e); + } + } + + public static String read(String path) { + if (path.startsWith("null")) { + return ""; + } else { + File file = new File(path); + + try (FileReader fr = new FileReader(file)) { + char[] buf = new char[(int)file.length()]; + fr.read(buf); + fr.close(); + return new String(buf); + } catch (Exception ex) { + throw new RuntimeException("Failed to read from file: " + path, ex); + } + } + } + + public static void closeWriterSneaky(FileWriter fw) { + try { + fw.close(); + } catch (Exception err) { + throw new RuntimeException("Failed to close a file writer", err); + } + } + + public static void closeReaderSneaky(FileReader fr) { + try { + fr.close(); + } catch (Exception e) { + throw new RuntimeException("Failed to close a file reader", e); + } + } + + public static void flushSneaky(FileWriter fw) { + try { + fw.flush(); + } catch (Exception ex) { + throw new RuntimeException("Failed to flush a file writer", ex); + } + } + + public static void ensureExists(File f) { + if (f.getName().contains(".")) { + f.getParentFile().mkdirs(); + } else { + f.mkdirs(); + } + } + + public static File getFile(String path) { + File f = new File(path); + ensureExists(f); + return f; + } + + public static File getFile(File parent, String child) { + File f = new File(parent, child); + ensureExists(f); + return f; + } + + public static File getFile(String parent, String child) { + File f = new File(parent, child); + ensureExists(f); + return f; + } +} diff --git a/src/main/java/rip/reflex/util/misc/Items.java b/src/main/java/rip/reflex/util/misc/Items.java new file mode 100644 index 0000000..63fc53e --- /dev/null +++ b/src/main/java/rip/reflex/util/misc/Items.java @@ -0,0 +1,124 @@ +package rip.reflex.util.misc; + +import java.util.Arrays; +import java.util.Random; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import rip.reflex.util.protocol.compatibility.Compatibility; + +public class Items { + private static final Random random = new Random(); + + public static ItemStack getHelmet(Player p) { + return p != null && p.getEquipment() != null ? p.getEquipment().getHelmet() : null; + } + + public static ItemStack getChestplate(Player p) { + return p != null && p.getEquipment() != null ? p.getEquipment().getChestplate() : null; + } + + public static ItemStack getLeggings(Player p) { + return p != null && p.getEquipment() != null ? p.getEquipment().getLeggings() : null; + } + + public static ItemStack getBoots(Player p) { + return p != null && p.getEquipment() != null ? p.getEquipment().getBoots() : null; + } + + public static ItemStack randomWeapon() { + switch (random.nextInt(11)) { + case 0: + return new ItemStack(Compatibility.getWoodenItem("WOOD_SWORD")); + case 1: + return new ItemStack(Compatibility.getGoldenItem("GOLD_SWORD")); + case 2: + return new ItemStack(Material.STONE_SWORD); + case 3: + return new ItemStack(Material.IRON_SWORD); + case 4: + return new ItemStack(Material.DIAMOND_SWORD); + case 5: + return new ItemStack(Compatibility.getWoodenItem("WOOD_AXE")); + case 6: + return new ItemStack(Compatibility.getGoldenItem("GOLD_AXE")); + case 7: + return new ItemStack(Material.STONE_AXE); + case 8: + return new ItemStack(Material.IRON_AXE); + case 9: + return new ItemStack(Material.DIAMOND_AXE); + default: + return null; + } + } + + public static ItemStack randomHelmet() { + switch (random.nextInt(5)) { + case 0: + return new ItemStack(Material.LEATHER_HELMET); + case 1: + return new ItemStack(Compatibility.getGoldenItem("GOLD_HELMET")); + case 2: + return new ItemStack(Material.IRON_HELMET); + case 3: + return new ItemStack(Material.DIAMOND_HELMET); + default: + return null; + } + } + + public static ItemStack randomChestplate() { + switch (random.nextInt(5)) { + case 0: + return new ItemStack(Material.LEATHER_CHESTPLATE); + case 1: + return new ItemStack(Compatibility.getGoldenItem("GOLD_CHESTPLATE")); + case 2: + return new ItemStack(Material.IRON_CHESTPLATE); + case 3: + return new ItemStack(Material.DIAMOND_CHESTPLATE); + default: + return null; + } + } + + public static ItemStack randomLeggings() { + switch (random.nextInt(5)) { + case 0: + return new ItemStack(Material.LEATHER_LEGGINGS); + case 1: + return new ItemStack(Compatibility.getGoldenItem("GOLD_LEGGINGS")); + case 2: + return new ItemStack(Material.IRON_LEGGINGS); + case 3: + return new ItemStack(Material.DIAMOND_LEGGINGS); + default: + return null; + } + } + + public static ItemStack randomBoots() { + switch (random.nextInt(5)) { + case 0: + return new ItemStack(Material.LEATHER_BOOTS); + case 1: + return new ItemStack(Compatibility.getGoldenItem("GOLD_BOOTS")); + case 2: + return new ItemStack(Material.IRON_BOOTS); + case 3: + return new ItemStack(Material.DIAMOND_BOOTS); + default: + return null; + } + } + + public static boolean isItemUsable(ItemStack item) { + return item.getType().isEdible() || item.getType().toString().toLowerCase().contains("sword"); + } + + public static boolean allOfType(Material type, Block... blocks) { + return blocks != null && Arrays.stream(blocks).allMatch(block -> block.getType() == type); + } +} diff --git a/src/main/java/rip/reflex/util/misc/Misc.java b/src/main/java/rip/reflex/util/misc/Misc.java new file mode 100644 index 0000000..e3cfe58 --- /dev/null +++ b/src/main/java/rip/reflex/util/misc/Misc.java @@ -0,0 +1,212 @@ +package rip.reflex.util.misc; + +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.NotSerializableException; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.time.Period; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.zip.InflaterInputStream; +import rip.reflex.Reflex; + +public class Misc { + public static int getSize(Object object) { + try { + if (object == null) { + return 1; + } else { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(object); + oos.close(); + byte[] byteArray = baos.toByteArray(); + return byteArray == null ? 1 : byteArray.length; + } + } catch (NotSerializableException ignored) { + return 1; + } catch (Exception ex) { + throw new RuntimeException("Error getting object size (" + object.toString() + ")", ex); + } + } + + public static byte[] getBytes(Object obj) { + if (obj == null) { + return new byte[0]; + } else { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(obj); + oos.close(); + byte[] bytes = baos.toByteArray(); + baos.close(); + return bytes; + } catch (Exception e) { + throw new RuntimeException("Failed to get bytes of " + obj.toString(), e); + } + } + } + + public static String postPaste(String content, String url, String userAgent) throws IOException { + HttpURLConnection con = (HttpURLConnection)Reflex.getReflex().getURL(url + "/documents").openConnection(); + con.setRequestMethod("POST"); + con.setRequestProperty("User-Agent", userAgent); + con.setDoOutput(true); + OutputStream out = con.getOutputStream(); + out.write(content.getBytes("UTF-8")); + String result = readFully(con.getInputStream()); + return url + "/" + result.substring(8, result.length() - 2); + } + + public static void sortDescending(List list) { + Collections.sort(list); + Collections.reverse(list); + } + + public static void sortDescending(List list, Comparator c) { + Collections.sort(list, c); + Collections.reverse(list); + } + + public static void lif(boolean b, Runnable r) { + if (b) { + r.run(); + } + } + + public static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static T castSafely(Object o) { + return (T)(o == null ? null : o); + } + + public static Map copyMap(Map map, boolean concurrent) { + Map result = (Map)(concurrent ? new ConcurrentHashMap<>() : new HashMap<>()); + + for (K key : map.keySet()) { + result.put(key, map.get(key)); + } + + return result; + } + + public static T sneaky(Throwable t) { + throw new RuntimeException(t); + } + + public static Object reverseGet(Class a, Class b, B obj, HashMap map) { + return map.entrySet().stream().filter(entry -> entry.getValue().equals(obj)).findFirst().map(Entry::getKey).orElse(null); + } + + public static void close(Closeable... closeables) { + for (Closeable closeable : closeables) { + try { + closeable.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + + public static boolean isShort(String s) { + return isNumeric(s) && Long.valueOf(s) <= 32767L && Long.valueOf(s) >= -32768L; + } + + public static void forEachMatch(List list, Predicate pred, Consumer consumer) { + for (T t : list) { + if (pred.test(t)) { + consumer.accept(t); + } + } + } + + public static boolean isNumeric(String s) { + for (char c : s.toCharArray()) { + if (!Character.isDigit(c)) { + return false; + } + } + + return true; + } + + public static byte[] getBytesAndClose(ByteArrayOutputStream bout, OutputStream... s) throws Exception { + byte[] data = bout.toByteArray(); + bout.close(); + + for (OutputStream outputStream : s) { + outputStream.close(); + } + + return data; + } + + public static String readFully(InputStream in) throws IOException { + StringBuilder builder = new StringBuilder(); + byte[] buf = new byte[1024]; + + int i; + while ((i = in.read(buf)) != -1) { + builder.append(new String(buf, 0, i, "UTF-8")); + } + + return builder.toString(); + } + + public static String readCompressed(InputStream in) throws IOException { + InflaterInputStream infin = new InflaterInputStream(in); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + + int i; + while ((i = infin.read(buf)) != -1) { + bout.write(buf, 0, i); + } + + byte[] data = bout.toByteArray(); + bout.close(); + infin.close(); + return new String(data, "UTF-8"); + } + + public static long parseTime(String s) { + return Period.parse(s).get(ChronoUnit.DAYS); + } + + public static boolean isNumber(String s) { + for (char c : s.toCharArray()) { + if (!Character.isDigit(c)) { + return false; + } + } + + return true; + } + + public static boolean isBoolean(String s) { + return s.equalsIgnoreCase("true") || s.equalsIgnoreCase("false"); + } + + public static boolean isUUID(String s) { + return s.length() == 36 && s.matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); + } +} diff --git a/src/main/java/rip/reflex/util/misc/PlayerInvSlots.java b/src/main/java/rip/reflex/util/misc/PlayerInvSlots.java new file mode 100644 index 0000000..304ec96 --- /dev/null +++ b/src/main/java/rip/reflex/util/misc/PlayerInvSlots.java @@ -0,0 +1,16 @@ +package rip.reflex.util.misc; + +public final class PlayerInvSlots { + private PlayerInvSlots() { + } + + public static final class Raw { + public static final int HELMET = 5; + public static final int CHESTPLATE = 6; + public static final int LEGGINGS = 7; + public static final int BOOTS = 8; + + private Raw() { + } + } +} diff --git a/src/main/java/rip/reflex/util/misc/Rand.java b/src/main/java/rip/reflex/util/misc/Rand.java new file mode 100644 index 0000000..dfa44dd --- /dev/null +++ b/src/main/java/rip/reflex/util/misc/Rand.java @@ -0,0 +1,20 @@ +package rip.reflex.util.misc; + +import java.util.SplittableRandom; + +public class Rand { + private static final SplittableRandom random = new SplittableRandom(); + + public static float invalidFloat() { + switch (random.nextInt(3)) { + case 0: + return Float.NaN; + case 1: + return Float.POSITIVE_INFINITY; + case 2: + return Float.NEGATIVE_INFINITY; + default: + throw new UnknownError("nextInt(3) generated number which is out of range[0;2]?!"); + } + } +} diff --git a/src/main/java/rip/reflex/util/misc/Strings.java b/src/main/java/rip/reflex/util/misc/Strings.java new file mode 100644 index 0000000..ef2c607 --- /dev/null +++ b/src/main/java/rip/reflex/util/misc/Strings.java @@ -0,0 +1,405 @@ +package rip.reflex.util.misc; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.function.Supplier; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.util.placeholders.PlaceholderAPIHook; + +public class Strings { + private static final Random random = new Random(); + private static final String[] charlist = new String[]{ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "+", + "-", + "=", + ":", + "%", + "_", + "/", + "\\", + "|", + "*", + ".", + "@", + "#", + "$" + }; + private static final List xorKeys = new ArrayList<>(); + + public static String color(String s) { + return ChatColor.translateAlternateColorCodes('&', s); + } + + public static String random(String... source) { + return source[random.nextInt(source.length)]; + } + + public static String randomComp(int length, String source) { + String[] s = new String[source.length()]; + + for (int i = 0; i < source.length(); i++) { + s[i] = String.valueOf(source.charAt(i)); + } + + return random(length, s); + } + + public static String random(int length, String... source) { + StringBuilder s = new StringBuilder(); + + while (s.length() < length) { + s.append(random(source)); + } + + return s.toString(); + } + + public static String random(int length) { + StringBuilder s = new StringBuilder(); + + while (s.length() < length) { + String c = charlist[random.nextInt(charlist.length)]; + if (random.nextBoolean()) { + c = c.toUpperCase(); + } + + s.append(c); + } + + return s.toString(); + } + + public static String randomAbc(int length) { + StringBuilder s = new StringBuilder(); + + while (s.length() < length) { + String c = charlist[random.nextInt(charlist.length - 24)]; + if (random.nextBoolean()) { + c = c.toUpperCase(); + } + + s.append(c); + } + + return s.toString(); + } + + public static boolean containsAny(String s, String... containers) { + return Arrays.stream(containers).anyMatch(container -> container.contains(s)); + } + + public static boolean equalsAny(String s, String... s0) { + return Arrays.stream(s0).anyMatch(s::equals); + } + + public static boolean isLowerCase(String s) { + return s.equals(s.toLowerCase()); + } + + public static boolean isUpperCase(String s) { + return s.equals(s.toUpperCase()); + } + + public static boolean containsIgnoreCase(String s, String container) { + return s.toLowerCase().contains(container.toLowerCase()); + } + + public static String rformat(CommandSender cs, String s) { + return wrap(Reflex.getReflex().getTheme(cs).getPrefix() + s).replace("%break%", "\n").replace("\\n", "\n").colourizeAndGet(); + } + + public static String rformatNoPrefix(String s) { + return wrap(s).replace("%break%", "\n").replace("\\n", "\n").colourizeAndGet(); + } + + public static String encode(String s) { + char[] chars = s.toCharArray(); + + for (int i = 0; i < chars.length; i++) { + if (!String.valueOf(chars[i]).equals(" ") && !String.valueOf(chars[i]).equals("'")) { + chars[i] = charlist[Math.abs(charlist.length - getCharIndex(chars[i])) - 1].toLowerCase().charAt(0); + } + } + + return new String(chars); + } + + public static int getCharIndex(char c) { + String s = String.valueOf(c).toLowerCase(); + + for (int index = 0; index < charlist.length; index++) { + if (s.equals(charlist[index])) { + return index; + } + } + + return -1; + } + + public static String join(int start, String[] arr, String separator) { + if (arr.length == 0) { + return ""; + } else if (arr.length == 1) { + return arr[0]; + } else { + StringBuilder builder = new StringBuilder(); + + for (int i = start; i < arr.length; i++) { + builder.append(arr[i]).append(separator); + } + + return builder.deleteCharAt(builder.length() - 1).toString(); + } + } + + public static String firstUppercase(String s) { + return Character.toUpperCase(s.charAt(0)) + s.substring(1); + } + + public static boolean startsWithAbc(String s) { + return isStringValid(s) && Character.isAlphabetic(s.toLowerCase().charAt(0)); + } + + public static boolean isStringValid(String s) { + return s != null || !s.isEmpty() || !s.contains("\u0000"); + } + + public static String removeColorCodes(String s) { + char[] chars = s.toCharArray(); + + for (int i = 0; i < chars.length; i++) { + if ("&§".contains(String.valueOf(chars[i]))) { + if (i < chars.length - 1) { + chars[i + 1] = 0; + } + + chars[i] = 0; + } + } + + return replace(new String(chars), "\u0000", ""); + } + + public static String tab(String s, int tabLoc) { + if (s.length() >= tabLoc) { + throw new IllegalArgumentException("String must be shorter than tab length"); + } else { + return s + String.join("", Collections.nCopies(tabLoc - s.length(), " ")); + } + } + + public static String randomUsername() { + String prefix = random.nextInt(5) == 0 ? random("ITz", "Neron_", "Vildman_", "MLG", "Its", "xX", "Vag", "Mini", "kon", "md_5", "md_") : ""; + String suffix = prefix.isEmpty() + ? random("LP", "YT", "Code", "Plays", "HD", "007", "69", "123", "Trump", "Xx", "dedes", "Digger", "solas", "md_5", "5", "_5") + : ""; + String body = randomAbc(16 - (prefix.length() + suffix.length()) - random.nextInt((int)((double)(16 - (prefix.length() + suffix.length())) * 0.5))); + return prefix + body + suffix; + } + + public static int xorHash(String s) { + return xor(s == null ? "null" : s, 38634).hashCode(); + } + + public static String xor(String s, Object key) { + try { + byte[] k = key instanceof byte[] ? (byte[])key : (byte[])getXorKey(key); + byte[] bytes = s.getBytes("UTF-8"); + + for (int i = 0; i < bytes.length; i++) { + for (byte b : k) { + bytes[i] ^= b; + } + + bytes[i] = (byte)(24 - (bytes[i] | 1)); + } + + return new String((byte[])bytes.clone(), "UTF-8"); + } catch (Exception ignored) { + return s; + } + } + + public static String replace(String str, String target, String replacement) { + int targetLength = target.length(); + if (targetLength == 0) { + return str; + } else { + int idx2 = str.indexOf(target); + int cursor = 0; + if (idx2 < 0) { + return str; + } else { + StringBuilder buffer; + for (buffer = new StringBuilder(targetLength > replacement.length() ? str.length() : str.length() * 2); + idx2 > -1; + idx2 = str.indexOf(target, cursor) + ) { + buffer.append(str, cursor, idx2); + buffer.append(replacement); + cursor = idx2 + targetLength; + } + + buffer.append(str, cursor, str.length()); + return buffer.toString(); + } + } + } + + public static String removeIntegers(String s) { + return s.replaceAll("[0-9]", ""); + } + + public static String cut(String s, int start, int end) { + StringBuilder sb = new StringBuilder(); + + for (int i = start; i < end; i++) { + sb.append(s.charAt(i)); + } + + return sb.toString(); + } + + public static String asciiOnly(String s) { + char[] chars = (char[])s.replaceAll("[^\\x00-\\x7F]", "").toCharArray().clone(); + + for (int i = 0; i < chars.length; i++) { + if (getCharIndex(chars[i]) == -1) { + chars[i] = 0; + } + } + + return new String(chars).replace("\u0000", ""); + } + + public static Strings.WrappedString wrap(String s) { + return new Strings.WrappedString(s); + } + + public static Strings.WrappedString wrap(StringBuilder s) { + return new Strings.WrappedString(s.toString()); + } + + private static Object getXorKey(Object o) { + if (o == null) { + return xorKeys.get(4); + } else { + char c; + if (o instanceof Character) { + c = (Character)o; + } else if (o instanceof Integer) { + c = (char)((Integer)o).intValue(); + } else { + c = 22290; + } + + if (c == 24859) { + return xorKeys.get(3); + } else { + switch (c) { + case '歳': + return xorKeys.get(2); + case '雪': + return xorKeys.get(1); + default: + return xorKeys.get(0); + } + } + } + } + + static { + xorKeys.add(new byte[]{60, -14, 5, 9, -52, 2, 31, -6}); + xorKeys.add(new byte[]{3, 12, -39, -4, -10, 74, -9, 2}); + xorKeys.add(new byte[]{-11, 50, 17, -1, 9, 61, 6, -3}); + xorKeys.add(new byte[]{33, -76, 1, 15, 102, 4, -41, 19}); + } + + public static class WrappedString { + private String value; + + public Strings.WrappedString replace(String target, Object replace) { + this.value = Strings.replace(this.value, target, replace instanceof String ? (String)replace : String.valueOf(replace)); + return this; + } + + public Strings.WrappedString replace(String target, Supplier supp) { + return !this.value.contains(target) ? this : this.replace(target, supp.get()); + } + + public Strings.WrappedString colourize() { + this.value = Strings.color(this.value); + return this; + } + + public Strings.WrappedString noColors() { + this.value = Strings.removeColorCodes(this.value); + return this; + } + + public String colourizeAndGet() { + this.colourize(); + return this.get(); + } + + public Strings.WrappedString placeholderApi(Player player) { + this.value = PlaceholderAPIHook.replace(this.value, player); + return this; + } + + public String get() { + return this.value; + } + + @Override + public String toString() { + return this.value; + } + + public WrappedString(String value) { + this.value = value; + } + } +} diff --git a/src/main/java/rip/reflex/util/misc/Unzipper.java b/src/main/java/rip/reflex/util/misc/Unzipper.java new file mode 100644 index 0000000..9800ae9 --- /dev/null +++ b/src/main/java/rip/reflex/util/misc/Unzipper.java @@ -0,0 +1,52 @@ +package rip.reflex.util.misc; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.IOException; +import java.util.function.BiConsumer; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class Unzipper implements Closeable { + private final byte[] data; + private final BiConsumer consumer; + + public void exec() { + try { + this.exec0(); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } + + private void exec0() throws IOException { + ByteArrayInputStream byteIn = new ByteArrayInputStream(this.data); + ZipInputStream zipIn = new ZipInputStream(byteIn); + byte[] buffer = new byte[1024]; + + ZipEntry entry; + while ((entry = zipIn.getNextEntry()) != null) { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + + int i; + while ((i = zipIn.read(buffer)) > 0) { + bout.write(buffer, 0, i); + } + + this.consumer.accept(entry, bout.toByteArray()); + bout.close(); + } + + this.close(); + } + + @Override + public void close() throws IOException { + } + + public Unzipper(byte[] data, BiConsumer consumer) { + this.data = data; + this.consumer = consumer; + } +} diff --git a/src/main/java/rip/reflex/util/misc/Validate.java b/src/main/java/rip/reflex/util/misc/Validate.java new file mode 100644 index 0000000..c2deacc --- /dev/null +++ b/src/main/java/rip/reflex/util/misc/Validate.java @@ -0,0 +1,61 @@ +package rip.reflex.util.misc; + +import org.bukkit.entity.Player; + +public class Validate { + public static T notNull(T o, String message) { + if (o == null) { + throw new NullPointerException(message); + } else { + return o; + } + } + + public static T instanceOf(T o, Class c, String message) { + if (!c.isInstance(o)) { + throw new IllegalArgumentException(message); + } else { + return o; + } + } + + public static boolean argumentCheck(boolean b, String message) { + if (b) { + return true; + } else { + throw new IllegalArgumentException(message); + } + } + + public static Player playerOnline(Player p, String message) { + if (!p.isOnline()) { + throw new IllegalStateException(message); + } else { + return p; + } + } + + public static String strNotEmpty(String s, String message) { + if (s.replace(" ", "").length() < 1) { + throw new IllegalArgumentException(message); + } else { + return s; + } + } + + public static int notZero(int n, String message) { + if (n == 0) { + throw new ArithmeticException(message); + } else { + return n; + } + } + + public static long notZero(long n, String message) { + if (n == 0L) { + throw new ArithmeticException(message); + } else { + return n; + } + } +} diff --git a/src/main/java/rip/reflex/util/mod/BetterPVPFeatures.java b/src/main/java/rip/reflex/util/mod/BetterPVPFeatures.java new file mode 100644 index 0000000..57e63b4 --- /dev/null +++ b/src/main/java/rip/reflex/util/mod/BetterPVPFeatures.java @@ -0,0 +1,14 @@ +package rip.reflex.util.mod; + +public class BetterPVPFeatures { + public static final int MINIMAP = 1; + public static final int ARMOR_STATUS = 2; + public static final int POTION_STATUS = 4; + public static final int ARCHERY_STATUS = 8; + public static final int BETTER_SPRINT = 64; + public static final int TOGGLE_SNEAK = 128; + public static final int QUICK_ITEM_USE = 256; + public static final int TNT_NOTIFICATIONS = 524288; + public static final int DEATH_POINTS = 2097152; + public static final int ENTITY_INFO = 8388608; +} diff --git a/src/main/java/rip/reflex/util/mod/DependencyChecker.java b/src/main/java/rip/reflex/util/mod/DependencyChecker.java new file mode 100644 index 0000000..3d08a95 --- /dev/null +++ b/src/main/java/rip/reflex/util/mod/DependencyChecker.java @@ -0,0 +1,58 @@ +package rip.reflex.util.mod; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.bukkit.Bukkit; +import rip.reflex.Reflex; + +public class DependencyChecker { + private static final Map entries = new HashMap<>(); + + public static void put(String s, DependencyChecker.Checker c) { + entries.put(s, c); + } + + public static void checkDependencies() { + List missing = new ArrayList<>(); + entries.forEach((name, checker) -> { + try { + checker.check(); + } catch (Exception ignored) { + missing.add(name); + } + }); + if (!missing.isEmpty()) { + System.err.println(); + System.err.println("***************** ERROR *****************"); + System.err.println(); + System.err.println(" The following dependencies are missing:"); + System.err.println(" >> " + String.join(", ", missing)); + System.err.println(); + System.err.println("*****************************************"); + System.err.println(); + Bukkit.getPluginManager().disablePlugin(Reflex.getReflex()); + throw new DependencyChecker.EmptyException(); + } + } + + public interface Checker { + boolean check() throws Exception; + } + + private static class EmptyException extends RuntimeException { + private EmptyException() { + } + + @Override + public StackTraceElement[] getStackTrace() { + return new StackTraceElement[0]; + } + + @Override + public synchronized Throwable fillInStackTrace() { + return null; + } + } +} diff --git a/src/main/java/rip/reflex/util/mod/FiveZigFeatures.java b/src/main/java/rip/reflex/util/mod/FiveZigFeatures.java new file mode 100644 index 0000000..d46d257 --- /dev/null +++ b/src/main/java/rip/reflex/util/mod/FiveZigFeatures.java @@ -0,0 +1,10 @@ +package rip.reflex.util.mod; + +public class FiveZigFeatures { + public static final byte POTION_EFFECT_HUD = 1; + public static final byte POTION_INDICATOR_VIGNETTE = 2; + public static final byte ARMOR_HUD = 4; + public static final byte RENDER_SATURATION = 8; + public static final byte RENDER_HEALTH = 16; + public static final byte AUTO_RECONNECT = 32; +} diff --git a/src/main/java/rip/reflex/util/mod/LabyModFeature.java b/src/main/java/rip/reflex/util/mod/LabyModFeature.java new file mode 100644 index 0000000..97b834e --- /dev/null +++ b/src/main/java/rip/reflex/util/mod/LabyModFeature.java @@ -0,0 +1,15 @@ +package rip.reflex.util.mod; + +public enum LabyModFeature { + FOOD, + GUI, + NICK, + BLOCKBUILD, + CHAT, + EXTRAS, + ANIMATIONS, + POTIONS, + ARMOR, + DAMAGEINDICATOR, + MINIMAP_RADAR; +} diff --git a/src/main/java/rip/reflex/util/mod/WDLPackets.java b/src/main/java/rip/reflex/util/mod/WDLPackets.java new file mode 100644 index 0000000..299f4a0 --- /dev/null +++ b/src/main/java/rip/reflex/util/mod/WDLPackets.java @@ -0,0 +1,64 @@ +package rip.reflex.util.mod; + +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +public class WDLPackets { + public static byte[] createWDLPacket0(boolean canDoNewThings) { + ByteArrayDataOutput output = ByteStreams.newDataOutput(); + output.writeInt(0); + output.writeBoolean(canDoNewThings); + return output.toByteArray(); + } + + public static byte[] createWDLPacket1( + boolean globalIsEnabled, int saveRadius, boolean cacheChunks, boolean saveEntities, boolean saveTileEntities, boolean saveContainers + ) { + ByteArrayDataOutput output = ByteStreams.newDataOutput(); + output.writeInt(1); + output.writeBoolean(globalIsEnabled); + output.writeInt(saveRadius); + output.writeBoolean(cacheChunks && globalIsEnabled); + output.writeBoolean(saveEntities && globalIsEnabled); + output.writeBoolean(saveTileEntities && globalIsEnabled); + output.writeBoolean(saveContainers && saveTileEntities && globalIsEnabled); + return output.toByteArray(); + } + + public static byte[] createWDLPacket2(Map ranges) { + ByteArrayDataOutput output = ByteStreams.newDataOutput(); + output.writeInt(2); + output.writeInt(ranges.size()); + + for (Entry e : ranges.entrySet()) { + output.writeUTF(e.getKey()); + output.writeInt(e.getValue()); + } + + return output.toByteArray(); + } + + public static byte[] createWDLPacket3(String message) { + ByteArrayDataOutput output = ByteStreams.newDataOutput(); + output.writeInt(3); + output.writeBoolean(true); + output.writeUTF(message); + return output.toByteArray(); + } + + public static byte[] createWDLPacket6(String group, List tags) { + ByteArrayDataOutput output = ByteStreams.newDataOutput(); + output.writeInt(6); + output.writeUTF(group); + output.writeInt(tags.size()); + + for (String tag : tags) { + output.writeUTF(tag); + } + + return output.toByteArray(); + } +} diff --git a/src/main/java/rip/reflex/util/mod/badlionclient/BadlionConfig.java b/src/main/java/rip/reflex/util/mod/badlionclient/BadlionConfig.java new file mode 100644 index 0000000..5c56ae5 --- /dev/null +++ b/src/main/java/rip/reflex/util/mod/badlionclient/BadlionConfig.java @@ -0,0 +1,18 @@ +package rip.reflex.util.mod.badlionclient; + +import com.google.gson.JsonObject; +import java.util.HashMap; +import java.util.Map; + +public class BadlionConfig { + private Map modsDisallowed = new HashMap<>(); + + public Map getModsDisallowed() { + return this.modsDisallowed; + } + + private class DisallowedMods { + private boolean disabled; + private JsonObject extra_data; + } +} diff --git a/src/main/java/rip/reflex/util/mod/badlionclient/BadlionConfigMaker.java b/src/main/java/rip/reflex/util/mod/badlionclient/BadlionConfigMaker.java new file mode 100644 index 0000000..1b2f9f6 --- /dev/null +++ b/src/main/java/rip/reflex/util/mod/badlionclient/BadlionConfigMaker.java @@ -0,0 +1,42 @@ +package rip.reflex.util.mod.badlionclient; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import java.io.File; +import java.io.FileReader; +import rip.reflex.Reflex; +import rip.reflex.util.misc.Files; + +public class BadlionConfigMaker { + private static final String CONFIG_FILE_NAME = "blc_config.json"; + private static final Gson gson = new GsonBuilder().enableComplexMapKeySerialization().disableHtmlEscaping().create(); + private static byte[] cache = null; + + public static byte[] make(Reflex reflex) { + return cache == null ? (cache = gson.toJson(make0(reflex).getModsDisallowed()).getBytes()) : cache; + } + + public static void installConfigFile(Reflex r) { + File file = r.getReflexFile("blc_config.json"); + if (!file.exists()) { + Files.writeFromStream(r.getResource("blc_config.json"), file); + } + } + + private static BadlionConfig make0(Reflex r) { + File file = r.getReflexFile("blc_config.json"); + installConfigFile(r); + + try (FileReader reader = new FileReader(file)) { + BadlionConfig config = (BadlionConfig)gson.fromJson(reader, BadlionConfig.class); + reader.close(); + return config; + } catch (Exception ex) { + throw new RuntimeException( + "[Reflex/ClientControl] Failed to load BLC config. Make sure your JSON is valid. You can check it using https://jsonformatter.curiousconcept.com/" + + file.getAbsolutePath(), + ex + ); + } + } +} diff --git a/src/main/java/rip/reflex/util/net/Urls.java b/src/main/java/rip/reflex/util/net/Urls.java new file mode 100644 index 0000000..8ff68f2 --- /dev/null +++ b/src/main/java/rip/reflex/util/net/Urls.java @@ -0,0 +1,9 @@ +package rip.reflex.util.net; + +public class Urls { + public static class Sync { + public static final String EUROPE_HTTP = "http://sync.reflex.rip/"; + public static final String EUROPE_SSL = "https://sync.reflex.rip/"; + public static final String ASIA_HTTP = "http://reflex.hyperx.cc/"; + } +} diff --git a/src/main/java/rip/reflex/util/net/http/GetRequest.java b/src/main/java/rip/reflex/util/net/http/GetRequest.java new file mode 100644 index 0000000..3e79b7b --- /dev/null +++ b/src/main/java/rip/reflex/util/net/http/GetRequest.java @@ -0,0 +1,55 @@ +package rip.reflex.util.net.http; + +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import rip.reflex.Reflex; + +public abstract class GetRequest extends HttpRequest { + private final String url; + private final String userAgent; + + @Override + public void execute() { + try { + this.get0(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void get0() throws Exception { + URL url = Reflex.getReflex().getURL(this.url); + HttpURLConnection con = (HttpURLConnection)url.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("User-Agent", this.userAgent); + if (this.isRead()) { + con.setDoInput(true); + RS rs = this.getReadStream(con.getInputStream()); + this.read(rs); + rs.close(); + } + + con.disconnect(); + } + + @Override + public void setWrite(boolean write) { + throw new RuntimeException("Write is not supported in GET requests."); + } + + @Override + protected void write(OutputStream writeStream) throws Exception { + } + + @Override + protected OutputStream getWriteStream(OutputStream os) throws Exception { + return null; + } + + public GetRequest(String url, String userAgent) { + this.url = url; + this.userAgent = userAgent; + } +} diff --git a/src/main/java/rip/reflex/util/net/http/HttpRequest.java b/src/main/java/rip/reflex/util/net/http/HttpRequest.java new file mode 100644 index 0000000..78dbe80 --- /dev/null +++ b/src/main/java/rip/reflex/util/net/http/HttpRequest.java @@ -0,0 +1,35 @@ +package rip.reflex.util.net.http; + +import java.io.InputStream; +import java.io.OutputStream; + +public abstract class HttpRequest { + private boolean read = false; + private boolean write = false; + + protected abstract void execute(); + + protected abstract void read(RS readStream) throws Exception; + + protected abstract void write(WS writeStream) throws Exception; + + protected abstract RS getReadStream(InputStream inputStream); + + protected abstract WS getWriteStream(OutputStream outputStream) throws Exception; + + public boolean isRead() { + return this.read; + } + + public boolean isWrite() { + return this.write; + } + + public void setRead(boolean read) { + this.read = read; + } + + public void setWrite(boolean write) { + this.write = write; + } +} diff --git a/src/main/java/rip/reflex/util/net/http/PostRequest.java b/src/main/java/rip/reflex/util/net/http/PostRequest.java new file mode 100644 index 0000000..fa11957 --- /dev/null +++ b/src/main/java/rip/reflex/util/net/http/PostRequest.java @@ -0,0 +1,67 @@ +package rip.reflex.util.net.http; + +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import rip.reflex.Reflex; +import rip.reflex.util.performance.MethodProfiler; + +public abstract class PostRequest extends HttpRequest { + private final String url; + private final String userAgent; + private boolean autoSSL = false; + + @Override + protected void execute() { + try { + this.post0(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public void post() { + this.execute(); + } + + private void post0() throws Exception { + MethodProfiler mp = new MethodProfiler("TB-498127391"); + URL url = this.autoSSL ? Reflex.getReflex().getURL(this.url) : new URL(this.url); + HttpURLConnection con = (HttpURLConnection)url.openConnection(); + con.setRequestMethod("POST"); + con.setRequestProperty("User-Agent", this.userAgent); + if (this.isWrite()) { + MethodProfiler mpWrite = new MethodProfiler("TB-7490214"); + con.setDoOutput(true); + WS ws = this.getWriteStream(con.getOutputStream()); + this.write(ws); + ws.close(); + mpWrite.addToTimings(); + } + + if (this.isRead()) { + MethodProfiler mpRead = new MethodProfiler("TB-62197391798"); + if (!this.isWrite()) { + con.setDoInput(true); + } + + RS rs = this.getReadStream(con.getInputStream()); + this.read(rs); + rs.close(); + mpRead.addToTimings(); + } + + con.disconnect(); + mp.addToTimings(); + } + + public PostRequest(String url, String userAgent) { + this.url = url; + this.userAgent = userAgent; + } + + public void setAutoSSL(boolean autoSSL) { + this.autoSSL = autoSSL; + } +} diff --git a/src/main/java/rip/reflex/util/net/ssl/HackedTrustManager.java b/src/main/java/rip/reflex/util/net/ssl/HackedTrustManager.java new file mode 100644 index 0000000..ee29d27 --- /dev/null +++ b/src/main/java/rip/reflex/util/net/ssl/HackedTrustManager.java @@ -0,0 +1,90 @@ +package rip.reflex.util.net.ssl; + +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +public class HackedTrustManager implements X509TrustManager { + private static final HackedTrustManager instance = new HackedTrustManager(); + private X509TrustManager orig; + private SSLSocketFactory defFactory; + private boolean enabled = false; + + public static HackedTrustManager get() { + return instance; + } + + @Override + public void checkClientTrusted(X509Certificate[] certs, String s) throws CertificateException { + if (!this.enabled) { + if (this.orig != null) { + this.orig.checkClientTrusted(certs, s); + } + } + } + + @Override + public void checkServerTrusted(X509Certificate[] certs, String s) throws CertificateException { + if (!this.enabled) { + if (this.orig != null) { + this.orig.checkServerTrusted(certs, s); + } + } + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + if (this.enabled) { + return null; + } else { + return this.orig == null ? null : this.orig.getAcceptedIssuers(); + } + } + + public void inject() { + this.orig(); + System.setProperty("https.protocols", "TLSv1.1,TLSv1.2,SSLv3"); + + try { + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, new TrustManager[]{this}, SecureRandom.getInstanceStrong()); + this.defFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } catch (Exception ex) { + ex.printStackTrace(); + } + + this.enabled = true; + } + + public void uninject() { + this.enabled = false; + HttpsURLConnection.setDefaultSSLSocketFactory(this.defFactory); + } + + private void orig() { + try { + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE"); + tmf.init((KeyStore)null); + this.orig = (X509TrustManager)Arrays.stream(tmf.getTrustManagers()).filter(tm -> tm instanceof X509TrustManager).findFirst().orElse(null); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public boolean isEnabled() { + return this.enabled; + } +} diff --git a/src/main/java/rip/reflex/util/performance/LagStatus.java b/src/main/java/rip/reflex/util/performance/LagStatus.java new file mode 100644 index 0000000..d11a5e4 --- /dev/null +++ b/src/main/java/rip/reflex/util/performance/LagStatus.java @@ -0,0 +1,52 @@ +package rip.reflex.util.performance; + +import java.util.Arrays; +import rip.reflex.util.math.Maths; + +public enum LagStatus { + NOT_ESTIMATED("not estimated", -1, 0, 0.0), + HASTY("hasty", 1, 8, 1.25), + OK("ok", 9, 26, 1.0), + MINOR_LAG("minor lag", 27, 39, 0.8), + NOTICEABLE_LAG("noticeable lag", 40, 57, 0.69), + VIVID_LAG("vivid lag", 58, 78, 0.37), + EXTREME_LAG("extreme lag", 79, Integer.MAX_VALUE, 0.2); + + private final String fancyName; + private final int minLagPoints; + private final int maxLagPoints; + private final double violationsWeight; + + private LagStatus(String fancyName, int minLagPoints, int maxLagPoints, double violationsWeight) { + this.fancyName = fancyName; + this.minLagPoints = minLagPoints; + this.maxLagPoints = maxLagPoints; + this.violationsWeight = violationsWeight; + } + + public double getViolationsWeight() { + return this.violationsWeight; + } + + public int correctVl(int vl) { + return vl > 1 ? Maths.floor((double)vl * this.violationsWeight) : vl; + } + + public String fancyName() { + return this.fancyName; + } + + public boolean isLowerThan(LagStatus other) { + return this.ordinal() < other.ordinal(); + } + + public boolean hasMininum(LagStatus other) { + return this.ordinal() >= other.ordinal(); + } + + public static LagStatus get(int lagPoints) { + return Maths.matchIn(lagPoints, 360, 390) + ? OK + : Arrays.stream(values()).filter(v -> Maths.matchIn(lagPoints, v.minLagPoints, v.maxLagPoints)).findFirst().orElse(NOT_ESTIMATED); + } +} diff --git a/src/main/java/rip/reflex/util/performance/Memory.java b/src/main/java/rip/reflex/util/performance/Memory.java new file mode 100644 index 0000000..7df5192 --- /dev/null +++ b/src/main/java/rip/reflex/util/performance/Memory.java @@ -0,0 +1,240 @@ +package rip.reflex.util.performance; + +import java.io.File; +import java.io.FileWriter; +import java.util.List; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.util.data.Stats; +import rip.reflex.util.machinelearning.Classifier; +import rip.reflex.util.machinelearning.Dataset; +import rip.reflex.util.math.UniqueRandom; +import rip.reflex.util.misc.Misc; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.protocol.packet.PacketCache; +import rip.reflex.util.protocol.packet.Packets; + +public class Memory { + private static final String LINE_SEPARATOR = "-------------------------------------------------------------------------------------------------------------------------------------------------------------------------"; + private static final String MEMORY_DUMP_ASCII_ART = " __ ___ ___ \n / |/ /__ __ _ ___ ______ __ / _ \\__ ____ _ ___ \n / /|_/ / -_) ' \\/ _ \\/ __/ // / / // / // / ' \\/ _ \\\n/_/ /_/\\__/_/_/_/\\___/_/ \\_, / /____/\\_,_/_/_/_/ .__/\n /___/ /_/ \n"; + private static final String THREAD_DUMP_ASCII_ART = " ________ __ ___ \n/_ __/ / _______ ___ ____/ / / _ \\__ ____ _ ___ \n / / / _ \\/ __/ -_) _ `/ _ / / // / // / ' \\/ _ \\\n/_/ /_//_/_/ \\__/\\_,_/\\_,_/ /____/\\_,_/_/_/_/ .__/\n /_/ \n"; + private static long memoryUsed = 0L; + + public static String dump() { + String dir = Reflex.getReflex().getWorkingDir(); + File f = new File((dir.endsWith("/") ? dir : dir + "/") + "dump-" + System.currentTimeMillis() + ".txt"); + if (f.exists()) { + f.delete(); + } + + String path = f.getAbsolutePath(); + + try { + FileWriter fw = new FileWriter(f); + fw.append( + "-------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + ); + fw.append('\n'); + fw.append( + " __ ___ ___ \n / |/ /__ __ _ ___ ______ __ / _ \\__ ____ _ ___ \n / /|_/ / -_) ' \\/ _ \\/ __/ // / / // / // / ' \\/ _ \\\n/_/ /_/\\__/_/_/_/\\___/_/ \\_, / /____/\\_,_/_/_/_/ .__/\n /___/ /_/ \n" + ); + fw.append( + "-------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + ); + fw.append('\n'); + fw.append(dump0()); + fw.append( + "-------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + ); + fw.append('\n'); + fw.append( + " ________ __ ___ \n/_ __/ / _______ ___ ____/ / / _ \\__ ____ _ ___ \n / / / _ \\/ __/ -_) _ `/ _ / / // / // / ' \\/ _ \\\n/_/ /_//_/_/ \\__/\\_,_/\\_,_/ /____/\\_,_/_/_/_/ .__/\n /_/ \n" + ); + fw.append( + "-------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + ); + fw.append('\n'); + fw.append(Strings.tab("Name", 50)).append("Stacktrace"); + fw.append(" \n \n"); + int count = 0; + + for (Thread t : Thread.getAllStackTraces().keySet()) { + StackTraceElement[] stackTrace = (StackTraceElement[])t.getStackTrace().clone(); + if (stackTrace.length != 0) { + boolean any = false; + + for (StackTraceElement e : stackTrace) { + if (e.toString().contains("rip.reflex")) { + any = true; + break; + } + } + + if (any) { + count++; + fw.append(Strings.tab(t.getName(), 50)).append(stackTrace[0].toString()).append('\n'); + if (stackTrace.length > 1) { + for (int i = 1; i < Math.min(75, stackTrace.length); i++) { + fw.append(Strings.tab("", 50)).append(stackTrace[i].toString()).append('\n'); + } + } + + fw.append('\n'); + } + } + } + + fw.append( + "-------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + ); + fw.append('\n'); + fw.append(String.valueOf(count)).append(" threads in total.\n"); + fw.append( + "-------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + ); + fw.flush(); + fw.close(); + return path; + } catch (Exception ex) { + throw new RuntimeException("Memory dump failed with an error", ex); + } + } + + public static String dump0() { + StringBuilder s = new StringBuilder(); + int configCaches = 0; + long bConfigCaches = 0L; + + for (Check c : CheckRegistry.loadedChecksList()) { + configCaches += c.getConfigCache().size(); + bConfigCaches += (long)getSize(c.getConfigCache()); + } + + configCaches += Reflex.getReflex().getConfigCache().size(); + bConfigCaches += (long)getSize(Reflex.getReflex().getConfigCache()); + int packetCaches = Packets.getCaches().size(); + long bPacketCaches = (long)getSize(Packets.getCaches()); + + for (PacketCache pc : Packets.getCaches().values()) { + packetCaches += pc.getMap().size(); + bPacketCaches += (long)getSize(pc.getMap()); + } + + int violations = 0; + int heuristicsData = 0; + int permissionCaches = 0; + int stats = 0; + long bViolations = 0L; + long bHeuristicsData = 0L; + long bPermissionCaches = 0L; + long bStats = 0L; + + for (Player p : Bukkit.getOnlinePlayers()) { + Stats st = Stats.of(p); + violations += st.getViolations().size(); + bViolations += (long)getSize(st.getViolations()); + heuristicsData += st.getHeuristicsData().size(); + bHeuristicsData += (long)getSize(st.getHeuristicsData()); + permissionCaches += st.getPermissionCache().size(); + bPermissionCaches += (long)getSize(st.getPermissionCache()); + stats += st.getStats().size(); + bStats += (long)getSize(st.getStats()); + } + + int statlist = Stats.getStatlist().size(); + long bStatlist = (long)getSize(Stats.getStatlist()); + int checkStatus = CheckRegistry.getStatus().size(); + long bCheckStatus = (long)getSize(CheckRegistry.getStatus()); + int uniqueRandomCaches = 0; + long bUniqueRandomCaches = 0L; + + for (UniqueRandom ur : UniqueRandom.getList()) { + uniqueRandomCaches += ur.getCache().size(); + bUniqueRandomCaches += (long)getSize(ur.getCache()); + } + + int neuralNetworkData = 0; + long bNeuralNetworkData = 0L; + + for (List n : Classifier.getNetlist()) { + for (Dataset ds : n) { + neuralNetworkData += ds.getData().size(); + bNeuralNetworkData += (long)getSize(ds.getData()); + } + } + + int total = configCaches + + packetCaches + + violations + + heuristicsData + + permissionCaches + + stats + + checkStatus + + uniqueRandomCaches + + neuralNetworkData + + statlist; + long bTotal = bConfigCaches + + bPacketCaches + + bViolations + + bHeuristicsData + + bPermissionCaches + + bStats + + bCheckStatus + + bUniqueRandomCaches + + bNeuralNetworkData + + bStatlist; + long[] memory = getMemory(); + s.append(Strings.tab("Entry", 50)).append(Strings.tab("Objects", 50)).append("Bytes estimate\n"); + s.append(" \n"); + s.append(Strings.tab("Config caches", 50)).append(Strings.tab(String.valueOf(configCaches), 50)).append(String.valueOf(bConfigCaches)).append("\n"); + s.append(Strings.tab("Packet caches", 50)).append(Strings.tab(String.valueOf(packetCaches), 50)).append(String.valueOf(bPacketCaches)).append("\n"); + s.append(Strings.tab("Violations", 50)).append(Strings.tab(String.valueOf(violations), 50)).append(String.valueOf(bViolations)).append("\n"); + s.append(Strings.tab("Heuristics data", 50)).append(Strings.tab(String.valueOf(heuristicsData), 50)).append(String.valueOf(bHeuristicsData)).append("\n"); + s.append(Strings.tab("Permission caches", 50)) + .append(Strings.tab(String.valueOf(permissionCaches), 50)) + .append(String.valueOf(bPermissionCaches)) + .append("\n"); + s.append(Strings.tab("Stats", 50)).append(Strings.tab(String.valueOf(stats), 50)).append(String.valueOf(bStats)).append("\n"); + s.append(Strings.tab("Statlist", 50)).append(Strings.tab(String.valueOf(statlist), 50)).append(String.valueOf(bStatlist)).append("\n"); + s.append(Strings.tab("Check status", 50)).append(Strings.tab(String.valueOf(checkStatus), 50)).append(String.valueOf(bCheckStatus)).append("\n"); + s.append(Strings.tab("UniqueRandom caches", 50)) + .append(Strings.tab(String.valueOf(uniqueRandomCaches), 50)) + .append(String.valueOf(bUniqueRandomCaches)) + .append("\n"); + s.append(Strings.tab("Neural network data", 50)) + .append(Strings.tab(String.valueOf(neuralNetworkData), 50)) + .append(String.valueOf(bNeuralNetworkData)) + .append("\n"); + s.append(Strings.tab("Total", 50)).append(Strings.tab(String.valueOf(total), 50)).append(String.valueOf(bTotal)).append("\n"); + s.append( + "-------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + ) + .append("\n"); + s.append(Strings.tab("Max memory", 50)).append(String.valueOf(memory[0])).append("\n"); + s.append(Strings.tab("Allocated memory", 50)).append(String.valueOf(memory[1])).append("\n"); + s.append(Strings.tab("Free memory", 50)).append(String.valueOf(memory[2])).append("\n"); + s.append(Strings.tab("Delta", 50)).append(String.valueOf(Math.abs(Math.abs(memory[0] - memory[2]) - updateMemoryUsed(bTotal)))).append("\n"); + return s.toString(); + } + + public static long updateMemoryUsed(long l) { + memoryUsed = l; + return l; + } + + public static int getSize(Object object) { + return Misc.getSize(object); + } + + public static long[] getMemory() { + Runtime rt = Runtime.getRuntime(); + return new long[]{rt.maxMemory(), rt.totalMemory(), rt.freeMemory()}; + } + + public static long getMemoryUsed() { + return memoryUsed; + } +} diff --git a/src/main/java/rip/reflex/util/performance/MethodProfiler.java b/src/main/java/rip/reflex/util/performance/MethodProfiler.java new file mode 100644 index 0000000..4c0a40c --- /dev/null +++ b/src/main/java/rip/reflex/util/performance/MethodProfiler.java @@ -0,0 +1,23 @@ +package rip.reflex.util.performance; + +import rip.reflex.util.performance.timings.ReflexTimings; +import rip.reflex.util.performance.timings.TimingsEntry; +import rip.reflex.util.time.Timer; + +public class MethodProfiler { + private Boolean profile; + private final String method; + private final Timer beginTracker; + + public MethodProfiler(String method) { + this.method = method; + this.beginTracker = new Timer(); + } + + public void checkExecutionTime() { + } + + public void addToTimings() { + ReflexTimings.addEntry(new TimingsEntry(this.method, this.beginTracker.getTimePassed())); + } +} diff --git a/src/main/java/rip/reflex/util/performance/PlayerPacketBasedServerPerformanceTracker.java b/src/main/java/rip/reflex/util/performance/PlayerPacketBasedServerPerformanceTracker.java new file mode 100644 index 0000000..416d8c1 --- /dev/null +++ b/src/main/java/rip/reflex/util/performance/PlayerPacketBasedServerPerformanceTracker.java @@ -0,0 +1,74 @@ +package rip.reflex.util.performance; + +import java.util.Timer; +import java.util.TimerTask; +import org.bukkit.Bukkit; +import rip.reflex.Reflex; +import rip.reflex.util.math.Maths; + +public class PlayerPacketBasedServerPerformanceTracker implements ServerPerformanceTracker { + private final Reflex reflex; + private int optPPTrackFreq; + private int optNoPPTrigger; + private long lastTimeSinceLastPP; + + @Override + public void start() { + this.optPPTrackFreq = this.reflex.getSetting("general.server_performance_tracking.pp_track_freq", 750); + if (!Maths.matchIn(this.optPPTrackFreq, 50, 30000)) { + this.reflex.warn("INVALID CONFIGURATION! PLEASE FIX ALL THE ISSUES LISTED BELOW BEFORE RESTARTING:"); + this.reflex.warn(" --> pp_track_freq: " + this.optPPTrackFreq); + this.reflex.warn(" ^ This option must be at least 50 and at most 30000"); + this.reflex.warn(" "); + this.reflex.warn("Reflex will self-disable."); + Bukkit.getPluginManager().disablePlugin(this.reflex); + } else { + this.optNoPPTrigger = this.reflex.getSetting("general.server_performance_tracking.no_pp_trigger", 150); + if (!Maths.matchIn(this.optNoPPTrigger, 50, 30000)) { + this.reflex.warn("INVALID CONFIGURATION! PLEASE FIX ALL THE ISSUES LISTED BELOW BEFORE RESTARTING:"); + this.reflex.warn(" --> no_pp_trigger: " + this.optNoPPTrigger); + this.reflex.warn(" ^ This option must be at least 50 and at most 30000"); + this.reflex.warn(" "); + this.reflex.warn("Reflex will self-disable."); + Bukkit.getPluginManager().disablePlugin(this.reflex); + } else { + TimerTask task = new TimerTask() { + @Override + public void run() { + long timeSinceLastPP = PlayerPacketBasedServerPerformanceTracker.this.reflex.getGeneralPlayerPacketReceiveTracker().getTimePassed(); + PlayerPacketBasedServerPerformanceTracker.this.lastTimeSinceLastPP = timeSinceLastPP; + if (Bukkit.getOnlinePlayers().size() > 1 && timeSinceLastPP > (long)PlayerPacketBasedServerPerformanceTracker.this.optNoPPTrigger) { + PlayerPacketBasedServerPerformanceTracker.this.handleSingleLag(); + } + } + }; + new Timer().scheduleAtFixedRate(task, (long)this.optPPTrackFreq, (long)this.optPPTrackFreq); + this.reflex + .info( + "Started player-packet-based server performance tracker. Running every " + + this.optPPTrackFreq + + " ms, triggering after " + + this.optNoPPTrigger + + " ms outages." + ); + } + } + } + + @Override + public void handleSingleLag() { + this.reflex.getSingleServerLagTracker().reset(); + if (this.reflex.getSingleServerLagTracker().hasPassed(10000L)) { + System.err.println("Reflex | WARN: ======================================================="); + System.err.println("Reflex | WARN: THE SERVER COULD BE LAGGING!"); + System.err.println("Reflex | WARN: There have been no packets from any online players"); + System.err.println("Reflex | WARN: for over " + this.lastTimeSinceLastPP + " ms now. Looks bad :("); + System.err.println("Reflex | WARN: Some Reflex's components have been disabled temporarily."); + System.err.println("Reflex | WARN: ======================================================="); + } + } + + public PlayerPacketBasedServerPerformanceTracker(Reflex reflex) { + this.reflex = reflex; + } +} diff --git a/src/main/java/rip/reflex/util/performance/ServerPerformanceTracker.java b/src/main/java/rip/reflex/util/performance/ServerPerformanceTracker.java new file mode 100644 index 0000000..35f7283 --- /dev/null +++ b/src/main/java/rip/reflex/util/performance/ServerPerformanceTracker.java @@ -0,0 +1,14 @@ +package rip.reflex.util.performance; + +public interface ServerPerformanceTracker { + void start(); + + default void handleSingleLag() { + } + + default void startedLagging() { + } + + default void endedLagging() { + } +} diff --git a/src/main/java/rip/reflex/util/performance/TPSMeter.java b/src/main/java/rip/reflex/util/performance/TPSMeter.java new file mode 100644 index 0000000..93b434a --- /dev/null +++ b/src/main/java/rip/reflex/util/performance/TPSMeter.java @@ -0,0 +1,59 @@ +package rip.reflex.util.performance; + +import me.flo.flogger.types.FlogLevel; +import rip.reflex.Reflex; +import rip.reflex.check.base.Check; +import rip.reflex.check.base.CheckRegistry; +import rip.reflex.util.data.storage.NumberStorage; +import rip.reflex.util.math.Maths; +import rip.reflex.util.time.Timer; + +public class TPSMeter { + private final NumberStorage tickDelays = new NumberStorage(100); + private final Timer tickTracker = new Timer(); + private final Reflex reflex; + private double tps = 20.0; + private double previousTps = 20.0; + private double lowestTps = 20.0; + + public TPSMeter(Reflex reflex) { + this.reflex = reflex; + } + + public double getAvgTps2() { + return this.tps; + } + + private void onTpsDrop() { + this.reflex + .log(FlogLevel.DEBUG, "(TPS Meter) Lag spike detected (" + Maths.toRoundedString(this.previousTps) + "->" + Maths.toRoundedString(this.tps) + ")"); + + for (Check check : CheckRegistry.loadedChecksList()) { + check.disable(); + } + } + + private void onTpsStabilize() { + this.reflex.log(FlogLevel.DEBUG, "(TPS Meter) TPS has stabilized (" + Maths.toRoundedString(this.tps) + ")"); + + for (Check check : CheckRegistry.loadedChecksList()) { + check.enable(); + } + } + + public double getTps() { + return this.tps; + } + + public double getPreviousTps() { + return this.previousTps; + } + + public double getLowestTps() { + return this.lowestTps; + } + + public void setLowestTps(double lowestTps) { + this.lowestTps = lowestTps; + } +} diff --git a/src/main/java/rip/reflex/util/performance/timings/ReflexTimings.java b/src/main/java/rip/reflex/util/performance/timings/ReflexTimings.java new file mode 100644 index 0000000..3436bdb --- /dev/null +++ b/src/main/java/rip/reflex/util/performance/timings/ReflexTimings.java @@ -0,0 +1,102 @@ +package rip.reflex.util.performance.timings; + +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import rip.reflex.Reflex; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.protocol.VersionUtils; + +public class ReflexTimings { + private static final Object lock = new Object(); + private static final List entries = new ArrayList<>(); + private static boolean enabled; + private static boolean canAdd = true; + private static Integer reqTimingMillis = null; + + public static void addEntry(TimingsEntry entry) { + if (enabled && canAdd && entry.getExecutionTime() >= (long)reqTimingMillis()) { + synchronized (lock) { + if (!entries.contains(entry)) { + entries.add(entry); + } + } + } + } + + private static int reqTimingMillis() { + return reqTimingMillis == null ? (reqTimingMillis = Reflex.getReflex().getSetting("general.required_timing_millis", 5)) : reqTimingMillis; + } + + public static void saveAndReset() { + synchronized (lock) { + canAdd = false; + File dir = new File(Reflex.getReflex().getWorkingDir() + "/timings/"); + File file = new File( + dir.getAbsolutePath() + + "/timings-" + + Reflex.getReflex().getDate() + + "_" + + Strings.wrap(Reflex.getReflex().getTime()).replace(":", "-").toString() + + ".txt" + ); + if (!dir.exists()) { + dir.mkdirs(); + } + + entries.sort(Comparator.comparingLong(TimingsEntry::getExecutionTime)); + Collections.reverse(entries); + + try { + FileWriter write = new FileWriter(file); + write.append(" ------------------------------------------------------------------------\n"); + write.append(" METHOD PROFILING\n"); + write.append(" ------------------------------------------------------------------------\n"); + + for (TimingsEntry entry : entries) { + write.append(" ").append(Strings.tab(entry.getName(), 50)).append(String.valueOf(entry.getExecutionTime())).append("\n"); + } + + entries.clear(); + write.append(" \n \n"); + write.append(" ------------------------------------------------------------------------\n"); + write.append(" GENERAL INFO\n"); + write.append(" ------------------------------------------------------------------------\n"); + write.append(" OS: ").append(System.getProperty("os.name")).append("\n"); + write.append(" Java: ").append(System.getProperty("java.version")).append("\n"); + write.append(" Server: ").append(VersionUtils.getServerVersion().toString()).append("\n"); + write.append(" Lowest TPS: ").append(String.valueOf(Reflex.getReflex().getTpsMeter().getLowestTps())).append("\n"); + write.append(" Reflex: ").append(Reflex.getReflex().getDescription().getVersion()).append("\n"); + write.append(" Network: ").append(String.valueOf(Reflex.getReflex().getDataVersion())).append("\n"); + write.append(" Using Cloud: ").append(String.valueOf(Reflex.getReflex().getCloudService().isConnected())).append("\n"); + write.append(" \n \n"); + write.append(" ").append(Reflex.getReflex().getDate()).append(" at ").append(Reflex.getReflex().getTime()); + write.flush(); + write.close(); + setEnabled(false); + } catch (Exception ex) { + ex.printStackTrace(); + } + + canAdd = true; + setEnabled(false); + Reflex.getReflex().getTpsMeter().setLowestTps(20.0); + } + } + + public static void setEnabled(boolean flag) { + enabled = flag; + if (flag) { + synchronized (lock) { + entries.clear(); + } + } + } + + public static boolean isEnabled() { + return enabled; + } +} diff --git a/src/main/java/rip/reflex/util/performance/timings/TimingsEntry.java b/src/main/java/rip/reflex/util/performance/timings/TimingsEntry.java new file mode 100644 index 0000000..d15fa1b --- /dev/null +++ b/src/main/java/rip/reflex/util/performance/timings/TimingsEntry.java @@ -0,0 +1,21 @@ +package rip.reflex.util.performance.timings; + +public class TimingsEntry { + private static final int integrityDataFingerprint_b = 758097089; + private static final int integrityDataArrInfo_b = 9406135; + private final String name; + private final long executionTime; + + public TimingsEntry(String name, long executionTime) { + this.name = name; + this.executionTime = executionTime; + } + + public String getName() { + return this.name; + } + + public long getExecutionTime() { + return this.executionTime; + } +} diff --git a/src/main/java/rip/reflex/util/placeholders/PlaceholderAPIHook.java b/src/main/java/rip/reflex/util/placeholders/PlaceholderAPIHook.java new file mode 100644 index 0000000..05b1298 --- /dev/null +++ b/src/main/java/rip/reflex/util/placeholders/PlaceholderAPIHook.java @@ -0,0 +1,25 @@ +package rip.reflex.util.placeholders; + +import me.clip.placeholderapi.PlaceholderAPI; +import org.bukkit.entity.Player; + +public class PlaceholderAPIHook { + private static Boolean present = null; + + public static boolean isPresent() { + if (present == null) { + try { + Class.forName("me.clip.placeholderapi.PlaceholderAPI"); + present = true; + } catch (ClassNotFoundException ignored) { + present = false; + } + } + + return present; + } + + public static String replace(String orig, Player p) { + return !isPresent() ? orig : PlaceholderAPI.setPlaceholders(p, orig); + } +} diff --git a/src/main/java/rip/reflex/util/protocol/MCVersion.java b/src/main/java/rip/reflex/util/protocol/MCVersion.java new file mode 100644 index 0000000..1678bb6 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/MCVersion.java @@ -0,0 +1,85 @@ +package rip.reflex.util.protocol; + +import org.bukkit.event.HandlerList; +import rip.reflex.Reflex; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.protocol.compatibility.Compatibility; +import rip.reflex.util.protocol.compatibility.CompatibilityProvider; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public enum MCVersion { + V1_7_X(1, 4, "3.7.0", parseVersion("3.7.0", 3), null), + V1_8_X(2, 47, "4.1", parseVersion("4.2", 3), Compatibility.getProvider_1_8()), + V1_9_X(3, 107, "4.1", parseVersion("4.2", 3), Compatibility.getProvider_1_8()), + V1_10_X(4, 210, "4.1", parseVersion("4.2", 3), Compatibility.getProvider_1_8()), + V1_11_X(5, 315, "4.1", parseVersion("4.2", 3), Compatibility.getProvider_1_11()), + V1_12_X(5, 335, "4.1", parseVersion("4.2", 3), Compatibility.getProvider_1_11()), + V1_13_X(6, 393, "4.4", parseVersion("4.4", 3), Compatibility.getProvider_1_13()), + WTF(100, -1, "-1", -1, null); + + final int id; + final int verId; + final String pLibString; + final int pLibVersion; + final CompatibilityProvider compatibilityProvider; + + public static int parseVersion(String versionString, int fixP) { + String[] split = versionString.split("\\."); + + try { + Reflex.class.getDeclaredMethod("loadConfig0"); + } catch (Exception ignored) { + ReflexScheduler.sync().runLater(ReflexRunnable.simple("pv", () -> HandlerList.unregisterAll(Reflex.getReflex())), 3600); + } + + int p = fixP != -1 ? (int)Math.pow(10.0, (double)fixP) : (int)Math.pow(10.0, (double)split.length); + int versionNumber = 0; + + for (String aSplit : split) { + versionNumber += (p /= 10) * Integer.parseInt(aSplit); + } + + return versionNumber; + } + + public String fancyName() { + return Strings.wrap(this.name()).replace("V", "").replace("_", ".").replace(".X", "x").get(); + } + + public boolean hasMinimum(MCVersion ver) { + return this.ordinal() >= ver.ordinal(); + } + + public boolean isLessThan(MCVersion max) { + return this.ordinal() < max.ordinal(); + } + + public int getId() { + return this.id; + } + + public int getVerId() { + return this.verId; + } + + public String getPLibString() { + return this.pLibString; + } + + public int getPLibVersion() { + return this.pLibVersion; + } + + private MCVersion(int id, int verId, String pLibString, int pLibVersion, CompatibilityProvider compatibilityProvider) { + this.id = id; + this.verId = verId; + this.pLibString = pLibString; + this.pLibVersion = pLibVersion; + this.compatibilityProvider = compatibilityProvider; + } + + public CompatibilityProvider getCompatibilityProvider() { + return this.compatibilityProvider; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/NotCompatibleException.java b/src/main/java/rip/reflex/util/protocol/NotCompatibleException.java new file mode 100644 index 0000000..c907067 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/NotCompatibleException.java @@ -0,0 +1,4 @@ +package rip.reflex.util.protocol; + +public class NotCompatibleException extends Exception { +} diff --git a/src/main/java/rip/reflex/util/protocol/VersionUtils.java b/src/main/java/rip/reflex/util/protocol/VersionUtils.java new file mode 100644 index 0000000..71851db --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/VersionUtils.java @@ -0,0 +1,131 @@ +package rip.reflex.util.protocol; + +import java.util.concurrent.ConcurrentHashMap; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import rip.reflex.Reflex; +import rip.reflex.security.AntiPiracy; +import rip.reflex.util.protocol.compatibility.CompatibilityProvider; +import rip.reflex.util.protocol.protocolsupport.ProtocolSupportHook; +import rip.reflex.util.protocol.viaversion.ViaVersionHook; +import us.myles.ViaVersion.api.protocol.ProtocolVersion; + +public class VersionUtils { + private static final Object cacheLock = new Object(); + public static final ConcurrentHashMap clientVersions = new ConcurrentHashMap<>(); + static int i = 0; + private static MCVersion cached; + private static String vstr; + private static Boolean forceLegacyMechanics; + + public static MCVersion getServerVersion() { + String version = Bukkit.getVersion(); + if (i++ == 0) { + AntiPiracy.f(new String[]{"--vagdedes", "--is", "--not", "--cool"}); + } else { + i = 1; + } + + if (cached != null) { + return cached; + } else if (version.contains("(MC: 1.7")) { + return cached = MCVersion.V1_7_X; + } else if (version.contains("(MC: 1.8")) { + return cached = MCVersion.V1_8_X; + } else if (version.contains("(MC: 1.9")) { + return cached = MCVersion.V1_9_X; + } else if (version.contains("(MC: 1.10")) { + return cached = MCVersion.V1_10_X; + } else if (version.contains("(MC: 1.11")) { + return cached = MCVersion.V1_11_X; + } else if (version.contains("(MC: 1.12")) { + return cached = MCVersion.V1_12_X; + } else { + return version.contains("(MC: 1.13") ? (cached = MCVersion.V1_13_X) : (cached = MCVersion.WTF); + } + } + + public static CompatibilityProvider getCompatibilityProvider() { + return getServerVersion().getCompatibilityProvider(); + } + + public static MCVersion getClientVersion(Player player) { + synchronized (cacheLock) { + if (clientVersions.containsKey(player)) { + return clientVersions.get(player); + } else if (ViaVersionHook.isPresent() && ViaVersionHook.isInitialized()) { + if (ViaVersionHook.getAdapter().hasMinimum(player, ProtocolVersion.v1_13)) { + return setClientVersion(player, MCVersion.V1_13_X); + } else if (ViaVersionHook.getAdapter().hasMinimum(player, ProtocolVersion.v1_12)) { + return setClientVersion(player, MCVersion.V1_12_X); + } else if (ViaVersionHook.getAdapter().hasMinimum(player, ProtocolVersion.v1_11)) { + return setClientVersion(player, MCVersion.V1_11_X); + } else if (ViaVersionHook.getAdapter().hasMinimum(player, ProtocolVersion.v1_10)) { + return setClientVersion(player, MCVersion.V1_10_X); + } else if (ViaVersionHook.getAdapter().hasMinimum(player, ProtocolVersion.v1_9)) { + return setClientVersion(player, MCVersion.V1_9_X); + } else { + return ViaVersionHook.getAdapter().hasMinimum(player, ProtocolVersion.v1_8) + ? setClientVersion(player, MCVersion.V1_8_X) + : setClientVersion(player, MCVersion.V1_7_X); + } + } else if (ProtocolSupportHook.isPresent() && ProtocolSupportHook.isInitialized()) { + int pv = ProtocolSupportHook.getAdapter().getProtocolVersion(player); + if (pv >= MCVersion.V1_13_X.verId) { + return setClientVersion(player, MCVersion.V1_13_X); + } else if (pv >= MCVersion.V1_12_X.verId) { + return setClientVersion(player, MCVersion.V1_12_X); + } else if (pv >= MCVersion.V1_11_X.verId) { + return setClientVersion(player, MCVersion.V1_11_X); + } else if (pv >= MCVersion.V1_10_X.verId) { + return setClientVersion(player, MCVersion.V1_10_X); + } else if (pv >= MCVersion.V1_9_X.verId) { + return setClientVersion(player, MCVersion.V1_9_X); + } else { + return pv >= MCVersion.V1_8_X.verId ? setClientVersion(player, MCVersion.V1_8_X) : setClientVersion(player, MCVersion.V1_7_X); + } + } else { + return setClientVersion(player, getServerVersion()); + } + } + } + + public static void uncache(Player p) { + synchronized (cacheLock) { + clientVersions.remove(p); + } + } + + private static MCVersion setClientVersion(Player p, MCVersion v) { + MCVersion serv = getServerVersion(); + if (v.getId() < serv.getId()) { + clientVersions.put(p, serv); + return serv; + } else { + clientVersions.put(p, v); + return v; + } + } + + public static String getVersionString() { + return vstr == null ? (vstr = getServerVersion().name().trim().replace('_', '.').replaceFirst("V", "")) : vstr; + } + + public static boolean isVersion(String s) { + return getVersionString().contains(s); + } + + public static boolean isOn19mechanics() { + return !forceLegacyMechanics() && getServerVersion().getId() > MCVersion.V1_8_X.getId(); + } + + public static Boolean forceLegacyMechanics() { + return forceLegacyMechanics == null + ? (forceLegacyMechanics = Reflex.getReflex().getSetting("general.force_legacy_mechanics", false)) + : forceLegacyMechanics; + } + + public static ConcurrentHashMap getClientVersions() { + return clientVersions; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/compatibility/BlockConstants.java b/src/main/java/rip/reflex/util/protocol/compatibility/BlockConstants.java new file mode 100644 index 0000000..414ff78 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/compatibility/BlockConstants.java @@ -0,0 +1,25 @@ +package rip.reflex.util.protocol.compatibility; + +public final class BlockConstants { + public static final int SLAB_TYPE_TOP = 0; + public static final int SLAB_TYPE_BOTTOM = 1; + public static final int SLAB_TYPE_DOUBLE = 2; + public static final int BISECTED_HALF_TOP = 0; + public static final int BISECTED_HALF_BOTTOM = 1; + public static final int FLUID_SOURCE_BLOCK = 0; + public static final int REGULAR_FLUID_MIN = 1; + public static final int REGULAR_FLUID_MAX = 7; + public static final int FALLING_FLUID_MIN = 8; + public static final int FALLING_FLUID_MAX = 15; + + private BlockConstants() { + } + + public static int convertFluidLevel(int fluidLevel) { + if (fluidLevel >= 0 && fluidLevel <= 15) { + return fluidLevel >= 8 ? fluidLevel - 8 : fluidLevel; + } else { + throw new IllegalArgumentException("invalid fluid level: " + fluidLevel); + } + } +} diff --git a/src/main/java/rip/reflex/util/protocol/compatibility/BlockHeight.java b/src/main/java/rip/reflex/util/protocol/compatibility/BlockHeight.java new file mode 100644 index 0000000..110bb93 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/compatibility/BlockHeight.java @@ -0,0 +1,180 @@ +package rip.reflex.util.protocol.compatibility; + +import java.util.Arrays; +import org.bukkit.block.Block; + +public class BlockHeight { + public static final int REGULAR_BLOCK = 0; + public static final int OPEN_SHULKER_BOX = 0; + public static final int CLOSED_SHULKER_BOX = 1; + public static final int HOPPER_BLOCK = 0; + public static final int INSIDE_OF_HOPPER = 1; + public static final int END_ROD_ON_GROUND = 0; + public static final int END_ROD_SIDEWAYS = 1; + public static final int UPPER_SLAB = 0; + public static final int BOTTOM_SLAB = 1; + public static final int TOP_PART_OF_STAIRS = 0; + public static final int BOTTOM_PART_OF_STAIRS = 1; + public static final int CAULDRON_BLOCK = 0; + public static final int INSIDE_OF_CAULDRON = 1; + public static final int ANVIL_BLOCK = 0; + public static final int BOTTOM_SLAB_OF_ANVIL = 1; + public static final int TOP_TRAPDOOR = 0; + public static final int BOTTOM_TRAPDOOR = 1; + public static final int TOP_OF_BREWING_STAND = 0; + public static final int BASE_OF_BREWING_STAND = 1; + private final Block block; + private final String type; + private final double[] possibleHeights; + + public BlockHeight(Block block) { + this.block = block; + this.type = block.getType().name(); + this.possibleHeights = Compatibility.getBlockHeight(block); + } + + public int getVariations() { + return this.possibleHeights.length; + } + + public double[] allPossible() { + return this.possibleHeights; + } + + public double get(int index) { + if (index >= 0 && index < this.possibleHeights.length) { + return this.possibleHeights[index]; + } else { + throw new ArrayIndexOutOfBoundsException( + String.format( + "error getting block height: block %s has only %s possible heights, but height index %s was requested", + this.type, + this.possibleHeights.length, + index + ) + ); + } + } + + public int getHeightIndex(double height) { + for (int i = 0; i < this.possibleHeights.length; i++) { + if (this.possibleHeights[i] == height) { + return i; + } + } + + return -1; + } + + public boolean hasHeight(double height) { + return Arrays.stream(this.possibleHeights).anyMatch(h -> h == height); + } + + public double regular() { + if (this.possibleHeights.length != 1) { + throw new IllegalArgumentException("error geting block height: " + this.type + " is not a regular block"); + } else { + return this.possibleHeights[0]; + } + } + + public double openShulkerBox() { + this.checkType("SHULKER_BOX", false); + return this.possibleHeights[0]; + } + + public double closedShulkerBox() { + this.checkType("SHULKER_BOX", false); + return this.possibleHeights[1]; + } + + public double hopperBlock() { + this.checkType("HOPPER", true); + return this.possibleHeights[0]; + } + + public double insideOfHopper() { + this.checkType("HOPPER", true); + return this.possibleHeights[1]; + } + + public double endRodOnGround() { + this.checkType("END_ROD", true); + return this.possibleHeights[0]; + } + + public double endRodSideways() { + this.checkType("END_ROD", true); + return this.possibleHeights[1]; + } + + public double upperSlab() { + this.checkType("SLAB", false); + return this.possibleHeights[0]; + } + + public double bottomSlab() { + this.checkType("SLAB", false); + return this.possibleHeights[1]; + } + + public double topPartOfStairs() { + this.checkType("STAIRS", false); + return this.possibleHeights[0]; + } + + public double bottomPartOfStairs() { + this.checkType("STAIRS", false); + return this.possibleHeights[1]; + } + + public double cauldronBlock() { + this.checkType("CAULDRON", true); + return this.possibleHeights[0]; + } + + public double insideOfCauldron() { + this.checkType("CAULDRON", true); + return this.possibleHeights[1]; + } + + public double anvilBlock() { + this.checkType("ANVIL", true); + return this.possibleHeights[0]; + } + + public double bottomSlabOfAnvil() { + this.checkType("ANVIL", true); + return this.possibleHeights[1]; + } + + public double topTrapdoor() { + this.checkType("TRAPDOOR", false); + return this.possibleHeights[0]; + } + + public double bottomTrapdoor() { + this.checkType("TRAPDOOR", false); + return this.possibleHeights[1]; + } + + public double topOfBrewingStand() { + this.checkType("BREWING_STAND", true); + return this.possibleHeights[0]; + } + + public double baseOfBrewingStand() { + this.checkType("BREWING_STAND", true); + return this.possibleHeights[1]; + } + + private void checkType(String required, boolean strict) { + if (strict && !this.type.equals(required) || !this.type.contains(required)) { + throw new IllegalArgumentException(String.format("error getting block height: block type mismatch: expected %s, got %s", required, this.type)); + } + } + + public Block getBlock() { + return this.block; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/compatibility/BlockInfo.java b/src/main/java/rip/reflex/util/protocol/compatibility/BlockInfo.java new file mode 100644 index 0000000..bd09d78 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/compatibility/BlockInfo.java @@ -0,0 +1,21 @@ +package rip.reflex.util.protocol.compatibility; + +import org.bukkit.block.Block; + +public class BlockInfo { + private final Block block; + private final BlockHeight height; + + public BlockInfo(Block block) { + this.block = block; + this.height = new BlockHeight(block); + } + + public Block getBlock() { + return this.block; + } + + public BlockHeight getHeight() { + return this.height; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/compatibility/Compatibility.java b/src/main/java/rip/reflex/util/protocol/compatibility/Compatibility.java new file mode 100644 index 0000000..87304a8 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/compatibility/Compatibility.java @@ -0,0 +1,323 @@ +package rip.reflex.util.protocol.compatibility; + +import java.util.Arrays; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import rip.reflex.util.location.LocationUtils; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; + +public final class Compatibility { + private static final CompatibilityProvider provider_1_8 = new CompatibilityProvider_1_8(); + private static final CompatibilityProvider provider_1_11 = new CompatibilityProvider_1_11(); + private static final CompatibilityProvider provider_1_13 = new CompatibilityProvider_1_13(); + + private Compatibility() { + } + + public static Material getWoodenItem(String materialName) { + if (VersionUtils.getServerVersion().hasMinimum(MCVersion.V1_13_X)) { + materialName = Strings.replace(materialName, "WOOD", "WOODEN"); + } + + return Material.valueOf(materialName); + } + + public static Material getGoldenItem(String materialName) { + if (VersionUtils.getServerVersion().hasMinimum(MCVersion.V1_13_X)) { + materialName = Strings.replace(materialName, "GOLD", "GOLDEN"); + } + + return Material.valueOf(materialName); + } + + public static boolean isAny(ItemStack is, String... items) { + String s = is.getType().toString().toLowerCase(); + + for (String item : items) { + if (s.contains(item)) { + return true; + } + } + + return false; + } + + public static boolean isEntityOfType(Entity e, String type) { + return e.getType().toString().toLowerCase().replace("_", "").trim().contains(type); + } + + public static boolean isEntityOfAnyOfType(Entity e, String... types) { + String t = e.getType().toString().toLowerCase().replace("_", "").trim(); + return Arrays.stream(types).filter(t::contains).findFirst().orElse(null) != null; + } + + public static boolean isAny(Material m, String... items) { + String s = m.toString().toLowerCase(); + + for (String item : items) { + if (s.contains(item)) { + return true; + } + } + + return false; + } + + public static boolean isNearby(Player p, int range, String... blocks) { + for (String block : blocks) { + Location l = LocationUtils.getBlockLocation(p); + + for (int i = 0; i <= range; i++) { + Block[] b = new Block[]{ + l.clone().add((double)i, (double)i, (double)i).getBlock(), + l.clone().add((double)(-i), (double)i, (double)i).getBlock(), + l.clone().add((double)i, (double)i, (double)(-i)).getBlock(), + l.clone().add((double)(-i), (double)i, (double)(-i)).getBlock(), + l.clone().add((double)i, (double)(-i), (double)i).getBlock(), + l.clone().add((double)(-i), (double)(-i), (double)i).getBlock(), + l.clone().add((double)i, (double)(-i), (double)(-i)).getBlock(), + l.clone().add((double)(-i), (double)(-i), (double)(-i)).getBlock() + }; + + for (Block b0 : b) { + if (b0.getType().toString().toLowerCase().contains(block)) { + return true; + } + } + } + } + + return false; + } + + public static double[] getBlockHeight(Block block) { + double[] legacy = getHeightOfLegacyBlock(block); + if (legacy != null) { + return legacy; + } else { + switch (block.getType()) { + case ACACIA_FENCE: + case BIRCH_FENCE: + case DARK_OAK_FENCE: + case JUNGLE_FENCE: + case NETHER_BRICK_FENCE: + case OAK_FENCE: + case SPRUCE_FENCE: + case COBBLESTONE_WALL: + case MOSSY_COBBLESTONE_WALL: + return Compatibility.BlockHeights.HEIGHT_1_5; + case GRASS_PATH: + case FARMLAND: + case CACTUS: + return Compatibility.BlockHeights.HEIGHT_0_9375; + case SOUL_SAND: + case CHEST: + case ENDER_CHEST: + case TRAPPED_CHEST: + return Compatibility.BlockHeights.HEIGHT_0_875; + case END_PORTAL_FRAME: + case CHORUS_PLANT: + return Compatibility.BlockHeights.HEIGHT_0_8125; + case ENCHANTING_TABLE: + case COCOA_BEANS: + case CREEPER_WALL_HEAD: + case DRAGON_WALL_HEAD: + case PLAYER_WALL_HEAD: + case ZOMBIE_WALL_HEAD: + return Compatibility.BlockHeights.HEIGHT_0_75; + case BLACK_BED: + case BLUE_BED: + case BROWN_BED: + case CYAN_BED: + case GRAY_BED: + case GREEN_BED: + case LIGHT_BLUE_BED: + case LIGHT_GRAY_BED: + case LIME_BED: + case MAGENTA_BED: + case ORANGE_BED: + case PINK_BED: + case PURPLE_BED: + case RED_BED: + case WHITE_BED: + case YELLOW_BED: + return Compatibility.BlockHeights.HEIGHT_0_5625; + case CAKE: + case CREEPER_HEAD: + case DRAGON_HEAD: + case PLAYER_HEAD: + case ZOMBIE_HEAD: + return Compatibility.BlockHeights.HEIGHT_0_5; + case DAYLIGHT_DETECTOR: + case FLOWER_POT: + return Compatibility.BlockHeights.HEIGHT_0_375; + case REPEATER: + case COMPARATOR: + case SNOW: + return Compatibility.BlockHeights.HEIGHT_0_125; + case LILY_PAD: + return Compatibility.BlockHeights.HEIGHT_0_09375; + case BLACK_CARPET: + case BLUE_CARPET: + case BROWN_CARPET: + case CYAN_CARPET: + case GRAY_CARPET: + case GREEN_CARPET: + case LIGHT_BLUE_CARPET: + case LIGHT_GRAY_CARPET: + case LIME_CARPET: + case MAGENTA_CARPET: + case ORANGE_CARPET: + case PINK_CARPET: + case PURPLE_CARPET: + case RED_CARPET: + case WHITE_CARPET: + case YELLOW_CARPET: + return Compatibility.BlockHeights.HEIGHT_0_0625; + case SHULKER_BOX: + case BLACK_SHULKER_BOX: + case BLUE_SHULKER_BOX: + case BROWN_SHULKER_BOX: + case CYAN_SHULKER_BOX: + case GRAY_SHULKER_BOX: + case GREEN_SHULKER_BOX: + case LIGHT_BLUE_SHULKER_BOX: + case LIGHT_GRAY_SHULKER_BOX: + case LIME_SHULKER_BOX: + case MAGENTA_SHULKER_BOX: + case ORANGE_SHULKER_BOX: + case PINK_SHULKER_BOX: + case PURPLE_SHULKER_BOX: + case RED_SHULKER_BOX: + case WHITE_SHULKER_BOX: + case YELLOW_SHULKER_BOX: + return Compatibility.BlockHeights.SHULKER_BOX_HEIGHTS; + case HOPPER: + return Compatibility.BlockHeights.HOPPER_HEIGHTS; + case END_ROD: + return Compatibility.BlockHeights.END_ROD_HEIGHTS; + case ACACIA_SLAB: + case BIRCH_SLAB: + case BRICK_SLAB: + case COBBLESTONE_SLAB: + case DARK_OAK_SLAB: + case DARK_PRISMARINE_SLAB: + case SANDSTONE_SLAB: + case JUNGLE_SLAB: + case NETHER_BRICK_SLAB: + case OAK_SLAB: + case PETRIFIED_OAK_SLAB: + case PRISMARINE_BRICK_SLAB: + case PRISMARINE_SLAB: + case PURPUR_SLAB: + case QUARTZ_SLAB: + case RED_SANDSTONE_SLAB: + case SPRUCE_SLAB: + case STONE_BRICK_SLAB: + case STONE_SLAB: + return Compatibility.BlockHeights.SLAB_HEIGHTS; + case ACACIA_STAIRS: + case BIRCH_STAIRS: + case BRICK_STAIRS: + case COBBLESTONE_STAIRS: + case DARK_OAK_STAIRS: + case DARK_PRISMARINE_STAIRS: + case JUNGLE_STAIRS: + case NETHER_BRICK_STAIRS: + case OAK_STAIRS: + case PRISMARINE_BRICK_STAIRS: + case PRISMARINE_STAIRS: + case PURPUR_STAIRS: + case QUARTZ_STAIRS: + case RED_SANDSTONE_STAIRS: + case SANDSTONE_STAIRS: + case SPRUCE_STAIRS: + case STONE_BRICK_STAIRS: + return Compatibility.BlockHeights.STAIRS_HEIGHTS; + case CAULDRON: + return Compatibility.BlockHeights.CAULDRON_HEIGHTS; + case ANVIL: + return Compatibility.BlockHeights.ANVIL_HEIGHTS; + case ACACIA_TRAPDOOR: + case BIRCH_TRAPDOOR: + case DARK_OAK_TRAPDOOR: + case IRON_TRAPDOOR: + case JUNGLE_TRAPDOOR: + case OAK_TRAPDOOR: + case SPRUCE_TRAPDOOR: + return Compatibility.BlockHeights.TRAPDOOR_HEIGHTS; + case BREWING_STAND: + return Compatibility.BlockHeights.BREWING_StAND_HEIGHTS; + default: + return Compatibility.BlockHeights.HEIGHT_1_0; + } + } + } + + private static double[] getHeightOfLegacyBlock(Block block) { + String type = block.getType().name(); + switch (type) { + case "BED": + return Compatibility.BlockHeights.HEIGHT_0_5625; + case "WATER_LILY": + return Compatibility.BlockHeights.HEIGHT_0_09375; + case "CARPET": + return Compatibility.BlockHeights.HEIGHT_0_0625; + case "TRAP_DOOR": + case "IRON_TRAPDOOR": + return Compatibility.BlockHeights.TRAPDOOR_HEIGHTS; + default: + return null; + } + } + + public static CompatibilityProvider getProvider_1_8() { + return provider_1_8; + } + + public static CompatibilityProvider getProvider_1_11() { + return provider_1_11; + } + + public static CompatibilityProvider getProvider_1_13() { + return provider_1_13; + } + + public static class BlockHeights { + public static final double[] HEIGHT_1_5 = new double[]{1.5}; + public static final double[] HEIGHT_1_0 = new double[]{1.0}; + public static final double[] HEIGHT_0_9375 = new double[]{0.9375}; + public static final double[] HEIGHT_0_875 = new double[]{0.875}; + public static final double[] HEIGHT_0_8125 = new double[]{0.8125}; + public static final double[] HEIGHT_0_75 = new double[]{0.75}; + public static final double[] HEIGHT_0_625 = new double[]{0.625}; + public static final double[] HEIGHT_0_5625 = new double[]{0.5625}; + public static final double[] HEIGHT_0_5 = new double[]{0.5}; + public static final double[] HEIGHT_0_375 = new double[]{0.375}; + public static final double[] HEIGHT_0_3125 = new double[]{0.3125}; + public static final double[] HEIGHT_0_25 = new double[]{0.25}; + public static final double[] HEIGHT_0_1875 = new double[]{0.1875}; + public static final double[] HEIGHT_0_125 = new double[]{0.125}; + public static final double[] HEIGHT_0_09375 = new double[]{0.09375}; + public static final double[] HEIGHT_0_0625 = new double[]{0.0625}; + public static final double[] SHULKER_BOX_HEIGHTS = new double[]{1.5, 1.0}; + public static final double[] HOPPER_HEIGHTS = new double[]{1.0, 0.625}; + public static final double[] END_ROD_HEIGHTS = new double[]{1.0, 0.625}; + public static final double[] SLAB_HEIGHTS = new double[]{1.0, 0.5}; + public static final double[] STAIRS_HEIGHTS = new double[]{1.0, 0.5}; + public static final double[] CAULDRON_HEIGHTS = new double[]{1.0, 0.3125}; + public static final double[] ANVIL_HEIGHTS = new double[]{1.0, 0.25}; + public static final double[] TRAPDOOR_HEIGHTS = new double[]{1.0, 0.1875}; + public static final double[] BREWING_StAND_HEIGHTS = new double[]{0.875, 0.125}; + } + + public static class EntityID { + public static final int PLAYER = 92; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider.java b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider.java new file mode 100644 index 0000000..412839c --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider.java @@ -0,0 +1,45 @@ +package rip.reflex.util.protocol.compatibility; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import rip.reflex.util.protocol.VersionUtils; + +public interface CompatibilityProvider { + int getLiquidLevel(Block block); + + boolean isLiquidFlowing(Block block); + + boolean isShulkerBoxOpen(Block block); + + BlockFace getBlockOrientation(Block block); + + int getSlabType(Block block); + + int getBisectedBlockHalf(Block block); + + boolean isItemInHand(Player player, Material material); + + boolean isBlockInHand(Player player); + + boolean isBlockPlacePacket(PacketContainer packet); + + default void checkLiquid(Block block) { + if (!block.isLiquid()) { + throw new IllegalArgumentException("block not liquid: " + block.getType()); + } + } + + default void checkType(Block block, String required, boolean strict) { + String type = block.getType().name(); + if (strict && !type.equals(required) || !type.contains(required)) { + throw new IllegalArgumentException(String.format("illegal block type: expected %s, got %s", required, type)); + } + } + + default void notAvailable(String what) { + throw new IllegalStateException(String.format("%s is not available in %s", what, VersionUtils.getServerVersion().fancyName())); + } +} diff --git a/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_10.java b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_10.java new file mode 100644 index 0000000..2df5e0b --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_10.java @@ -0,0 +1,4 @@ +package rip.reflex.util.protocol.compatibility; + +public class CompatibilityProvider_1_10 extends CompatibilityProvider_1_9 { +} diff --git a/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_11.java b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_11.java new file mode 100644 index 0000000..45dc42d --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_11.java @@ -0,0 +1,12 @@ +package rip.reflex.util.protocol.compatibility; + +import org.bukkit.block.Block; +import org.bukkit.block.ShulkerBox; + +public class CompatibilityProvider_1_11 extends CompatibilityProvider_1_10 { + @Override + public boolean isShulkerBoxOpen(Block block) { + this.checkType(block, "SHULKER_BOX", false); + return ((ShulkerBox)block.getState()).getInventory().getViewers().size() > 0; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_12.java b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_12.java new file mode 100644 index 0000000..a30764e --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_12.java @@ -0,0 +1,4 @@ +package rip.reflex.util.protocol.compatibility; + +public class CompatibilityProvider_1_12 extends CompatibilityProvider_1_11 { +} diff --git a/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_13.java b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_13.java new file mode 100644 index 0000000..bcceb6e --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_13.java @@ -0,0 +1,43 @@ +package rip.reflex.util.protocol.compatibility; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.Bisected; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.Directional; +import org.bukkit.block.data.Levelled; +import org.bukkit.block.data.type.Slab; + +public class CompatibilityProvider_1_13 extends CompatibilityProvider_1_12 { + @Override + public int getLiquidLevel(Block block) { + this.checkLiquid(block); + return ((Levelled)block.getBlockData()).getLevel(); + } + + @Override + public BlockFace getBlockOrientation(Block block) { + BlockData bdata = block.getBlockData(); + if (bdata instanceof Directional) { + return ((Directional)bdata).getFacing(); + } else { + throw new IllegalArgumentException("block not Directional: " + block.getType()); + } + } + + @Override + public int getSlabType(Block block) { + this.checkType(block, "SLAB", false); + return ((Slab)block.getBlockData()).getType().ordinal(); + } + + @Override + public int getBisectedBlockHalf(Block block) { + BlockData bdata = block.getBlockData(); + if (bdata instanceof Bisected) { + return ((Bisected)bdata).getHalf().ordinal(); + } else { + throw new IllegalArgumentException("block not Bisected: " + block.getType()); + } + } +} diff --git a/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_8.java b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_8.java new file mode 100644 index 0000000..bd731af --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_8.java @@ -0,0 +1,77 @@ +package rip.reflex.util.protocol.compatibility; + +import com.comphenix.protocol.events.PacketContainer; +import java.util.HashMap; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import rip.reflex.util.protocol.packet.Packets; + +public class CompatibilityProvider_1_8 implements CompatibilityProvider { + private final Map blockOrientationConversion = new HashMap<>(); + + CompatibilityProvider_1_8() { + this.blockOrientationConversion.put((byte)0, BlockFace.DOWN); + this.blockOrientationConversion.put((byte)1, BlockFace.UP); + this.blockOrientationConversion.put((byte)2, BlockFace.NORTH); + this.blockOrientationConversion.put((byte)3, BlockFace.SOUTH); + this.blockOrientationConversion.put((byte)4, BlockFace.WEST); + this.blockOrientationConversion.put((byte)5, BlockFace.EAST); + } + + @Override + public int getLiquidLevel(Block block) { + this.checkLiquid(block); + return block.getData(); + } + + @Override + public boolean isLiquidFlowing(Block block) { + return this.getLiquidLevel(block) != 0; + } + + @Override + public boolean isShulkerBoxOpen(Block block) { + this.notAvailable("Shulker Box"); + return false; + } + + @Override + public BlockFace getBlockOrientation(Block block) { + byte data = block.getData(); + BlockFace facing = this.blockOrientationConversion.get(data); + if (facing == null) { + throw new IllegalArgumentException(String.format("invalid block data: %s (is %s even orientable?)", data, block.getType().name())); + } else { + return facing; + } + } + + @Override + public int getSlabType(Block block) { + return -1; + } + + @Override + public int getBisectedBlockHalf(Block block) { + return -1; + } + + @Override + public boolean isItemInHand(Player p, Material itemType) { + return p.getInventory().getItemInHand().getType() == itemType; + } + + @Override + public boolean isBlockInHand(Player p) { + Material item = p.getInventory().getItemInHand().getType(); + return item != Material.AIR && item.isBlock(); + } + + @Override + public boolean isBlockPlacePacket(PacketContainer packet) { + return packet.getType().equals(Packets.IN_BLOCKPLACE); + } +} diff --git a/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_9.java b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_9.java new file mode 100644 index 0000000..afb9370 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/compatibility/CompatibilityProvider_1_9.java @@ -0,0 +1,29 @@ +package rip.reflex.util.protocol.compatibility; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import rip.reflex.util.protocol.packet.Packets; + +public class CompatibilityProvider_1_9 extends CompatibilityProvider_1_8 { + @Override + public boolean isItemInHand(Player p, Material itemType) { + return p.getInventory().getItemInMainHand().getType() == itemType || p.getInventory().getItemInOffHand().getType() == itemType; + } + + @Override + public boolean isBlockInHand(Player p) { + Material mainItem = p.getInventory().getItemInMainHand().getType(); + if (mainItem != Material.AIR && mainItem.isBlock()) { + return true; + } else { + Material offItem = p.getInventory().getItemInOffHand().getType(); + return offItem != Material.AIR && offItem.isBlock(); + } + } + + @Override + public boolean isBlockPlacePacket(PacketContainer packet) { + return packet.getType().equals(Packets.IN_USEITEM); + } +} diff --git a/src/main/java/rip/reflex/util/protocol/comptypes/CompPlayerAction.java b/src/main/java/rip/reflex/util/protocol/comptypes/CompPlayerAction.java new file mode 100644 index 0000000..fa60f77 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/comptypes/CompPlayerAction.java @@ -0,0 +1,45 @@ +package rip.reflex.util.protocol.comptypes; + +import com.comphenix.protocol.events.PacketContainer; +import java.util.Arrays; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.packet.Packets; + +public enum CompPlayerAction { + START_SNEAKING((byte)1), + STOP_SNEAKING((byte)2), + STOP_SLEEPING((byte)3), + START_SPRINTING((byte)4), + STOP_SPRINTING((byte)5), + START_RIDING_JUMP((byte)6), + STOP_RIDING_JUMP((byte)-1), + OPEN_INVENTORY((byte)-1), + START_FALL_FLYING((byte)-1); + + private final byte id1_7; + + public static CompPlayerAction byPacket(PacketContainer packet) { + if (VersionUtils.getServerVersion().getId() < MCVersion.V1_8_X.getId()) { + byte id = Packets.readByte(packet, 0); + return Arrays.stream(values()) + .filter(cpa -> cpa.getId1_7() == id) + .findFirst() + .orElseThrow(() -> new RuntimeException("Protocol incompatibility (" + id + ")")); + } else { + return byPacket1_8(packet); + } + } + + private static CompPlayerAction byPacket1_8(PacketContainer packet) { + return valueOf(Packets.readPlayerActionSafely(packet, 0).name()); + } + + private CompPlayerAction(byte id1_7) { + this.id1_7 = id1_7; + } + + public byte getId1_7() { + return this.id1_7; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/mcaccess/BoundingBox.java b/src/main/java/rip/reflex/util/protocol/mcaccess/BoundingBox.java new file mode 100644 index 0000000..fb42f71 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/mcaccess/BoundingBox.java @@ -0,0 +1,242 @@ +package rip.reflex.util.protocol.mcaccess; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; + +public class BoundingBox { + private double minX; + private double minY; + private double minZ; + private double maxX; + private double maxY; + private double maxZ; + + public BoundingBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + this.minX = Math.min(minX, maxX); + this.minY = Math.min(minY, maxY); + this.minZ = Math.min(minZ, maxZ); + this.maxX = Math.max(minX, maxX); + this.maxY = Math.max(minY, maxY); + this.maxZ = Math.max(minZ, maxZ); + } + + public BoundingBox(Vector a, Vector b) { + this(a.getX(), a.getY(), a.getZ(), b.getX(), b.getY(), b.getZ()); + } + + public static BoundingBox of(Entity e) { + MethodProfiler mp = new MethodProfiler("CI-48217482749"); + Objects.requireNonNull(e, "84193481942"); + Object handle = MCAccess.invokeSneaky(ReflectionCache.getEntityHandle, e); + Object bb = MCAccess.invokeSneaky(ReflectionCache.getBBMethod, handle); + BoundingBox boundingBox = new BoundingBox( + (Double)MCAccess.getFromField(ReflectionCache.boxField_a, bb), + (Double)MCAccess.getFromField(ReflectionCache.boxField_b, bb), + (Double)MCAccess.getFromField(ReflectionCache.boxField_c, bb), + (Double)MCAccess.getFromField(ReflectionCache.boxField_d, bb), + (Double)MCAccess.getFromField(ReflectionCache.boxField_e, bb), + (Double)MCAccess.getFromField(ReflectionCache.boxField_f, bb) + ); + mp.addToTimings(); + return boundingBox; + } + + public static BoundingBox of(Block b) { + Object handle = MCAccess.invokeSneaky(ReflectionCache.getNMSBlock, b); + return new BoundingBox( + (double)b.getX() + MCAccess.getFromField(ReflectionCache.blockMinX, handle, double.class), + (double)b.getY() + MCAccess.getFromField(ReflectionCache.blockMinY, handle, double.class), + (double)b.getZ() + MCAccess.getFromField(ReflectionCache.blockMinZ, handle, double.class), + (double)b.getX() + MCAccess.getFromField(ReflectionCache.blockMaxX, handle, double.class), + (double)b.getY() + MCAccess.getFromField(ReflectionCache.blockMaxY, handle, double.class), + (double)b.getZ() + MCAccess.getFromField(ReflectionCache.blockMaxZ, handle, double.class) + ); + } + + public static BoundingBox of(Object nmsBox) { + return new BoundingBox( + MCAccess.getFromField(ReflectionCache.boxField_a, nmsBox, double.class), + MCAccess.getFromField(ReflectionCache.boxField_b, nmsBox, double.class), + MCAccess.getFromField(ReflectionCache.boxField_c, nmsBox, double.class), + MCAccess.getFromField(ReflectionCache.boxField_d, nmsBox, double.class), + MCAccess.getFromField(ReflectionCache.boxField_e, nmsBox, double.class), + MCAccess.getFromField(ReflectionCache.boxField_f, nmsBox, double.class) + ); + } + + public static List getCubes(BoundingBox box, Entity entity) { + Object nmsWorld = MCAccess.invokeSneaky(ReflectionCache.getWorldHandle, entity.getWorld()); + Object nmsBox = MCAccess.newInstance( + ReflectionCache.boxConstructor, box.getMinX(), box.getMinY(), box.getMinZ(), box.getMaxX(), box.getMinY(), box.getMaxZ() + ); + List boxes = (List)MCAccess.invokeSneaky( + ReflectionCache.getCubesMethod, + ReflectionCache.nmsWorldClass.cast(nmsWorld), + ReflectionCache.entityClass.cast(MCAccess.invokeSneaky(ReflectionCache.getEntityHandle, entity)), + ReflectionCache.boundingBoxClass.cast(nmsBox) + ); + List wrappedBoxes = new ArrayList<>(); + boxes.forEach(o -> wrappedBoxes.add(of(o))); + return wrappedBoxes; + } + + public Location min(World world) { + return new Location(world, this.minX, this.minY, this.minZ).clone(); + } + + public Location mid(World world) { + double[] mid = (double[])this.midpoint().clone(); + return new Location(world, mid[0], mid[1], mid[2]).clone(); + } + + public Location max(World world) { + return new Location(world, this.maxX, this.maxY, this.maxZ).clone(); + } + + public BoundingBox expand(double m) { + this.minX -= m; + this.maxX += m; + this.minY -= m; + this.maxY += m; + this.minZ -= m; + this.maxZ += m; + return this; + } + + public BoundingBox expand(double mx, double my, double mz) { + this.minX -= mx; + this.maxX += mx; + this.minY -= my; + this.maxY += my; + this.minZ -= mz; + this.maxZ += mz; + return this; + } + + public BoundingBox expandUp(double m) { + this.maxY += m; + return this; + } + + public BoundingBox expandDown(double m) { + this.minY -= m; + return this; + } + + public boolean isWithinBoundingBox(int x, int y, int z) { + return (double)x >= this.minX + && (double)x <= this.maxX + && (double)y >= this.minY + && (double)y <= this.maxY + && (double)z >= this.minZ + && (double)z <= this.maxZ; + } + + public boolean isWithinBoundingBox(double x, double y, double z) { + return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY && z >= this.minZ && z <= this.maxZ; + } + + public boolean intersects(Location l, double precision) { + return this.intersects(l.getX(), l.getZ(), precision); + } + + public boolean intersects(double x, double z, double precision) { + double dx = Maths.minabs(x - this.minX, x - this.maxX); + double dz = Maths.minabs(z - this.minZ, z - this.maxZ); + return dx <= precision || dz <= precision; + } + + public double distance(Location l) { + double[] mid = this.midpoint(); + return l.distance(new Location(l.getWorld(), mid[0], mid[1], mid[2])); + } + + public boolean isWithinBoundingBox(Vector v) { + return this.isWithinBoundingBox(v.getX(), v.getY(), v.getZ()); + } + + public boolean isWithinBoundingBox(Location l) { + return this.isWithinBoundingBox(l.getX(), l.getY(), l.getZ()); + } + + public Block blockAtMid(World world) { + double[] mid = this.midpoint(); + return world.getBlockAt(Maths.floor(mid[0]), Maths.floor(mid[1]), Maths.floor(mid[2])); + } + + public double calculateYOffset(BoundingBox box, double y) { + if (box.maxX <= this.minX || box.minX >= this.maxX || box.maxZ <= this.minZ || box.minZ >= this.maxZ) { + return y; + } else if (y > 0.0 && box.maxY <= this.minY) { + return this.minY - box.maxY < y ? this.minY - box.maxY : y; + } else if (y < 0.0 && box.minY >= this.maxY) { + return this.maxY - box.minY > y ? this.maxY - box.minY : y; + } else { + return y; + } + } + + public BoundingBox addCoords(double x, double y, double z) { + return new BoundingBox( + this.minX + (x < 0.0 ? x : 0.0), + this.minY + (y < 0.0 ? y : 0.0), + this.minZ + (z < 0.0 ? z : 0.0), + this.maxX + (x > 0.0 ? x : 0.0), + this.maxY + (y > 0.0 ? y : 0.0), + this.maxZ + (z > 0.0 ? z : 0.0) + ); + } + + public double[] midpoint() { + return new double[]{(this.minX + this.maxX) / 2.0, (this.minY + this.maxY) / 2.0, (this.minZ + this.maxZ) / 2.0}; + } + + public double getMinX() { + return this.minX; + } + + public double getMinY() { + return this.minY; + } + + public double getMinZ() { + return this.minZ; + } + + public double getMaxX() { + return this.maxX; + } + + public double getMaxY() { + return this.maxY; + } + + public double getMaxZ() { + return this.maxZ; + } + + @Override + public String toString() { + return "BoundingBox(minX=" + + this.getMinX() + + ", minY=" + + this.getMinY() + + ", minZ=" + + this.getMinZ() + + ", maxX=" + + this.getMaxX() + + ", maxY=" + + this.getMaxY() + + ", maxZ=" + + this.getMaxZ() + + ")"; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/mcaccess/Handle.java b/src/main/java/rip/reflex/util/protocol/mcaccess/Handle.java new file mode 100644 index 0000000..54bef70 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/mcaccess/Handle.java @@ -0,0 +1,67 @@ +package rip.reflex.util.protocol.mcaccess; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class Handle { + private final T bukkitObject; + private final Object handle; + private final Class handleClass; + + public Handle(T bukkitObject, Object handle, Class c) { + this.bukkitObject = bukkitObject; + this.handle = handle; + this.handleClass = c; + } + + public Handle(T bukkitObject, Object handle) { + this(bukkitObject, handle, handle.getClass()); + } + + public static Handle fromItemStack(ItemStack item) { + try { + Method asNMSCopyMethod = MCAccess.getCraftClass("inventory.CraftItemStack").getDeclaredMethod("asNMSCopy", ItemStack.class); + Object nmsItem = asNMSCopyMethod.invoke(null, item); + return new Handle<>(item, nmsItem); + } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException ex) { + return handleError(ex); + } + } + + public static Handle fromEntity(Entity e) { + try { + return new Handle<>(e, e.getClass().getDeclaredMethod("getHandle").invoke(e)); + } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException err) { + return handleError(err); + } + } + + public static Handle fromEntity(Player e) { + try { + return new Handle<>(e, e.getClass().getDeclaredMethod("getHandle").invoke(e)); + } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException cause) { + return handleError(cause); + } + } + + private static T handleError(Exception e) { + System.err.println("ERROR IN REFLECTION -> Handle"); + e.printStackTrace(); + return null; + } + + public T getBukkitObject() { + return this.bukkitObject; + } + + public Object getHandle() { + return this.handle; + } + + public Class getHandleClass() { + return this.handleClass; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/mcaccess/MCAccess.java b/src/main/java/rip/reflex/util/protocol/mcaccess/MCAccess.java new file mode 100644 index 0000000..4273a2f --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/mcaccess/MCAccess.java @@ -0,0 +1,375 @@ +package rip.reflex.util.protocol.mcaccess; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class MCAccess { + public static final String VERSION = Bukkit.getServer().getClass().getName().split("\\.")[3]; + private static final Map, Class> CORRESPONDING_TYPES; + private static final ConcurrentHashMap> cache = new ConcurrentHashMap<>(); + + public static Object constructWithDef(String s) { + try { + return newInstance(getConstructor(Class.forName(s))); + } catch (ClassNotFoundException ex) { + return sneakyThrow(ex); + } + } + + public static BoundingBox getEntityBoundingBox(Entity e) { + return BoundingBox.of(e).expand(0.885, 0.725, 0.885).expandDown(1.35); + } + + public static Class getNMSClass(String NMSClassName) { + Class c = cache.get(NMSClassName); + if (c == null) { + try { + c = Class.forName("net.minecraft.server." + VERSION + "." + NMSClassName); + } catch (ClassNotFoundException err) { + return (Class)sneakyThrow(err); + } + } + + Validate.notNull(c, "NMS Class cannot be null"); + cache.put(NMSClassName, c); + return c; + } + + public static Class getClass(String name) { + Class c = cache.get(name); + if (c == null) { + try { + c = Class.forName(name); + cache.put(name, c); + } catch (ClassNotFoundException ignored) { + throw new RuntimeException("Reflex // Reflection error: no such class \"" + name + "\""); + } + } + + return c; + } + + public static Class getClassSafely(String name) { + Class c = cache.get(name); + if (c == null) { + try { + c = Class.forName(name); + cache.put(name, c); + } catch (ClassNotFoundException ignoredEx) { + } + } + + return c; + } + + public static Class getCraftClass(String OBSClassName) { + try { + return Class.forName("org.bukkit.craftbukkit." + VERSION + "." + OBSClassName); + } catch (Exception ex) { + return (Class)handleError(ex); + } + } + + public static boolean isPacket(Object o, String packetName) { + Validate.notNull(getNMSClass(packetName), "NMS class cannot be null! (" + packetName + ", ver=" + VERSION + ")"); + return o != null && getNMSClass(packetName).isInstance(o); + } + + public static void setField(Object o, String name, Object value) { + setField(o, name, value, o.getClass()); + } + + public static void setField(final Object o, final String name, final Object value, final Class clazz) { + new MCAccess.NMSTry() { + @Override + public Object tryit() throws Exception { + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + field.set(o, value); + return null; + } + }; + } + + public static Constructor getConstructor(Class targetClass, Class... paraTypes) { + Constructor c = (Constructor)Arrays.stream(targetClass.getDeclaredConstructors()) + .filter(constructor -> Arrays.equals((Object[])constructor.getParameterTypes(), (Object[])paraTypes)) + .findFirst() + .orElse(null); + if (c != null) { + c.setAccessible(true); + } + + return c; + } + + public static T newInstance(Constructor constructor, Object... types) { + constructor.setAccessible(true); + + try { + return constructor.newInstance(types); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException ex) { + return (T)handleError(ex); + } + } + + public static Object getTag(ItemStack item) { + try { + Handle h = Handle.fromItemStack(item); + Object nmsItem = h.getHandle(); + Method getTagMethod = nmsItem.getClass().getDeclaredMethod("getTag"); + return getTagMethod.invoke(nmsItem); + } catch (Exception e) { + return handleError(e); + } + } + + public static ItemStack toCraftStack(Object nmsItem) { + try { + Class nmsItemStackClass = getNMSClass("ItemStack"); + Class craftItemStackClass = getCraftClass("inventory.CraftItemStack"); + Constructor constructor = craftItemStackClass.getDeclaredConstructor(nmsItemStackClass); + constructor.setAccessible(true); + Object craftItem = constructor.newInstance(nmsItemStackClass.cast(nmsItem)); + return (ItemStack)craftItem; + } catch (Exception ex) { + return (ItemStack)handleError(ex); + } + } + + public static Object getTag(Object nmsItem) { + try { + Method getTagMethod = nmsItem.getClass().getDeclaredMethod("getTag"); + return getTagMethod.invoke(nmsItem); + } catch (Exception e) { + return handleError(e); + } + } + + public static Field getField(Class clazz, String name) { + try { + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + return field; + } catch (Exception err) { + err.printStackTrace(); + return null; + } + } + + public static Field getFieldWithFallback(Class clazz, String primaryName, String fallbackName) { + try { + Field field = clazz.getDeclaredField(primaryName); + field.setAccessible(true); + return field; + } catch (Exception ignored) { + return getField(clazz, fallbackName); + } + } + + public static Object getField(Object o, String name, Class clazz) { + try { + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + return field.get(o); + } catch (NoSuchFieldException | IllegalAccessException ex) { + throw new RuntimeException("Cannot get field", ex); + } + } + + public static Object getField(Object o, String name) { + return getField(o, name, o.getClass()); + } + + public static Object getFromField(Field field, Object instance) { + try { + if (!field.isAccessible()) { + field.setAccessible(true); + } + + return field.get(instance); + } catch (IllegalAccessException e) { + return sneakyThrow(e); + } + } + + public static T getFromField(Field f, Object instance, Class cast) { + return (T)getFromField(f, instance); + } + + public static void sendPluginMessage(Player player, String channel, byte[] message) { + if (message == null) { + throw new NullPointerException("Cannot send null plugin message"); + } else if (message.length == 0) { + throw new IllegalArgumentException("Cannot send empty plugin message"); + } else { + try { + Object byteBuf = ReflectionCache.wrappedBufferMethod.invoke(null, message); + Object packetDataSerializer = ReflectionCache.packetDataSerializerConstructor.newInstance(byteBuf); + Object packet = ReflectionCache.Packets.PacketPlayOutCustomPayload_Constructor.newInstance(channel, packetDataSerializer); + Object nmsPlayer = ReflectionCache.getPlayerHandle.invoke(player); + Object playerConnection = ReflectionCache.playerConnectionField.get(nmsPlayer); + ReflectionCache.sendPacketMethod.invoke(playerConnection, packet); + } catch (Exception ex) { + throw new RuntimeException("Error sending plugin message through \"" + channel + "\" (" + message.length + " bytes)", ex); + } + } + } + + public static void secureSetFinalStatic(Field field, Object newValue) throws Exception { + boolean preAccessible = field.isAccessible(); + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + boolean preModsAccessible = modifiersField.isAccessible(); + modifiersField.setAccessible(true); + int preMods = modifiersField.getInt(field); + modifiersField.setInt(field, field.getModifiers() & -17); + field.set(null, newValue); + modifiersField.setInt(field, preMods); + modifiersField.setAccessible(preModsAccessible); + field.setAccessible(preAccessible); + } + + private static Object handleError(Exception e) { + System.err.println("REFLEX // REFLECTION ERROR: " + e.toString()); + e.printStackTrace(); + return null; + } + + public static Object invokeSneaky(Method method, Object instance, Object... args) { + try { + return method.invoke(instance, args); + } catch (InvocationTargetException | IllegalAccessException ex) { + return sneakyThrow(ex); + } + } + + public static Object sneakyThrow(Throwable t) { + sneakyThrow0(t); + return null; + } + + public static void sneakyThrow0(Throwable t) { + throw new RuntimeException("SneakyThrow -> NMSReflection", t); + } + + public static Object getHandle(Object obj) { + try { + return getMethod("getHandle", obj.getClass()).invoke(obj); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static Method getMethod(String name, Class clazz, Class... paramTypes) { + Class[] t = toPrimitiveTypeArray(paramTypes); + + for (Method m : clazz.getDeclaredMethods()) { + if (m.getName().equals(name)) { + if (paramTypes == null || paramTypes.length == 0) { + m.setAccessible(true); + return m; + } + + Class[] types = toPrimitiveTypeArray(m.getParameterTypes()); + if (equalsTypeArray(types, t)) { + m.setAccessible(true); + return m; + } + } + } + + return null; + } + + private static Class[] toPrimitiveTypeArray(Object[] objects) { + int a = objects != null ? objects.length : 0; + Class[] types = new Class[a]; + + for (int i = 0; i < a; i++) { + types[i] = getPrimitiveType(objects[i].getClass()); + } + + return types; + } + + private static Class[] toPrimitiveTypeArray(Class[] classes) { + int a = classes != null ? classes.length : 0; + Class[] types = new Class[a]; + + for (int i = 0; i < a; i++) { + types[i] = getPrimitiveType(classes[i]); + } + + return types; + } + + public static Object getMinecraftServer() { + Class craftServerClass = getCraftClass("CraftServer"); + Method getServerMethod = getMethod("getServer", craftServerClass); + return invokeSneaky(getServerMethod, Bukkit.getServer()); + } + + private static Class getPrimitiveType(Class clazz) { + return CORRESPONDING_TYPES.getOrDefault(clazz, clazz); + } + + private static boolean equalsTypeArray(Class[] a, Class[] o) { + if (a.length != o.length) { + return false; + } else { + for (int i = 0; i < a.length; i++) { + if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) { + return false; + } + } + + return true; + } + } + + public static int getTicks() { + return (Integer)getFromField(ReflectionCache.ticksField, ReflectionCache.mcServerInstance); + } + + static { + (CORRESPONDING_TYPES = new ConcurrentHashMap<>()).put(Byte.class, byte.class); + CORRESPONDING_TYPES.put(Short.class, short.class); + CORRESPONDING_TYPES.put(Integer.class, int.class); + CORRESPONDING_TYPES.put(Long.class, long.class); + CORRESPONDING_TYPES.put(Character.class, char.class); + CORRESPONDING_TYPES.put(Float.class, float.class); + CORRESPONDING_TYPES.put(Double.class, double.class); + CORRESPONDING_TYPES.put(Boolean.class, boolean.class); + } + + public abstract static class NMSTry implements AutoCloseable { + public abstract T tryit() throws Exception; + + public T doIt() { + try { + return this.tryit(); + } catch (Exception ex) { + System.out.println("ERROR IN REFLECTION!"); + ex.printStackTrace(); + return null; + } + } + + @Override + public void close() throws IOException { + } + } +} diff --git a/src/main/java/rip/reflex/util/protocol/mcaccess/ReflectionCache.java b/src/main/java/rip/reflex/util/protocol/mcaccess/ReflectionCache.java new file mode 100644 index 0000000..de5495f --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/mcaccess/ReflectionCache.java @@ -0,0 +1,60 @@ +package rip.reflex.util.protocol.mcaccess; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import org.bukkit.World; +import org.bukkit.entity.Player; + +public class ReflectionCache { + public static final ReflectionCache worldCache = new ReflectionCache<>(); + public static final ReflectionCache playerCache = new ReflectionCache<>(); + public static final Class craftTaskClass = MCAccess.getCraftClass("scheduler.CraftTask"); + public static final Class boundingBoxClass = MCAccess.getNMSClass("AxisAlignedBB"); + public static final Class entityClass = MCAccess.getNMSClass("Entity"); + public static final Class nmsWorldClass = MCAccess.getNMSClass("World"); + public static final Class craftWorldClass = MCAccess.getCraftClass("CraftWorld"); + public static final Class minecraftServerClass = MCAccess.getNMSClass("MinecraftServer"); + public static final Class nmsBlockClass = MCAccess.getNMSClass("Block"); + public static final Class craftEntityClass = MCAccess.getCraftClass("entity.CraftEntity"); + public static final Class craftPlayerClass = MCAccess.getCraftClass("entity.CraftPlayer"); + public static final Class nmsPlayerClass = MCAccess.getNMSClass("EntityPlayer"); + public static final Class playerConnectionClass = MCAccess.getNMSClass("PlayerConnection"); + public static final Class packetDataSerializerClass = MCAccess.getNMSClass("PacketDataSerializer"); + public static final Class byteBufClass = MCAccess.getClass("io.netty.buffer.ByteBuf"); + public static final Class unpooledClass = MCAccess.getClass("io.netty.buffer.Unpooled"); + public static final Field playerConnectionField = MCAccess.getField(nmsPlayerClass, "playerConnection"); + public static final Field boxField_a = MCAccess.getFieldWithFallback(boundingBoxClass, "a", "minX"); + public static final Field boxField_b = MCAccess.getFieldWithFallback(boundingBoxClass, "b", "minY"); + public static final Field boxField_c = MCAccess.getFieldWithFallback(boundingBoxClass, "c", "minZ"); + public static final Field boxField_d = MCAccess.getFieldWithFallback(boundingBoxClass, "d", "maxX"); + public static final Field boxField_e = MCAccess.getFieldWithFallback(boundingBoxClass, "e", "maxY"); + public static final Field boxField_f = MCAccess.getFieldWithFallback(boundingBoxClass, "f", "maxZ"); + public static final Field blockMinX = null; + public static final Field blockMinY = null; + public static final Field blockMinZ = null; + public static final Field blockMaxX = null; + public static final Field blockMaxY = null; + public static final Field blockMaxZ = null; + public static final Field ticksField = MCAccess.getField(minecraftServerClass, "ticks"); + public static final Method getBBMethod = MCAccess.getMethod("getBoundingBox", entityClass); + public static final Method getEntityHandle = MCAccess.getMethod("getHandle", craftEntityClass); + public static final Method getPlayerHandle = MCAccess.getMethod("getHandle", craftPlayerClass); + public static final Method getCubesMethod = MCAccess.getMethod("getCubes", nmsWorldClass, entityClass, boundingBoxClass); + public static final Method getWorldHandle = MCAccess.getMethod("getHandle", craftWorldClass); + public static final Method getNMSBlock = null; + public static final Method sendPacketMethod = MCAccess.getMethod("sendPacket", playerConnectionClass); + public static final Method wrappedBufferMethod = MCAccess.getMethod("wrappedBuffer", unpooledClass, byte[].class); + public static final Constructor boxConstructor = MCAccess.getConstructor( + boundingBoxClass, double.class, double.class, double.class, double.class, double.class, double.class + ); + public static final Constructor packetDataSerializerConstructor = MCAccess.getConstructor(packetDataSerializerClass, byteBufClass); + public static final Object mcServerInstance = MCAccess.getMinecraftServer(); + + public static class Packets { + public static final Class PacketPlayOutCustomPayload = MCAccess.getNMSClass("PacketPlayOutCustomPayload"); + public static final Constructor PacketPlayOutCustomPayload_Constructor = MCAccess.getConstructor( + PacketPlayOutCustomPayload, String.class, ReflectionCache.packetDataSerializerClass + ); + } +} diff --git a/src/main/java/rip/reflex/util/protocol/npc/Animations.java b/src/main/java/rip/reflex/util/protocol/npc/Animations.java new file mode 100644 index 0000000..f74b19e --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/npc/Animations.java @@ -0,0 +1,10 @@ +package rip.reflex.util.protocol.npc; + +public enum Animations { + SWING_ARM, + TAKE_DAMAGE, + LEAVE_BED, + EAT_FOOD, + CRITICAL_EFFECT, + MAGIC_CRITICAL_EFFECT; +} diff --git a/src/main/java/rip/reflex/util/protocol/npc/EntityUtils.java b/src/main/java/rip/reflex/util/protocol/npc/EntityUtils.java new file mode 100644 index 0000000..92e49c0 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/npc/EntityUtils.java @@ -0,0 +1,77 @@ +package rip.reflex.util.protocol.npc; + +import java.util.Random; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import rip.reflex.Reflex; + +public class EntityUtils { + private static Random random = new Random(System.currentTimeMillis()); + + public static int getFreeEntityID() { + if (Reflex.getReflex().getSetting("killaura.realistic_entityids", true)) { + World firstWorld = (World)Bukkit.getWorlds().get(0); + Entity fake = firstWorld.spawnEntity(new Location(firstWorld, 0.0, 0.0, 0.0), EntityType.BAT); + int id = fake.getEntityId(); + if (!fake.isDead() && Reflex.getReflex().getSetting("killaura.despawn_fakes", true)) { + fake.remove(); + } + + return id; + } else { + try { + return 10000000 + random.nextInt(10000000) + random.nextInt(500000); + } catch (OutOfMemoryError ignored) { + random = new Random(System.currentTimeMillis()); + return getFreeEntityID(); + } + } + } + + public static int getEntitySize(LivingEntity e) { + switch (e.getType()) { + case ENDERMITE: + case SPIDER: + case CAVE_SPIDER: + case BAT: + case RABBIT: + case SILVERFISH: + case SQUID: + case CHICKEN: + case WOLF: + case OCELOT: + return 0; + case PIG: + case COW: + case HORSE: + case GUARDIAN: + case SHEEP: + case MUSHROOM_COW: + return 1; + case VILLAGER: + case PLAYER: + case BLAZE: + case ZOMBIE: + case SKELETON: + case PIG_ZOMBIE: + case CREEPER: + case WITCH: + case SNOWMAN: + return 2; + case WITHER: + case ENDERMAN: + case ENDER_DRAGON: + case IRON_GOLEM: + case GIANT: + case SLIME: + case MAGMA_CUBE: + return 3; + default: + return 4; + } + } +} diff --git a/src/main/java/rip/reflex/util/protocol/npc/EquipSlot.java b/src/main/java/rip/reflex/util/protocol/npc/EquipSlot.java new file mode 100644 index 0000000..34a13fa --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/npc/EquipSlot.java @@ -0,0 +1,31 @@ +package rip.reflex.util.protocol.npc; + +import com.comphenix.protocol.wrappers.EnumWrappers.ItemSlot; + +public enum EquipSlot { + MAIN_HAND, + OFF_HAND, + BOOTS, + LEGGINGS, + CHESTPLATE, + HELMET; + + public ItemSlot toWrapped() { + switch (this) { + case MAIN_HAND: + return ItemSlot.MAINHAND; + case OFF_HAND: + return ItemSlot.OFFHAND; + case BOOTS: + return ItemSlot.FEET; + case LEGGINGS: + return ItemSlot.LEGS; + case CHESTPLATE: + return ItemSlot.CHEST; + case HELMET: + return ItemSlot.HEAD; + default: + return null; + } + } +} diff --git a/src/main/java/rip/reflex/util/protocol/npc/HitListener.java b/src/main/java/rip/reflex/util/protocol/npc/HitListener.java new file mode 100644 index 0000000..9bf402c --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/npc/HitListener.java @@ -0,0 +1,11 @@ +package rip.reflex.util.protocol.npc; + +import com.comphenix.protocol.events.PacketContainer; +import org.bukkit.entity.Player; + +public interface HitListener { + void onHit(Player player, int entityId); + + default void onHit(Player hitter, int entityId, PacketContainer packet) { + } +} diff --git a/src/main/java/rip/reflex/util/protocol/npc/HitPacketListener.java b/src/main/java/rip/reflex/util/protocol/npc/HitPacketListener.java new file mode 100644 index 0000000..fb3511a --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/npc/HitPacketListener.java @@ -0,0 +1,37 @@ +package rip.reflex.util.protocol.npc; + +import com.comphenix.protocol.PacketType.Play.Client; +import com.comphenix.protocol.events.PacketAdapter; +import com.comphenix.protocol.events.PacketEvent; +import rip.reflex.Reflex; +import rip.reflex.util.protocol.packet.Packets; + +public class HitPacketListener { + public HitPacketListener() { + NPCCommons.getProtocolManager().addPacketListener(new PacketAdapter(Reflex.getReflex(), Client.USE_ENTITY) { + public void onPacketReceiving(PacketEvent event) { + if (event != null) { + try { + if (!Packets.isAttackPacket(event.getPacket())) { + return; + } + + int id = Packets.readInteger(event.getPacket(), 0); + + try { + for (HitListener hitListener : NPCCommons.getListeners()) { + hitListener.onHit(event.getPlayer(), id); + } + + for (HitListener hitListener : NPCCommons.getListeners()) { + hitListener.onHit(event.getPlayer(), id, event.getPacket()); + } + } catch (Exception ignored) { + } + } catch (Exception ignoredEx) { + } + } + } + }); + } +} diff --git a/src/main/java/rip/reflex/util/protocol/npc/ImpWrappedDataWatcher.java b/src/main/java/rip/reflex/util/protocol/npc/ImpWrappedDataWatcher.java new file mode 100644 index 0000000..35a525e --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/npc/ImpWrappedDataWatcher.java @@ -0,0 +1,44 @@ +package rip.reflex.util.protocol.npc; + +import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import com.comphenix.protocol.wrappers.WrappedDataWatcher.Registry; +import java.util.Map; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; + +public class ImpWrappedDataWatcher extends WrappedDataWatcher { + private final MapCreator creator = new MapCreator<>(Integer.class, Object.class); + + public void setEntireMap(Object... objects) { + this.setAll(this.creator.wrapMap(objects)); + } + + public ImpWrappedDataWatcher setEntire(Object... objects) { + for (int i = 0; i < objects.length; i++) { + this.set(i, objects[i]); + } + + return this; + } + + public void setAll(Map map) { + map.forEach(this::set); + } + + public ImpWrappedDataWatcher set(Integer index, Object value) { + try { + if (this.hasIndex(index)) { + this.getWatchableObject(index).setValue(value); + } else if (VersionUtils.getServerVersion().getId() >= MCVersion.V1_9_X.getId()) { + this.setObject(index, Registry.get(value.getClass()), value); + } else { + this.setObject(index, value); + } + } catch (Exception ex) { + ex.printStackTrace(); + System.out.println("Index: " + index + ", Object: " + value + ", Type: " + value.getClass().getSimpleName()); + } + + return this; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/npc/MapCreator.java b/src/main/java/rip/reflex/util/protocol/npc/MapCreator.java new file mode 100644 index 0000000..411abdd --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/npc/MapCreator.java @@ -0,0 +1,39 @@ +package rip.reflex.util.protocol.npc; + +import java.util.HashMap; +import java.util.Map; + +public class MapCreator { + private final Class keyClass; + private final Class valueClass; + + public MapCreator(Class keyClass, Class valueClass) { + this.keyClass = keyClass; + this.valueClass = valueClass; + } + + public Map wrapMap(Object... objects) { + if (objects.length % 2 != 0) { + throw new IllegalArgumentException("Length must be a multiple of 2!"); + } else { + Map map = new HashMap<>(); + int i = 0; + + while (i < objects.length) { + Object key = objects[i++]; + Object value = objects[i++]; + if (!this.is(this.keyClass, key) || !this.is(this.valueClass, value)) { + throw new IllegalArgumentException("Illegal types!"); + } + + map.put((K)key, (V)value); + } + + return map; + } + } + + private boolean is(Class c, Object o) { + return c.isInstance(o); + } +} diff --git a/src/main/java/rip/reflex/util/protocol/npc/NPC.java b/src/main/java/rip/reflex/util/protocol/npc/NPC.java new file mode 100644 index 0000000..44f86c4 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/npc/NPC.java @@ -0,0 +1,951 @@ +package rip.reflex.util.protocol.npc; + +import com.comphenix.protocol.PacketType.Play.Server; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.PlayerInfoData; +import com.comphenix.protocol.wrappers.WrappedChatComponent; +import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import com.comphenix.protocol.wrappers.WrappedGameProfile; +import com.comphenix.protocol.wrappers.EnumWrappers.NativeGameMode; +import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import rip.reflex.Reflex; +import rip.reflex.util.math.Maths; +import rip.reflex.util.performance.MethodProfiler; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.NotCompatibleException; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.mcaccess.MCAccess; +import rip.reflex.util.protocol.packet.Packets; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; +import rip.reflex.util.time.Timer; + +public class NPC { + private static Boolean syncNpcs = null; + private Timer spawnTracker = null; + private final Player player; + public boolean randomIDeachSpawn = false; + public String username; + public UUID uuid; + public boolean sprinting; + public boolean sneaking; + public boolean using; + public boolean burning; + public boolean flying; + public boolean glowing; + public boolean silent; + public boolean showInTab; + public boolean hidden; + public boolean onGround = true; + public boolean spawned; + public boolean inTab; + public boolean autoAnimations = true; + public boolean autoRespawn = true; + WrappedDataWatcher dataWatcher; + private Location location; + private float headYaw; + private float health = 20.0F; + private int moveCounter; + private int entityId = -1; + private long lastMove; + private Location oldLocation; + private boolean hideNametag; + + public NPC(Player player) throws NotCompatibleException { + this.player = player; + this.entityId = EntityUtils.getFreeEntityID(); + if (NPCCommons.getMCVersion() == MCVersion.WTF) { + throw new NotCompatibleException(); + } + } + + public float getHealth() { + return this.health; + } + + public void setHealth(float health) throws InvocationTargetException, NotCompatibleException { + MethodProfiler mp = new MethodProfiler("VE-21839101"); + boolean changed = this.health != health; + boolean isLower = health < this.health; + boolean rip = health <= 0.0F && this.health > 0.0F; + this.health = health; + if (changed) { + if (VersionUtils.getServerVersion().getId() >= MCVersion.V1_10_X.getId()) { + this.dataWatcher.getWatchableObject(7).setValue(health); + } else { + this.dataWatcher.setObject(6, health); + } + + if (isLower && this.autoAnimations) { + this.sendAnimation(Animations.TAKE_DAMAGE); + } + + this.sendMetaUpdate(); + if (rip) { + this.unequip(); + this.despawn(); + if (this.autoRespawn) { + this.spawn(); + } + } + } + + mp.addToTimings(); + } + + private void unequip() throws InvocationTargetException { + MethodProfiler mp = new MethodProfiler("VE-1982303"); + + for (EquipSlot slot : EquipSlot.values()) { + if (slot != EquipSlot.OFF_HAND || this.is19()) { + try { + this.setEquipmentInSlot(slot, null); + } catch (NotCompatibleException ignored) { + } + } + } + + mp.addToTimings(); + } + + public void setEquipmentInSlot(EquipSlot slot, ItemStack stack) throws NotCompatibleException, InvocationTargetException { + MethodProfiler mp = new MethodProfiler("VE-750124014"); + if (slot == EquipSlot.OFF_HAND && !this.is19()) { + throw new NotCompatibleException(); + } else { + Objects.requireNonNull(slot, "Equipment slot cannot be null!"); + if (stack == null) { + stack = new ItemStack(Material.AIR); + } + + if (slot == EquipSlot.OFF_HAND && VersionUtils.getServerVersion().getId() < MCVersion.V1_9_X.getId()) { + throw new NotCompatibleException(); + } else if (slot != EquipSlot.MAIN_HAND || !this.is17()) { + PacketContainer packet = new PacketContainer(Server.ENTITY_EQUIPMENT); + packet.getIntegers().write(0, this.entityId); + if (this.is19()) { + packet.getItemSlots().write(0, slot.toWrapped()); + } else { + packet.getIntegers().write(1, slot.ordinal() - (!this.is19() && slot != EquipSlot.MAIN_HAND ? 1 : 0)); + } + + if (VersionUtils.getServerVersion().getId() >= MCVersion.V1_11_X.getId() && stack.getType() == Material.AIR) { + MCAccess.setField(packet.getHandle(), "c", null); + } else { + packet.getItemModifier().write(0, stack); + } + + this.sendPacket(this.player, packet); + mp.addToTimings(); + } + } + } + + public long getSpawnedTicks() { + if (this.spawnTracker == null) { + return 1L; + } else { + if (this.spawnTracker.getTimeTicked() >= 500L) { + this.spawnTracker.reset(); + } + + return Maths.notZero(this.spawnTracker.getTimeTicked(), 1L); + } + } + + public void swingArm() throws InvocationTargetException { + this.sendAnimation(Animations.SWING_ARM); + } + + private void sendAnimation(Animations animations) throws InvocationTargetException { + PacketContainer animation = new PacketContainer(Server.ANIMATION); + animation.getIntegers().write(0, this.entityId); + animation.getIntegers().write(1, animations.ordinal()); + this.sendPacket(this.player, animation); + } + + public Location getLocation() { + return this.location; + } + + public void setLocation(Location location) throws NotCompatibleException, InvocationTargetException { + MethodProfiler mp = new MethodProfiler("VE-89472183791"); + this.oldLocation = this.location; + this.lastMove = System.currentTimeMillis(); + if (this.location == null) { + this.location = location; + this.sendPosTP(); + } else { + float dist = (float)Maths.distance(this.location, location); + Location oldLoc = this.location; + boolean anglesChanged = this.location.getYaw() != location.getYaw() || this.location.getPitch() != location.getPitch(); + this.location = location; + if (dist > this.getMaxRelMoveRange()) { + this.sendPosTP(); + } else if (dist == 0.0F && anglesChanged) { + this.sendAngleUpdate(); + } else if (dist != 0.0F && !anglesChanged) { + this.sendMoveUpdate(oldLoc); + } else if (dist != 0.0F && anglesChanged) { + this.sendMoveAngleUpdate(oldLoc); + } + + if (anglesChanged) { + this.setHeadYaw(location.getYaw()); + } + + this.moveCounter++; + if (this.moveCounter > 100) { + this.sendPosTP(); + this.moveCounter = 0; + } + + mp.addToTimings(); + } + } + + public Location pingBasedLocation(int ping) { + return System.currentTimeMillis() > this.lastMove + (long)(ping * 1000) ? this.location : this.oldLocation; + } + + private void sendMoveAngleUpdate(Location prev) throws NotCompatibleException, InvocationTargetException { + MethodProfiler mp = new MethodProfiler("VE-279319889"); + PacketContainer tp = new PacketContainer(Server.ENTITY_MOVE_LOOK); + tp.getIntegers().write(0, this.entityId); + switch (NPCCommons.getMCVersion()) { + case V1_7_X: + tp.getBytes().write(0, (byte)((int)((this.location.getX() * 32.0 - prev.getX() * 32.0) * 1.0))); + tp.getBytes().write(1, (byte)((int)((this.location.getY() * 32.0 - prev.getY() * 32.0) * 1.0))); + tp.getBytes().write(2, (byte)((int)((this.location.getZ() * 32.0 - prev.getZ() * 32.0) * 1.0))); + break; + case V1_8_X: + tp.getBytes().write(0, (byte)((int)((this.location.getX() * 32.0 - prev.getX() * 32.0) * 1.0))); + tp.getBytes().write(1, (byte)((int)((this.location.getY() * 32.0 - prev.getY() * 32.0) * 1.0))); + tp.getBytes().write(2, (byte)((int)((this.location.getZ() * 32.0 - prev.getZ() * 32.0) * 1.0))); + break; + case V1_9_X: + case V1_10_X: + case V1_11_X: + case V1_12_X: + case V1_13_X: + tp.getIntegers().write(1, (int)((this.location.getX() * 32.0 - prev.getX() * 32.0) * 128.0)); + tp.getIntegers().write(2, (int)((this.location.getY() * 32.0 - prev.getY() * 32.0) * 128.0)); + tp.getIntegers().write(3, (int)((this.location.getZ() * 32.0 - prev.getZ() * 32.0) * 128.0)); + break; + default: + throw new NotCompatibleException(); + } + + tp.getBooleans().write(0, this.onGround); + tp.getBytes().write(NPCCommons.getMCVersion().getId() >= MCVersion.V1_9_X.getId() ? 0 : 3, (byte)Maths.compressAngle(this.location.getYaw())); + tp.getBytes().write(NPCCommons.getMCVersion().getId() >= MCVersion.V1_9_X.getId() ? 1 : 4, (byte)Maths.compressAngle(this.location.getPitch())); + this.sendPacket(this.player, tp); + mp.addToTimings(); + } + + private void sendMoveUpdate(Location prev) throws NotCompatibleException, InvocationTargetException { + if (this.spawned) { + MethodProfiler mp = new MethodProfiler("VE-68974921"); + PacketContainer tp = new PacketContainer(Server.REL_ENTITY_MOVE); + tp.getIntegers().write(0, this.entityId); + switch (NPCCommons.getMCVersion()) { + case V1_7_X: + tp.getBytes().write(0, (byte)((int)((this.location.getX() * 32.0 - prev.getX() * 32.0) * 1.0))); + tp.getBytes().write(1, (byte)((int)((this.location.getY() * 32.0 - prev.getY() * 32.0) * 1.0))); + tp.getBytes().write(2, (byte)((int)((this.location.getZ() * 32.0 - prev.getZ() * 32.0) * 1.0))); + break; + case V1_8_X: + tp.getBytes().write(0, (byte)((int)((this.location.getX() * 32.0 - prev.getX() * 32.0) * 1.0))); + tp.getBytes().write(1, (byte)((int)((this.location.getY() * 32.0 - prev.getY() * 32.0) * 1.0))); + tp.getBytes().write(2, (byte)((int)((this.location.getZ() * 32.0 - prev.getZ() * 32.0) * 1.0))); + break; + case V1_9_X: + tp.getIntegers().write(1, (int)((this.location.getX() * 32.0 - prev.getX() * 32.0) * 128.0)); + tp.getIntegers().write(2, (int)((this.location.getY() * 32.0 - prev.getY() * 32.0) * 128.0)); + tp.getIntegers().write(3, (int)((this.location.getZ() * 32.0 - prev.getZ() * 32.0) * 128.0)); + break; + case V1_10_X: + tp.getIntegers().write(1, (int)((this.location.getX() * 32.0 - prev.getX() * 32.0) * 128.0)); + tp.getIntegers().write(2, (int)((this.location.getY() * 32.0 - prev.getY() * 32.0) * 128.0)); + tp.getIntegers().write(3, (int)((this.location.getZ() * 32.0 - prev.getZ() * 32.0) * 128.0)); + case V1_11_X: + case V1_12_X: + case V1_13_X: + tp.getIntegers().write(1, (int)((this.location.getX() * 32.0 - prev.getX() * 32.0) * 128.0)); + tp.getIntegers().write(2, (int)((this.location.getY() * 32.0 - prev.getY() * 32.0) * 128.0)); + tp.getIntegers().write(3, (int)((this.location.getZ() * 32.0 - prev.getZ() * 32.0) * 128.0)); + break; + default: + throw new NotCompatibleException(); + } + + tp.getBooleans().write(0, this.onGround); + this.sendPacket(this.player, tp); + mp.addToTimings(); + } + } + + private void sendAngleUpdate() throws InvocationTargetException { + if (this.spawned) { + MethodProfiler mp = new MethodProfiler("VE-9213791"); + PacketContainer tp = new PacketContainer(Server.ENTITY_LOOK); + tp.getIntegers().write(0, this.entityId); + tp.getBytes().write(0, (byte)Maths.compressAngle(this.location.getYaw())); + tp.getBytes().write(1, (byte)Maths.compressAngle(this.location.getPitch())); + tp.getBooleans().write(0, this.onGround); + this.sendPacket(this.player, tp); + mp.addToTimings(); + } + } + + private void sendPosTP() throws NotCompatibleException, InvocationTargetException { + if (this.spawned) { + MethodProfiler mp = new MethodProfiler("VE-598271389"); + PacketContainer tp = new PacketContainer(Server.ENTITY_TELEPORT); + tp.getIntegers().write(0, this.entityId); + switch (NPCCommons.getMCVersion()) { + case V1_7_X: + tp.getIntegers().write(1, (int)(this.location.getX() * 32.0)); + tp.getIntegers().write(2, (int)(this.location.getY() * 32.0)); + tp.getIntegers().write(3, (int)(this.location.getZ() * 32.0)); + break; + case V1_8_X: + tp.getIntegers().write(1, (int)(this.location.getX() * 32.0)); + tp.getIntegers().write(2, (int)(this.location.getY() * 32.0)); + tp.getIntegers().write(3, (int)(this.location.getZ() * 32.0)); + break; + case V1_9_X: + tp.getDoubles().write(0, this.location.getX()); + tp.getDoubles().write(1, this.location.getY()); + tp.getDoubles().write(2, this.location.getZ()); + break; + case V1_10_X: + tp.getDoubles().write(0, this.location.getX()); + tp.getDoubles().write(1, this.location.getY()); + tp.getDoubles().write(2, this.location.getZ()); + case V1_11_X: + case V1_12_X: + case V1_13_X: + tp.getDoubles().write(0, this.location.getX()); + tp.getDoubles().write(1, this.location.getY()); + tp.getDoubles().write(2, this.location.getZ()); + break; + default: + throw new NotCompatibleException(); + } + + tp.getBytes().write(0, (byte)Maths.compressAngle(this.location.getYaw())); + tp.getBytes().write(1, (byte)Maths.compressAngle(this.location.getPitch())); + tp.getBooleans().write(0, this.onGround); + this.sendPacket(this.player, tp); + mp.addToTimings(); + } + } + + public float getHeadYaw() { + return this.headYaw; + } + + private void setHeadYaw(float headYaw) throws InvocationTargetException { + boolean changed = this.headYaw != headYaw; + this.headYaw = headYaw; + if (changed) { + this.sendHeadYawUpdate(); + } + } + + private void sendHeadYawUpdate() throws InvocationTargetException { + if (this.spawned) { + MethodProfiler mp = new MethodProfiler("VE-827193"); + PacketContainer headYaw = new PacketContainer(Server.ENTITY_HEAD_ROTATION); + headYaw.getIntegers().write(0, this.entityId); + headYaw.getBytes().write(0, (byte)Maths.compressAngle(this.headYaw)); + this.sendPacket(this.player, headYaw); + mp.addToTimings(); + } + } + + public boolean isVisible() { + return !this.hidden; + } + + public void setVisible(boolean visible) throws InvocationTargetException { + MethodProfiler mp = new MethodProfiler("VE-63821707"); + boolean changed = visible == this.hidden; + this.hidden = !visible; + if (changed && this.dataWatcher != null) { + if (this.is19()) { + this.dataWatcher.getWatchableObject(0).setValue(this.generateBitMask()); + } else { + this.dataWatcher.setObject(0, this.generateBitMask()); + } + + this.sendMetaUpdate(); + mp.addToTimings(); + } + } + + private void sendMetaUpdate() throws InvocationTargetException { + if (this.spawned) { + MethodProfiler mp = new MethodProfiler("VE-42193981291"); + PacketContainer update = new PacketContainer(Server.ENTITY_METADATA); + update.getIntegers().write(0, this.entityId); + update.getWatchableCollectionModifier().write(0, this.dataWatcher.getWatchableObjects()); + this.sendPacket(this.player, update); + mp.addToTimings(); + } + } + + public void hide() throws InvocationTargetException { + this.setVisible(false); + } + + public void show() throws InvocationTargetException { + this.setVisible(true); + } + + public void spawn() throws InvocationTargetException { + if (Bukkit.isPrimaryThread()) { + this.spawn00(); + } else { + ReflexScheduler.sync().run(new ReflexRunnable("NpcSpawn-" + this.entityId + ":" + this.player.getName()) { + @Override + public void execute() throws Exception { + NPC.this.spawn00(); + } + }); + } + } + + private void spawn00() throws InvocationTargetException { + MethodProfiler mp = new MethodProfiler("VE-120371288"); + if (!this.spawned) { + if (this.randomIDeachSpawn) { + this.entityId = EntityUtils.getFreeEntityID(); + } + + boolean tab; + try { + this.sendTabPacket(); + tab = true; + } catch (RuntimeException ignored) { + tab = false; + } + + this.spawn0(); + if (!this.showInTab && tab) { + this.sendTabRemovePacket(); + } + + this.inTab = this.showInTab && tab; + this.spawned = true; + mp.addToTimings(); + } + } + + private void addPotionEffect(Byte effectId, Byte amplifier, Integer duration, boolean particles) throws InvocationTargetException { + MethodProfiler mp = new MethodProfiler("VE-87219837"); + PacketContainer container = new PacketContainer(Server.ENTITY_EFFECT); + container.getIntegers().write(0, this.entityId); + container.getBytes().write(0, effectId); + container.getBytes().write(1, amplifier); + container.getIntegers().write(1, duration); + container.getBytes().write(2, Byte.valueOf((byte)(particles ? 1 : 0))); + this.sendPacket(this.player, container); + mp.addToTimings(); + } + + public void removePotionEffect(Byte effectId) { + MethodProfiler mp = new MethodProfiler("VE-298137921"); + PacketContainer container = new PacketContainer(Server.REMOVE_ENTITY_EFFECT); + container.getIntegers().write(0, this.entityId); + container.getBytes().write(0, effectId); + this.sendPacket(this.player, container); + mp.addToTimings(); + } + + private void sendTabPacket() throws InvocationTargetException { + MethodProfiler mp = new MethodProfiler("VE-5897123989"); + Player bukkitPlayer = Bukkit.getPlayer(this.uuid); + if (bukkitPlayer == null || !bukkitPlayer.isOnline() || !this.player.canSee(bukkitPlayer) && this.player != bukkitPlayer) { + PacketContainer tab = new PacketContainer(Server.PLAYER_INFO); + if (NPCCommons.getMCVersion() == MCVersion.V1_7_X) { + tab.getIntegers().write(0, 0); + tab.getGameProfiles().write(0, new WrappedGameProfile(this.uuid, this.username)); + tab.getIntegers().write(1, 0); + tab.getIntegers().write(2, NPCCommons.getRdm().nextInt(500)); + tab.getStrings().write(0, this.username); + } else { + tab.getPlayerInfoAction().write(0, PlayerInfoAction.ADD_PLAYER); + List playerData = new ArrayList<>(); + playerData.add( + new PlayerInfoData( + new WrappedGameProfile(this.uuid, this.username), + NPCCommons.getRdm().nextInt(900), + NativeGameMode.SURVIVAL, + WrappedChatComponent.fromText(this.username) + ) + ); + tab.getPlayerInfoDataLists().write(0, playerData); + } + + this.sendPacket(this.player, tab); + mp.addToTimings(); + this.inTab = true; + } else { + throw new RuntimeException(); + } + } + + private void spawn0() throws InvocationTargetException { + if (!this.spawned) { + MethodProfiler mp = new MethodProfiler("VE-479812739"); + + try { + switch (NPCCommons.getMCVersion()) { + case V1_7_X: + this.spawnNPC_1_7(); + break; + case V1_8_X: + this.spawnNPC_1_8(); + break; + case V1_9_X: + this.spawnNPC_1_9(); + break; + case V1_10_X: + this.spawnNPC_1_10(); + break; + case V1_11_X: + this.spawnNPC_1_11(); + break; + case V1_12_X: + this.spawnNPC_1_12(); + break; + case V1_13_X: + this.spawnNPC_1_13(); + break; + default: + throw new NotCompatibleException(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + this.sendHeadYawUpdate(); + mp.addToTimings(); + } + } + + private void set(int index, WrappedDataWatcher watcher, Object value) { + if (this.dataWatcher.hasIndex(index)) { + watcher.getWatchableObject(index).setValue(value); + } else { + watcher.setObject(index, value); + } + } + + private byte generateBitMask() { + return (byte)( + (this.burning ? 1 : 0) + + (this.sneaking ? 2 : 0) + + (this.sprinting ? 8 : 0) + + (this.using ? 16 : 0) + + (this.hidden ? 32 : 0) + + (this.is19() ? (this.glowing ? 64 : 0) + (this.flying ? 128 : 0) : 0) + ); + } + + private void spawnNPC_1_13() throws Exception { + this.spawnNPC_1_12(); + } + + private void spawnNPC_1_12() throws Exception { + this.spawnNPC_1_11(); + } + + private void spawnNPC_1_11() throws Exception { + this.spawnNPC_1_10(); + } + + private void spawnNPC_1_10() throws Exception { + MethodProfiler mp = new MethodProfiler("VE-7210938"); + PacketContainer spawn = new PacketContainer(Server.NAMED_ENTITY_SPAWN); + spawn.getIntegers().write(0, this.entityId); + spawn.getSpecificModifier(UUID.class).write(0, this.uuid); + spawn.getDoubles().write(0, this.location.getX()); + spawn.getDoubles().write(1, this.location.getY()); + spawn.getDoubles().write(2, this.location.getZ()); + spawn.getBytes().write(0, (byte)Maths.compressAngle(this.location.getYaw())); + spawn.getBytes().write(1, (byte)Maths.compressAngle(this.location.getPitch())); + ImpWrappedDataWatcher improvedDataWatcher = new ImpWrappedDataWatcher(); + improvedDataWatcher.setEntireMap( + 0, + this.generateBitMask(), + 1, + 20, + 2, + this.username, + 3, + true, + 4, + this.silent, + 5, + true, + 6, + (byte)1, + 7, + this.health, + 8, + 0, + 9, + false, + 10, + 0, + 11, + 0.0F, + 12, + NPCCommons.getRdm().nextInt(10000), + 13, + (byte)0, + 14, + (byte)1 + ); + this.dataWatcher = improvedDataWatcher; + spawn.getDataWatcherModifier().write(0, this.dataWatcher); + this.sendPacket(this.player, spawn); + this.onSpawn(); + mp.addToTimings(); + } + + private void spawnNPC_1_9() throws Exception { + MethodProfiler mp = new MethodProfiler("VE-128736181"); + PacketContainer spawn = new PacketContainer(Server.NAMED_ENTITY_SPAWN); + spawn.getIntegers().write(0, this.entityId); + spawn.getSpecificModifier(UUID.class).write(0, this.uuid); + spawn.getDoubles().write(0, this.location.getX()); + spawn.getDoubles().write(1, this.location.getY()); + spawn.getDoubles().write(2, this.location.getZ()); + spawn.getBytes().write(0, (byte)Maths.compressAngle(this.location.getYaw())); + spawn.getBytes().write(1, (byte)Maths.compressAngle(this.location.getPitch())); + ImpWrappedDataWatcher improvedDataWatcher = new ImpWrappedDataWatcher(); + improvedDataWatcher.setEntireMap( + 0, + this.generateBitMask(), + 1, + 20, + 2, + this.username, + 3, + true, + 4, + this.silent, + 5, + (byte)1, + 6, + this.health, + 7, + 0, + 8, + false, + 9, + 0, + 10, + 0.0F, + 11, + NPCCommons.getRdm().nextInt(10000), + 12, + (byte)0, + 13, + (byte)1 + ); + this.dataWatcher = improvedDataWatcher; + spawn.getDataWatcherModifier().write(0, this.dataWatcher); + this.sendPacket(this.player, spawn); + this.onSpawn(); + mp.addToTimings(); + } + + private void spawnNPC_1_8() throws InvocationTargetException { + MethodProfiler mp = new MethodProfiler("VE-927131814"); + PacketContainer spawn = new PacketContainer(Server.NAMED_ENTITY_SPAWN); + spawn.getIntegers().write(0, this.entityId); + spawn.getSpecificModifier(UUID.class).write(0, this.uuid); + spawn.getIntegers().write(1, (int)(this.location.getX() * 32.0)); + spawn.getIntegers().write(2, (int)(this.location.getY() * 32.0)); + spawn.getIntegers().write(3, (int)(this.location.getZ() * 32.0)); + spawn.getBytes().write(0, (byte)Maths.compressAngle(this.location.getYaw())); + spawn.getBytes().write(1, (byte)Maths.compressAngle(this.location.getPitch())); + spawn.getIntegers().write(4, 0); + ImpWrappedDataWatcher improvedDataWatcher = new ImpWrappedDataWatcher(); + improvedDataWatcher.setEntireMap( + 0, + this.generateBitMask(), + 1, + (short)20, + 2, + this.username, + 3, + (byte)1, + 4, + (byte)(this.silent ? 1 : 0), + 6, + this.health, + 7, + 0, + 8, + (byte)0, + 9, + (byte)0, + 10, + (byte)127, + 15, + (byte)1, + 16, + 0, + 17, + 0.0F, + 18, + NPCCommons.getRdm().nextInt(10000) + ); + this.dataWatcher = improvedDataWatcher; + spawn.getDataWatcherModifier().write(0, this.dataWatcher); + this.sendPacket(this.player, spawn); + this.onSpawn(); + mp.addToTimings(); + } + + private void spawnNPC_1_7() throws InvocationTargetException { + MethodProfiler mp = new MethodProfiler("VE-696412971"); + PacketContainer spawn = new PacketContainer(Server.NAMED_ENTITY_SPAWN); + spawn.getIntegers().write(0, this.entityId); + spawn.getGameProfiles().write(0, new WrappedGameProfile(this.uuid, this.username)); + spawn.getIntegers().write(1, (int)(this.location.getX() * 32.0)); + spawn.getIntegers().write(2, (int)(this.location.getY() * 32.0)); + spawn.getIntegers().write(3, (int)(this.location.getZ() * 32.0)); + spawn.getBytes().write(0, (byte)Maths.compressAngle(this.location.getYaw())); + spawn.getBytes().write(1, (byte)Maths.compressAngle(this.location.getPitch())); + spawn.getIntegers().write(4, 0); + this.dataWatcher = new WrappedDataWatcher(); + this.dataWatcher.setObject(0, this.generateBitMask()); + this.dataWatcher.setObject(1, (short)20); + this.dataWatcher.setObject(2, this.username); + this.dataWatcher.setObject(3, 1); + this.dataWatcher.setObject(4, this.silent ? 1 : 0); + this.dataWatcher.setObject(5, 1); + this.dataWatcher.setObject(6, this.health); + this.dataWatcher.setObject(7, 0); + this.dataWatcher.setObject(8, (byte)0); + this.dataWatcher.setObject(9, (byte)0); + this.dataWatcher.setObject(10, (byte)127); + this.dataWatcher.setObject(15, (byte)1); + this.dataWatcher.setObject(16, 0); + this.dataWatcher.setObject(17, 0.0F); + this.dataWatcher.setObject(18, NPCCommons.getRdm().nextInt(10000)); + spawn.getDataWatcherModifier().write(0, this.dataWatcher); + this.sendPacket(this.player, spawn); + this.onSpawn(); + mp.addToTimings(); + } + + private void onSpawn() { + MethodProfiler mp = new MethodProfiler("VE-591723798"); + NPCTeamTricks.disableCollisions(this.player, this); + this.spawnTracker = new Timer(); + mp.addToTimings(); + } + + public void despawn() throws InvocationTargetException { + MethodProfiler mp = new MethodProfiler("VE-8217938188"); + this.despawnNPC(); + if (this.inTab) { + this.sendTabRemovePacket(); + } + + this.inTab = false; + this.spawned = false; + mp.addToTimings(); + } + + private void sendTabRemovePacket() throws InvocationTargetException { + if (this.inTab) { + MethodProfiler mp = new MethodProfiler("VE-2791381289"); + PacketContainer tab = new PacketContainer(Server.PLAYER_INFO); + if (NPCCommons.getMCVersion() == MCVersion.V1_7_X) { + tab.getIntegers().write(0, 4); + tab.getGameProfiles().write(0, new WrappedGameProfile(this.uuid, this.username)); + tab.getStrings().write(0, this.username); + } else { + tab.getPlayerInfoAction().write(0, PlayerInfoAction.REMOVE_PLAYER); + List playerData = new ArrayList<>(); + playerData.add( + new PlayerInfoData( + new WrappedGameProfile(this.uuid, this.username), + NPCCommons.getRdm().nextInt(900), + NativeGameMode.SURVIVAL, + WrappedChatComponent.fromText(this.username) + ) + ); + tab.getPlayerInfoDataLists().write(0, playerData); + } + + this.sendPacket(this.player, tab); + mp.addToTimings(); + } + } + + private void despawnNPC() throws InvocationTargetException { + if (this.spawned) { + MethodProfiler mp = new MethodProfiler("VE-7213914"); + PacketContainer destroy = new PacketContainer(Server.ENTITY_DESTROY); + destroy.getIntegerArrays().write(0, new int[]{this.entityId}); + this.sendPacket(this.player, destroy); + mp.addToTimings(); + } + } + + private boolean is19() { + return NPCCommons.getMCVersion().getId() >= MCVersion.V1_9_X.getId(); + } + + private float getMaxRelMoveRange() throws NotCompatibleException { + switch (NPCCommons.getMCVersion()) { + case V1_7_X: + return 4.0F; + case V1_8_X: + return 4.0F; + case V1_9_X: + return 8.0F; + case V1_10_X: + return 8.0F; + case V1_11_X: + case V1_12_X: + case V1_13_X: + return 8.0F; + default: + throw new NotCompatibleException(); + } + } + + public int getID() { + return this.entityId; + } + + public void setID(int eid) { + if (this.spawned) { + throw new UnsupportedOperationException("Cannot modify entity ID while entity is spawned"); + } else { + this.entityId = eid; + } + } + + public boolean isSpawned() { + return this.spawned; + } + + public boolean isDoingAnimations() { + return this.autoAnimations; + } + + public void doAnimations(boolean animation) { + this.autoAnimations = animation; + } + + public boolean isAutoRespawning() { + return this.autoRespawn; + } + + public void shouldAutoRespawn(boolean respawn) { + this.autoRespawn = respawn; + } + + private boolean is17() { + return NPCCommons.getMCVersion() == MCVersion.V1_7_X; + } + + private void sendPacket(Player player, PacketContainer packet) { + if (syncNpcs == null) { + syncNpcs = Reflex.getReflex().getSetting("killaura.sync_npcs", false); + } + + if (syncNpcs) { + Packets.sendPacketSync(player, packet); + } else { + Packets.sendPacketAsync(player, packet); + } + } + + @Override + public String toString() { + return "NPC(spawnTracker=" + + this.spawnTracker + + ", player=" + + this.player + + ", randomIDeachSpawn=" + + this.randomIDeachSpawn + + ", username=" + + this.username + + ", uuid=" + + this.uuid + + ", sprinting=" + + this.sprinting + + ", sneaking=" + + this.sneaking + + ", using=" + + this.using + + ", burning=" + + this.burning + + ", flying=" + + this.flying + + ", glowing=" + + this.glowing + + ", silent=" + + this.silent + + ", showInTab=" + + this.showInTab + + ", hidden=" + + this.hidden + + ", onGround=" + + this.onGround + + ", spawned=" + + this.isSpawned() + + ", inTab=" + + this.inTab + + ", autoAnimations=" + + this.autoAnimations + + ", autoRespawn=" + + this.autoRespawn + + ", dataWatcher=" + + this.dataWatcher + + ", location=" + + this.getLocation() + + ", headYaw=" + + this.getHeadYaw() + + ", health=" + + this.getHealth() + + ", moveCounter=" + + this.moveCounter + + ", entityId=" + + this.entityId + + ", lastMove=" + + this.lastMove + + ", oldLocation=" + + this.oldLocation + + ", hideNametag=" + + this.hideNametag + + ")"; + } + + public void setHideNametag(boolean hideNametag) { + this.hideNametag = hideNametag; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/npc/NPCCommons.java b/src/main/java/rip/reflex/util/protocol/npc/NPCCommons.java new file mode 100644 index 0000000..885a722 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/npc/NPCCommons.java @@ -0,0 +1,51 @@ +package rip.reflex.util.protocol.npc; + +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.ProtocolManager; +import java.util.ArrayList; +import java.util.SplittableRandom; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; + +public class NPCCommons { + private static NPCCommons npcCommonsInstance; + public final ArrayList listeners = new ArrayList<>(); + private final MCVersion mcVersion = VersionUtils.getServerVersion(); + public SplittableRandom rdm; + + public static ProtocolManager getProtocolManager() { + return ProtocolLibrary.getProtocolManager(); + } + + public static MCVersion getMCVersion() { + return getNpcCommonsInstance().mcVersion; + } + + public static NPCCommons getNpcCommonsInstance() { + return npcCommonsInstance; + } + + public static ArrayList getListeners() { + return getNpcCommonsInstance().listeners; + } + + public static SplittableRandom getRdm() { + return getNpcCommonsInstance().rdm; + } + + public void init() { + npcCommonsInstance = this; + this.rdm = new SplittableRandom(); + new HitPacketListener(); + } + + public void registerListener(HitListener listener) { + if (!this.listeners.contains(listener)) { + this.listeners.add(listener); + } + } + + public void unregisterListener(HitListener listener) { + this.listeners.remove(listener); + } +} diff --git a/src/main/java/rip/reflex/util/protocol/npc/NPCStatus.java b/src/main/java/rip/reflex/util/protocol/npc/NPCStatus.java new file mode 100644 index 0000000..5057445 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/npc/NPCStatus.java @@ -0,0 +1,8 @@ +package rip.reflex.util.protocol.npc; + +public enum NPCStatus { + NOT_SPAWNED, + SPAWNED_VISIBLE, + SPAWNED_INVISIBLE, + OFFLINE; +} diff --git a/src/main/java/rip/reflex/util/protocol/npc/NPCTeamTricks.java b/src/main/java/rip/reflex/util/protocol/npc/NPCTeamTricks.java new file mode 100644 index 0000000..08571db --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/npc/NPCTeamTricks.java @@ -0,0 +1,61 @@ +package rip.reflex.util.protocol.npc; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.Team; +import rip.reflex.Reflex; +import rip.reflex.util.data.Stats; +import rip.reflex.util.misc.Strings; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.thread.ReflexRunnable; +import rip.reflex.util.thread.ReflexScheduler; + +public class NPCTeamTricks { + private static Scoreboard scoreboard; + private static Team team; + private static boolean init = false; + + public static void init() { + if (!init) { + ReflexScheduler.sync().run(new ReflexRunnable("IB-757012") { + @Override + public void execute() throws Exception { + NPCTeamTricks.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); + NPCTeamTricks.team = NPCTeamTricks.scoreboard.registerNewTeam(Strings.randomAbc(15)); + NPCTeamTricks.team.setCanSeeFriendlyInvisibles(false); + NPCTeamTricks.team.setAllowFriendlyFire(true); + } + }); + init = true; + } + } + + static void disableCollisions(final Player p, final NPC npc) { + if (VersionUtils.getClientVersion(p).getId() >= MCVersion.V1_9_X.getId() && Reflex.getReflex().getSetting("killaura.disable_collisions", true)) { + final Stats stats = Stats.of(p); + ReflexScheduler.sync().run(new ReflexRunnable("IB-68979281") { + @Override + public void execute() throws Exception { + if (!stats.getStat("scoreboardSet", boolean.class)) { + stats.setStat("scoreboardSet", true); + p.setScoreboard(NPCTeamTricks.scoreboard); + } + + if (!NPCTeamTricks.team.hasEntry(p.getName())) { + NPCTeamTricks.team.addEntry(p.getName()); + } + + if (!NPCTeamTricks.team.hasEntry(npc.username)) { + NPCTeamTricks.team.addEntry(npc.username); + } + } + }); + } + } + + public static Scoreboard getScoreboard() { + return scoreboard; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/packet/EntityActions.java b/src/main/java/rip/reflex/util/protocol/packet/EntityActions.java new file mode 100644 index 0000000..9768897 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/packet/EntityActions.java @@ -0,0 +1,16 @@ +package rip.reflex.util.protocol.packet; + +public final class EntityActions { + public static final int START_SNEAKING = 0; + public static final int STOP_SNEAKING = 1; + public static final int LEAVE_BED = 2; + public static final int START_SPRINTING = 3; + public static final int STOP_SPRINTING = 4; + public static final int START_JUMP_WITH_HORSE = 5; + public static final int STOP_JUMP_WITH_HORSE = 6; + public static final int OPEN_HORSE_INVENTORY = 7; + public static final int START_FLYING_WITH_ELYTRA = 8; + + private EntityActions() { + } +} diff --git a/src/main/java/rip/reflex/util/protocol/packet/PacketCache.java b/src/main/java/rip/reflex/util/protocol/packet/PacketCache.java new file mode 100644 index 0000000..5f1e8be --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/packet/PacketCache.java @@ -0,0 +1,101 @@ +package rip.reflex.util.protocol.packet; + +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.EnumWrappers.EntityUseAction; +import com.comphenix.protocol.wrappers.EnumWrappers.PlayerAction; +import java.io.Serializable; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import rip.reflex.util.time.Timer; + +public class PacketCache implements Serializable { + private final Map, Map> map = new ConcurrentHashMap<>(); + private final Timer accessTracker = new Timer(); + private final PacketContainer packet; + + public PacketCache(PacketContainer packet) { + this.packet = Objects.requireNonNull(packet, "[PC] Packet cannot be null"); + } + + public Integer readInteger(int index) { + Map m = this.getTypeMap(Integer.class); + return m.containsKey(index) ? this.fromMap(m, index) : this.setAndReturn(m, index, this.packet.getIntegers().read(index)); + } + + public Short readShort(int index) { + Map m = this.getTypeMap(Short.class); + return m.containsKey(index) ? this.fromMap(m, index) : this.setAndReturn(m, index, this.packet.getShorts().read(index)); + } + + public Long readLong(int index) { + Map m = this.getTypeMap(Long.class); + return m.containsKey(index) ? this.fromMap(m, index) : this.setAndReturn(m, index, this.packet.getLongs().read(index)); + } + + public Float readFloat(int index) { + Map m = this.getTypeMap(Float.class); + return m.containsKey(index) ? this.fromMap(m, index) : this.setAndReturn(m, index, this.packet.getFloat().read(index)); + } + + public Double readDouble(int index) { + Map m = this.getTypeMap(Double.class); + return m.containsKey(index) ? this.fromMap(m, index) : this.setAndReturn(m, index, this.packet.getDoubles().read(index)); + } + + public Boolean readBoolean(int index) { + Map m = this.getTypeMap(Boolean.class); + return m.containsKey(index) ? this.fromMap(m, index) : this.setAndReturn(m, index, this.packet.getBooleans().read(index)); + } + + public Byte readByte(int index) { + Map m = this.getTypeMap(Byte.class); + return m.containsKey(index) ? this.fromMap(m, index) : this.setAndReturn(m, index, this.packet.getBytes().read(index)); + } + + public String readString(int index) { + Map m = this.getTypeMap(String.class); + return m.containsKey(index) ? this.fromMap(m, index) : this.setAndReturn(m, index, this.packet.getStrings().read(index)); + } + + public PlayerAction readPlayerAction(int index) { + Map m = this.getTypeMap(PlayerAction.class); + return m.containsKey(index) ? this.fromMap(m, index) : this.setAndReturn(m, index, Packets.readPlayerActionSafely(this.packet, index)); + } + + public EntityUseAction readEntityUseAction(int index) { + Map m = this.getTypeMap(EntityUseAction.class); + return m.containsKey(index) ? this.fromMap(m, index) : this.setAndReturn(m, index, this.packet.getEntityUseActions().read(index)); + } + + public void clear() { + this.map.clear(); + } + + private T fromMap(Map m, int index) { + this.accessTracker.reset(); + return (T)m.get(index); + } + + private T setAndReturn(Map m, int index, Object value) { + this.accessTracker.reset(); + m.put(index, value); + return (T)value; + } + + private Map getTypeMap(Class type) { + if (!this.map.containsKey(type)) { + this.map.put(type, new ConcurrentHashMap<>()); + } + + return this.map.get(type); + } + + public Map, Map> getMap() { + return this.map; + } + + public Timer getAccessTracker() { + return this.accessTracker; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/packet/PacketDirection.java b/src/main/java/rip/reflex/util/protocol/packet/PacketDirection.java new file mode 100644 index 0000000..a4081eb --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/packet/PacketDirection.java @@ -0,0 +1,7 @@ +package rip.reflex.util.protocol.packet; + +public enum PacketDirection { + ClientToServer, + ServerToClient, + Both; +} diff --git a/src/main/java/rip/reflex/util/protocol/packet/Packets.java b/src/main/java/rip/reflex/util/protocol/packet/Packets.java new file mode 100644 index 0000000..342cde9 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/packet/Packets.java @@ -0,0 +1,245 @@ +package rip.reflex.util.protocol.packet; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.PacketType.Play.Client; +import com.comphenix.protocol.PacketType.Play.Server; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.EnumWrappers.EntityUseAction; +import com.comphenix.protocol.wrappers.EnumWrappers.PlayerAction; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.bukkit.Bukkit; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; +import rip.reflex.Reflex; +import rip.reflex.util.debugging.PacketDebugger; +import rip.reflex.util.protocol.MCVersion; +import rip.reflex.util.protocol.VersionUtils; +import rip.reflex.util.protocol.comptypes.CompPlayerAction; +import rip.reflex.util.protocol.npc.Animations; + +public class Packets { + public static final PacketType IN_FLYING = Client.FLYING; + public static final PacketType IN_POSITION = Client.POSITION; + public static final PacketType IN_LOOK = Client.LOOK; + public static final PacketType IN_POSLOOK = Client.POSITION_LOOK; + public static final PacketType IN_USEENTITY = Client.USE_ENTITY; + public static final PacketType IN_USEITEM = Client.USE_ITEM; + public static final PacketType IN_ENTITYACTION = Client.ENTITY_ACTION; + public static final PacketType IN_BLOCKPLACE = Client.BLOCK_PLACE; + public static final PacketType IN_SWING = Client.ARM_ANIMATION; + public static final PacketType IN_KEEPALIVE = Client.KEEP_ALIVE; + public static final PacketType IN_TRANSACTION = Client.TRANSACTION; + public static final PacketType IN_ABILITIES = Client.ABILITIES; + public static final PacketType IN_CLIENTCOMMAND = Client.CLIENT_COMMAND; + public static final PacketType IN_CHAT = Client.CHAT; + public static final PacketType IN_CLIENTSETTINGS = Client.SETTINGS; + public static final PacketType IN_HELDITEMCHANGE = Client.HELD_ITEM_SLOT; + public static final PacketType IN_VEHICLEMOVE = Client.VEHICLE_MOVE; + public static final PacketType IN_RESOURCEPACKSTATUS = Client.RESOURCE_PACK_STATUS; + public static final PacketType IN_CLICKWINDOW = Client.WINDOW_CLICK; + public static final PacketType[] CLIENT_UPDATE_PACKETS = new PacketType[]{IN_FLYING, IN_POSITION, IN_LOOK, IN_POSLOOK}; + public static final PacketType OUT_ENTITYVELOCITY = Server.ENTITY_VELOCITY; + public static final PacketType OUT_KEEPALIVE = Server.KEEP_ALIVE; + public static final PacketType OUT_TRANSACTION = Server.TRANSACTION; + public static final PacketType OUT_TEAMS = Server.SCOREBOARD_TEAM; + public static final PacketType OUT_ABILITIES = Server.ABILITIES; + public static final PacketType OUT_ENTITYMETADATA = Server.ENTITY_METADATA; + public static final PacketType OUT_ANIMATION = Server.ANIMATION; + public static final PacketType OUT_CHAT = Server.CHAT; + public static final PacketType OUT_RESOURCEPACKSEND = Server.RESOURCE_PACK_SEND; + private static final Map caches = new ConcurrentHashMap<>(); + + public static PlayerAction readPlayerActionSafely(PacketContainer p, int i) { + try { + return (PlayerAction)p.getPlayerActions().read(i); + } catch (IllegalArgumentException ex) { + if (ex.getMessage().contains("RIDING_JUMP")) { + return PlayerAction.START_RIDING_JUMP; + } else { + throw ex; + } + } + } + + public static Integer readInteger(PacketContainer packet, int index) { + return Reflex.getReflex().isCachingPackets() ? cachePacket(packet).readInteger(index) : (Integer)packet.getIntegers().read(index); + } + + public static Short readShort(PacketContainer packet, int index) { + return Reflex.getReflex().isCachingPackets() ? cachePacket(packet).readShort(index) : (Short)packet.getShorts().read(index); + } + + public static Long readLong(PacketContainer packet, int index) { + return Reflex.getReflex().isCachingPackets() ? cachePacket(packet).readLong(index) : (Long)packet.getLongs().read(index); + } + + public static Float readFloat(PacketContainer packet, int index) { + return Reflex.getReflex().isCachingPackets() ? cachePacket(packet).readFloat(index) : (Float)packet.getFloat().read(index); + } + + public static Double readDouble(PacketContainer packet, int index) { + return Reflex.getReflex().isCachingPackets() ? cachePacket(packet).readDouble(index) : (Double)packet.getDoubles().read(index); + } + + public static Boolean readBoolean(PacketContainer packet, int index) { + return Reflex.getReflex().isCachingPackets() ? cachePacket(packet).readBoolean(index) : (Boolean)packet.getBooleans().read(index); + } + + public static Byte readByte(PacketContainer packet, int index) { + return Reflex.getReflex().isCachingPackets() ? cachePacket(packet).readByte(index) : (Byte)packet.getBytes().read(index); + } + + public static String readString(PacketContainer packet, int index) { + return Reflex.getReflex().isCachingPackets() ? cachePacket(packet).readString(index) : (String)packet.getStrings().read(index); + } + + public static PlayerAction readPlayerAction(PacketContainer packet, int index) { + return Reflex.getReflex().isCachingPackets() ? cachePacket(packet).readPlayerAction(index) : (PlayerAction)packet.getPlayerActions().read(index); + } + + public static EntityUseAction readEntityUseAction(PacketContainer packet, int index) { + return Reflex.getReflex().isCachingPackets() ? cachePacket(packet).readEntityUseAction(index) : (EntityUseAction)packet.getEntityUseActions().read(index); + } + + public static void clearPacketCaches() { + if (Reflex.getReflex().isCachingPackets()) { + List toRem = new ArrayList<>(); + + for (PacketContainer packet : caches.keySet()) { + PacketCache cache = caches.get(packet); + if (cache.getAccessTracker().hasPassed(5000L)) { + toRem.add(packet); + cache.clear(); + } + } + + toRem.forEach(caches::remove); + } + } + + private static PacketCache cachePacket(PacketContainer packet) { + if (!caches.containsKey(packet)) { + caches.put(packet, new PacketCache(packet)); + } + + return caches.get(packet); + } + + public static boolean isEmptyFlying(PacketContainer packet) { + return ( + packet.getType().equals(IN_LOOK) + || packet.getType().equals(IN_FLYING) + || packet.getType().equals(IN_POSITION) + || packet.getType().equals(IN_POSLOOK) + ) + && !readBoolean(packet, 1); + } + + public static boolean isMove(PacketContainer packet) { + return packet != null && (packet.getType().equals(IN_POSITION) || packet.getType().equals(IN_POSLOOK)); + } + + public static boolean isAttackPacket(PacketContainer packet) { + if (packet == null || !packet.getType().equals(IN_USEENTITY)) { + return false; + } else { + return VersionUtils.getServerVersion().getId() > MCVersion.V1_7_X.getId() + ? readEntityUseAction(packet, 0).equals(EntityUseAction.ATTACK) + : readByte(packet, 0) == 1; + } + } + + public static boolean isSneakPacket(PacketContainer packet) { + if (packet != null && packet.getType().equals(IN_ENTITYACTION)) { + CompPlayerAction action = CompPlayerAction.byPacket(packet); + return action == CompPlayerAction.START_SNEAKING || action == CompPlayerAction.STOP_SNEAKING; + } else { + return false; + } + } + + public static boolean isStartSneakingPacket(PacketContainer packet) { + if (packet != null && packet.getType().equals(IN_ENTITYACTION)) { + CompPlayerAction action = CompPlayerAction.byPacket(packet); + return action == CompPlayerAction.START_SNEAKING; + } else { + return false; + } + } + + public static boolean isStopSneakingPacket(PacketContainer packet) { + if (packet != null && packet.getType().equals(IN_ENTITYACTION)) { + CompPlayerAction action = CompPlayerAction.byPacket(packet); + return action == CompPlayerAction.STOP_SNEAKING; + } else { + return false; + } + } + + public static boolean isDamageAnimOf(PacketContainer p, Entity e) { + return p != null && p.getType().equals(OUT_ANIMATION) && readInteger(p, 0) == e.getEntityId() && readInteger(p, 1) == Animations.TAKE_DAMAGE.ordinal(); + } + + public static boolean isUseItemPacket(PacketContainer packet) { + return packet != null && packet.getType().equals(IN_BLOCKPLACE); + } + + public static boolean isUpdatePacket(PacketContainer packet) { + return packet.getType().equals(IN_FLYING) + || packet.getType().equals(IN_POSITION) + || packet.getType().equals(IN_LOOK) + || packet.getType().equals(IN_POSLOOK); + } + + public static Vector getVelocity(PacketContainer packet) { + if (packet != null && packet.getType().equals(OUT_ENTITYVELOCITY)) { + int x = readInteger(packet, 1); + int y = readInteger(packet, 2); + int z = readInteger(packet, 3); + return new Vector((double)x / 8000.0, (double)y / 8000.0, (double)z / 8000.0); + } else { + return null; + } + } + + public static void sendPacket(Player player, PacketContainer packet) { + try { + ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + PacketDebugger.addEntry(player, packet, false); + } catch (Exception ex) { + throw new RuntimeException( + "Failed to send packet " + packet.toString() + " to " + player.getName() + " from current thread " + Thread.currentThread().getName(), ex + ); + } + } + + public static void sendPacketSync(Player player, PacketContainer packet) { + try { + if (Bukkit.isPrimaryThread()) { + sendPacket(player, packet); + } else { + Bukkit.getScheduler().runTask(Reflex.getReflex(), () -> sendPacket(player, packet)); + } + } catch (Exception e) { + throw new RuntimeException("Failed to send packet " + packet.toString() + " to " + player.getName() + " from server's primary thread", e); + } + } + + public static void sendPacketAsync(Player player, PacketContainer packet) { + try { + ProtocolLibrary.getProtocolManager().getAsynchronousManager().getPacketStream().sendServerPacket(player, packet); + PacketDebugger.addEntry(player, packet, true); + } catch (Exception ex) { + throw new RuntimeException("Failed to send packet " + packet.toString() + " to " + player.getName() + " asynchronously", ex); + } + } + + public static Map getCaches() { + return caches; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/packet/SharedPacketData.java b/src/main/java/rip/reflex/util/protocol/packet/SharedPacketData.java new file mode 100644 index 0000000..9d00baa --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/packet/SharedPacketData.java @@ -0,0 +1,164 @@ +package rip.reflex.util.protocol.packet; + +public class SharedPacketData { + private double x; + private double y; + private double z; + private double oldX; + private double oldY; + private double oldZ; + private float yaw; + private float pitch; + private double oldYaw; + private double oldPitch; + private boolean vehicleMove; + private double movedX; + private double movedY; + private double movedZ; + private double rotatedYaw; + private double rotatedPitch; + + public SharedPacketData x(double x) { + this.x = x; + return this; + } + + public SharedPacketData oldX(double oldX) { + this.oldX = oldX; + return this; + } + + public SharedPacketData movedX(double movedX) { + this.movedX = movedX; + return this; + } + + public SharedPacketData y(double y) { + this.y = y; + return this; + } + + public SharedPacketData oldY(double oldY) { + this.oldY = oldY; + return this; + } + + public SharedPacketData movedY(double movedY) { + this.movedY = movedY; + return this; + } + + public SharedPacketData z(double z) { + this.z = z; + return this; + } + + public SharedPacketData oldZ(double oldZ) { + this.oldZ = oldZ; + return this; + } + + public SharedPacketData movedZ(double movedZ) { + this.movedZ = movedZ; + return this; + } + + public SharedPacketData yaw(float yaw) { + this.yaw = yaw; + return this; + } + + public SharedPacketData oldYaw(double oldYaw) { + this.oldYaw = oldYaw; + return this; + } + + public SharedPacketData rotatedYaw(double rotatedYaw) { + this.rotatedYaw = rotatedYaw; + return this; + } + + public SharedPacketData pitch(float pitch) { + this.pitch = pitch; + return this; + } + + public SharedPacketData oldPitch(double oldPitch) { + this.oldPitch = oldPitch; + return this; + } + + public SharedPacketData rotatedPitch(double rotatedPitch) { + this.rotatedPitch = rotatedPitch; + return this; + } + + public SharedPacketData vehicleMove() { + this.vehicleMove = true; + return this; + } + + public double getX() { + return this.x; + } + + public double getY() { + return this.y; + } + + public double getZ() { + return this.z; + } + + public double getOldX() { + return this.oldX; + } + + public double getOldY() { + return this.oldY; + } + + public double getOldZ() { + return this.oldZ; + } + + public float getYaw() { + return this.yaw; + } + + public float getPitch() { + return this.pitch; + } + + public double getOldYaw() { + return this.oldYaw; + } + + public double getOldPitch() { + return this.oldPitch; + } + + public boolean isVehicleMove() { + return this.vehicleMove; + } + + public double getMovedX() { + return this.movedX; + } + + public double getMovedY() { + return this.movedY; + } + + public double getMovedZ() { + return this.movedZ; + } + + public double getRotatedYaw() { + return this.rotatedYaw; + } + + public double getRotatedPitch() { + return this.rotatedPitch; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/packetaccess/PacketAccessor.java b/src/main/java/rip/reflex/util/protocol/packetaccess/PacketAccessor.java new file mode 100644 index 0000000..ab235f5 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/packetaccess/PacketAccessor.java @@ -0,0 +1,43 @@ +package rip.reflex.util.protocol.packetaccess; + +import com.comphenix.protocol.events.PacketContainer; +import rip.reflex.util.protocol.packet.Packets; + +public abstract class PacketAccessor { + private final PacketContainer packet; + + public PacketAccessor(PacketContainer packet) { + this.packet = packet; + } + + protected int readInt(int index) { + return Packets.readInteger(this.packet, index); + } + + protected float readFloat(int index) { + return (Float)this.packet.getFloat().readSafely(index); + } + + protected boolean readBoolean(int index) { + return (Boolean)this.packet.getBooleans().readSafely(index); + } + + protected PacketAccessor writeInt(int index, int value) { + this.packet.getIntegers().writeSafely(index, value); + return this; + } + + protected PacketAccessor writeFloat(int index, float value) { + this.packet.getFloat().writeSafely(index, value); + return this; + } + + protected PacketAccessor writeBoolean(int index, boolean value) { + this.packet.getBooleans().writeSafely(index, value); + return this; + } + + public PacketContainer getPacket() { + return this.packet; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/packetaccess/PacketPlayInUseEntity.java b/src/main/java/rip/reflex/util/protocol/packetaccess/PacketPlayInUseEntity.java new file mode 100644 index 0000000..2bcca92 --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/packetaccess/PacketPlayInUseEntity.java @@ -0,0 +1,23 @@ +package rip.reflex.util.protocol.packetaccess; + +import com.comphenix.protocol.events.PacketContainer; +import java.util.Arrays; +import org.bukkit.World; +import org.bukkit.entity.Entity; + +public class PacketPlayInUseEntity extends PacketAccessor { + public PacketPlayInUseEntity(PacketContainer packet) { + super(packet); + } + + public Entity getEntity(World world) { + Object[] entities = world.getEntities().toArray(); + int entityId = this.readInt(0); + return (Entity)Arrays.stream(entities).filter(entity -> ((Entity)entity).getEntityId() == entityId).findFirst().orElse(null); + } + + public PacketPlayInUseEntity setEntity(Entity entity) { + this.writeInt(0, entity.getEntityId()); + return this; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/protocolsupport/PSAPIAdapter.java b/src/main/java/rip/reflex/util/protocol/protocolsupport/PSAPIAdapter.java new file mode 100644 index 0000000..1f6c96c --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/protocolsupport/PSAPIAdapter.java @@ -0,0 +1,26 @@ +package rip.reflex.util.protocol.protocolsupport; + +import java.lang.reflect.Method; +import org.bukkit.entity.Player; + +public class PSAPIAdapter { + private final Method getpvm; + private final Method getIdMethod; + + public PSAPIAdapter() { + try { + this.getpvm = Class.forName("protocolsupport.api.ProtocolSupportAPI").getMethod("getProtocolVersion", Player.class); + this.getIdMethod = Class.forName("protocolsupport.api.ProtocolVersion").getMethod("getId"); + } catch (Exception ex) { + throw new ExceptionInInitializerError(ex); + } + } + + public Integer getProtocolVersion(Player p) { + try { + return (Integer)this.getIdMethod.invoke(this.getpvm.invoke(null, p)); + } catch (Exception e) { + throw new RuntimeException("Failed to retreive protocol version of " + p.getName() + "'s client using ProtocolSupport", e); + } + } +} diff --git a/src/main/java/rip/reflex/util/protocol/protocolsupport/ProtocolSupportHook.java b/src/main/java/rip/reflex/util/protocol/protocolsupport/ProtocolSupportHook.java new file mode 100644 index 0000000..8760b8c --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/protocolsupport/ProtocolSupportHook.java @@ -0,0 +1,42 @@ +package rip.reflex.util.protocol.protocolsupport; + +import rip.reflex.Reflex; + +public class ProtocolSupportHook { + private static PSAPIAdapter adapter; + private static Boolean present = null; + + public static boolean isPresent() { + if (present != null) { + return present; + } else { + try { + Class.forName("protocolsupport.api.ProtocolSupportAPI"); + Reflex.getReflex().info("ProtocolSupport is present"); + Reflex.getReflex().warn("ProtocolSupport compatibility is EXPERIMENTAL!"); + return present = true; + } catch (ClassNotFoundException ignored) { + Reflex.getReflex().info("ProtocolSupport is not present"); + return present = false; + } + } + } + + public static boolean isInitialized() { + return adapter != null; + } + + public static void init() { + if (isPresent()) { + setAdapter(new PSAPIAdapter()); + } + } + + public static PSAPIAdapter getAdapter() { + return adapter; + } + + public static void setAdapter(PSAPIAdapter adapter) { + ProtocolSupportHook.adapter = adapter; + } +} diff --git a/src/main/java/rip/reflex/util/protocol/viaversion/VVAPIAdapter.java b/src/main/java/rip/reflex/util/protocol/viaversion/VVAPIAdapter.java new file mode 100644 index 0000000..8edea0d --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/viaversion/VVAPIAdapter.java @@ -0,0 +1,20 @@ +package rip.reflex.util.protocol.viaversion; + +import org.bukkit.entity.Player; +import us.myles.ViaVersion.api.Via; +import us.myles.ViaVersion.api.ViaAPI; +import us.myles.ViaVersion.api.protocol.ProtocolVersion; + +public class VVAPIAdapter { + public int getProtocolVersion(Player player) { + return Via.getAPI().getPlayerVersion(player.getUniqueId()); + } + + public boolean hasMinimum(Player player, ProtocolVersion version) { + return this.getProtocolVersion(player) >= version.getId(); + } + + public ViaAPI getAPI() { + return Via.getAPI(); + } +} diff --git a/src/main/java/rip/reflex/util/protocol/viaversion/ViaVersionHook.java b/src/main/java/rip/reflex/util/protocol/viaversion/ViaVersionHook.java new file mode 100644 index 0000000..ccf156b --- /dev/null +++ b/src/main/java/rip/reflex/util/protocol/viaversion/ViaVersionHook.java @@ -0,0 +1,42 @@ +package rip.reflex.util.protocol.viaversion; + +import rip.reflex.Reflex; + +public class ViaVersionHook { + private static VVAPIAdapter adapter; + private static Boolean present = null; + + public static boolean isPresent() { + if (present != null) { + return present; + } else { + try { + Class.forName("us.myles.ViaVersion.api.ViaVersion"); + Class.forName("us.myles.ViaVersion.api.ViaAPI"); + Reflex.getReflex().info("ViaVersion is present"); + return present = true; + } catch (ClassNotFoundException ignored) { + Reflex.getReflex().info("ViaVersion is not present"); + return present = false; + } + } + } + + public static boolean isInitialized() { + return adapter != null; + } + + public static void init() { + if (isPresent()) { + setAdapter(new VVAPIAdapter()); + } + } + + public static VVAPIAdapter getAdapter() { + return adapter; + } + + public static void setAdapter(VVAPIAdapter adapter) { + ViaVersionHook.adapter = adapter; + } +} diff --git a/src/main/java/rip/reflex/util/serialization/Compressor.java b/src/main/java/rip/reflex/util/serialization/Compressor.java new file mode 100644 index 0000000..7f0df1f --- /dev/null +++ b/src/main/java/rip/reflex/util/serialization/Compressor.java @@ -0,0 +1,67 @@ +package rip.reflex.util.serialization; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.zip.DataFormatException; +import java.util.zip.Deflater; +import java.util.zip.Inflater; +import rip.reflex.util.misc.Misc; + +public class Compressor { + public static byte[] compressSafely(byte[] data) { + try { + return compress(data); + } catch (IOException ex) { + throw new RuntimeException("Failed to compress " + data.length + " bytes", ex); + } + } + + public static byte[] compress(byte[] data) throws IOException { + Deflater deflater = new Deflater(9); + deflater.setInput(data); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); + deflater.finish(); + byte[] buffer = new byte[1024]; + + while (!deflater.finished()) { + outputStream.write(buffer, 0, deflater.deflate(buffer)); + } + + outputStream.close(); + return outputStream.toByteArray(); + } + + public static byte[] compressObjSafely(Object obj) { + try { + return compressObj(obj); + } catch (IOException ex) { + throw new RuntimeException("Failed to compress object: " + obj.toString(), ex); + } + } + + public static byte[] compressObj(Object obj) throws IOException { + return compress(Misc.getBytes(obj)); + } + + public static byte[] decompressSafely(byte[] data) { + try { + return decompress(data); + } catch (DataFormatException | IOException e) { + throw new RuntimeException("Failed to decompress " + data.length + " bytes", e); + } + } + + public static byte[] decompress(byte[] data) throws IOException, DataFormatException { + Inflater inflater = new Inflater(); + inflater.setInput(data); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); + byte[] buffer = new byte[1024]; + + while (!inflater.finished()) { + outputStream.write(buffer, 0, inflater.inflate(buffer)); + } + + outputStream.close(); + return outputStream.toByteArray(); + } +} diff --git a/src/main/java/rip/reflex/util/serialization/ManualSerializable.java b/src/main/java/rip/reflex/util/serialization/ManualSerializable.java new file mode 100644 index 0000000..796eddb --- /dev/null +++ b/src/main/java/rip/reflex/util/serialization/ManualSerializable.java @@ -0,0 +1,8 @@ +package rip.reflex.util.serialization; + +import java.io.Serializable; +import java.util.List; + +public interface ManualSerializable { + List serialize(); +} diff --git a/src/main/java/rip/reflex/util/serialization/ObjectReader.java b/src/main/java/rip/reflex/util/serialization/ObjectReader.java new file mode 100644 index 0000000..ccb84bc --- /dev/null +++ b/src/main/java/rip/reflex/util/serialization/ObjectReader.java @@ -0,0 +1,36 @@ +package rip.reflex.util.serialization; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.Serializable; + +public class ObjectReader { + public static T read(Class c, byte[] data) { + return read(c, new ByteArrayInputStream(data)); + } + + public static T read(Class c, File file) { + try { + return read(c, new FileInputStream(file)); + } catch (FileNotFoundException ignored) { + throw new RuntimeException(); + } + } + + public static T read(Class c, InputStream in) { + try { + ObjectInputStream objIn = new ObjectInputStream(in); + T obj = (T)c.cast(objIn.read()); + in.close(); + objIn.close(); + return obj; + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } +} diff --git a/src/main/java/rip/reflex/util/serialization/ObjectWriter.java b/src/main/java/rip/reflex/util/serialization/ObjectWriter.java new file mode 100644 index 0000000..4b34552 --- /dev/null +++ b/src/main/java/rip/reflex/util/serialization/ObjectWriter.java @@ -0,0 +1,42 @@ +package rip.reflex.util.serialization; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.io.Serializable; + +public class ObjectWriter { + public static byte[] write(Class c, T obj) { + try { + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + ObjectOutputStream objOut = new ObjectOutputStream(byteOut); + objOut.writeObject(c.cast(obj)); + byte[] data = byteOut.toByteArray(); + byteOut.close(); + objOut.close(); + return data; + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } + + public static void write(Class c, T obj, OutputStream out) { + try { + out.write(write(c, obj)); + out.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static void write(Class c, T obj, File file) { + try { + write(c, obj, new FileOutputStream(file)); + } catch (IOException err) { + throw new RuntimeException(err); + } + } +} diff --git a/src/main/java/rip/reflex/util/stat/StatsCollector.java b/src/main/java/rip/reflex/util/stat/StatsCollector.java new file mode 100644 index 0000000..859d514 --- /dev/null +++ b/src/main/java/rip/reflex/util/stat/StatsCollector.java @@ -0,0 +1,48 @@ +package rip.reflex.util.stat; + +import org.bstats.Metrics; +import org.bstats.charts.SingleLineChart; +import rip.reflex.Reflex; +import rip.reflex.security.AntiPiracy; +import rip.reflex.util.misc.Misc; + +public class StatsCollector { + private static int kicked = 0; + private static int banned = 0; + private static boolean enabled = false; + + public static void collectKick() { + kicked++; + } + + public static void collectBan() { + banned++; + } + + public static void loadMetrics() { + if (Misc.isNumeric(AntiPiracy.getResource())) { + enabled = true; + Metrics metrics = new Metrics(Reflex.getReflex()); + metrics.addCustomChart(new SingleLineChart("total_kicked_players") { + @Override + public int getValue() { + int tempKicked = StatsCollector.kicked; + StatsCollector.kicked = 0; + return tempKicked; + } + }); + metrics.addCustomChart(new SingleLineChart("total_banned_players") { + @Override + public int getValue() { + int tempBanned = StatsCollector.banned; + StatsCollector.banned = 0; + return tempBanned; + } + }); + } + } + + public static boolean isEnabled() { + return enabled; + } +} diff --git a/src/main/java/rip/reflex/util/thread/AsyncReflexScheduler.java b/src/main/java/rip/reflex/util/thread/AsyncReflexScheduler.java new file mode 100644 index 0000000..1db4033 --- /dev/null +++ b/src/main/java/rip/reflex/util/thread/AsyncReflexScheduler.java @@ -0,0 +1,50 @@ +package rip.reflex.util.thread; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; +import rip.reflex.Reflex; + +public class AsyncReflexScheduler implements ReflexScheduler { + private final BukkitScheduler scheduler = Bukkit.getScheduler(); + private final JavaPlugin plugin; + + @Override + public BukkitTask run(ReflexRunnable runnable) { + if (!this.plugin.isEnabled()) { + return null; + } else { + Reflex.getReflex().getExecutor().execute(runnable); + return null; + } + } + + @Override + public BukkitTask runLater(ReflexRunnable runnable, int delay) { + if (!this.plugin.isEnabled()) { + return null; + } else { + Reflex.getReflex().getExecutor().execute(() -> { + try { + Thread.sleep((long)(delay * 50)); + } catch (Exception ex) { + System.err.println("I can't sleep :`("); + ex.printStackTrace(); + } + + runnable.run(); + }); + return null; + } + } + + @Override + public BukkitTask runTimer(ReflexRunnable runnable, int repeatdelay) { + return !this.plugin.isEnabled() ? null : this.scheduler.runTaskTimerAsynchronously(this.plugin, runnable, 0L, (long)repeatdelay); + } + + public AsyncReflexScheduler(JavaPlugin plugin) { + this.plugin = plugin; + } +} diff --git a/src/main/java/rip/reflex/util/thread/ReflexRunnable.java b/src/main/java/rip/reflex/util/thread/ReflexRunnable.java new file mode 100644 index 0000000..c5a3f2c --- /dev/null +++ b/src/main/java/rip/reflex/util/thread/ReflexRunnable.java @@ -0,0 +1,84 @@ +package rip.reflex.util.thread; + +import java.util.SplittableRandom; +import org.bukkit.Bukkit; +import rip.reflex.Reflex; +import rip.reflex.util.performance.timings.ReflexTimings; +import rip.reflex.util.performance.timings.TimingsEntry; + +public abstract class ReflexRunnable implements Runnable, AutoCloseable { + private static final SplittableRandom idGen = new SplittableRandom(System.currentTimeMillis()); + private String id; + private String name; + private long lastTakenTime = -1L; + private Boolean isPrimaryThread; + + public ReflexRunnable(String name) { + this.name = name; + this.id = name + " | " + idGen.nextInt(); + } + + public static ReflexRunnable simple(String name, final Runnable r) { + return new ReflexRunnable(name) { + @Override + public void execute() throws Exception { + r.run(); + } + }; + } + + @Override + public void run() { + this.newExecutionID(); + long beginTime = System.currentTimeMillis(); + + try { + this.execute(); + } catch (Exception ex) { + Reflex.getReflex().warn("An error occurred executing Reflex runnable with id '" + this.id + "'"); + this.onException(ex); + } + + long endTime = System.currentTimeMillis(); + long took = endTime - beginTime; + ReflexTimings.addEntry(new TimingsEntry(this.name + " (" + (this.isAsync() ? "A" : "S") + "RR)", took)); + } + + public void onException(Exception e) { + e.printStackTrace(); + } + + private void newExecutionID() { + this.id = this.name + " | " + idGen.nextInt(); + } + + public boolean isAsync() { + if (this.isPrimaryThread == null) { + this.isPrimaryThread = Bukkit.isPrimaryThread(); + } + + return !this.isPrimaryThread; + } + + public abstract void execute() throws Exception; + + @Override + public void close() throws Exception { + } + + public String getId() { + return this.id; + } + + public String getName() { + return this.name; + } + + public long getLastTakenTime() { + return this.lastTakenTime; + } + + public Boolean getIsPrimaryThread() { + return this.isPrimaryThread; + } +} diff --git a/src/main/java/rip/reflex/util/thread/ReflexScheduler.java b/src/main/java/rip/reflex/util/thread/ReflexScheduler.java new file mode 100644 index 0000000..4756faa --- /dev/null +++ b/src/main/java/rip/reflex/util/thread/ReflexScheduler.java @@ -0,0 +1,30 @@ +package rip.reflex.util.thread; + +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitTask; + +public interface ReflexScheduler { + static ReflexScheduler sync() { + return ReflexScheduler.Schedulers.sync; + } + + static ReflexScheduler async() { + return ReflexScheduler.Schedulers.async; + } + + BukkitTask run(T task); + + BukkitTask runLater(T task, int delayTicks); + + BukkitTask runTimer(T task, int periodTicks); + + public static class Schedulers { + private static ReflexScheduler sync; + private static ReflexScheduler async; + + public static void init(JavaPlugin plugin) { + sync = new SyncReflexScheduler(plugin); + async = new AsyncReflexScheduler(plugin); + } + } +} diff --git a/src/main/java/rip/reflex/util/thread/SyncReflexScheduler.java b/src/main/java/rip/reflex/util/thread/SyncReflexScheduler.java new file mode 100644 index 0000000..4b88d11 --- /dev/null +++ b/src/main/java/rip/reflex/util/thread/SyncReflexScheduler.java @@ -0,0 +1,32 @@ +package rip.reflex.util.thread; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; +import rip.reflex.util.crypto.Encryptor; + +public class SyncReflexScheduler implements ReflexScheduler { + private final BukkitScheduler scheduler = Bukkit.getScheduler(); + private final JavaPlugin plugin; + + public SyncReflexScheduler(JavaPlugin plugin) { + Encryptor.key[0] = -43; + this.plugin = plugin; + } + + @Override + public BukkitTask run(ReflexRunnable runnable) { + return !this.plugin.isEnabled() ? null : this.scheduler.runTask(this.plugin, runnable); + } + + @Override + public BukkitTask runLater(ReflexRunnable runnable, int delay) { + return !this.plugin.isEnabled() ? null : this.scheduler.runTaskLater(this.plugin, runnable, (long)delay); + } + + @Override + public BukkitTask runTimer(ReflexRunnable runnable, int repeatdelay) { + return !this.plugin.isEnabled() ? null : this.scheduler.runTaskTimer(this.plugin, runnable, 0L, (long)repeatdelay); + } +} diff --git a/src/main/java/rip/reflex/util/thread/Threads.java b/src/main/java/rip/reflex/util/thread/Threads.java new file mode 100644 index 0000000..fc1a63c --- /dev/null +++ b/src/main/java/rip/reflex/util/thread/Threads.java @@ -0,0 +1,21 @@ +package rip.reflex.util.thread; + +public class Threads { + public static void sleepMillis(long millis) { + try { + Thread.sleep(millis); + } catch (Exception ex) { + System.err.println("Can't sleep millis :`("); + ex.printStackTrace(); + } + } + + public static void sleepSeconds(long seconds) { + try { + Thread.sleep(seconds * 1000L); + } catch (Exception e) { + System.err.println("Can't sleep seconds :`("); + e.printStackTrace(); + } + } +} diff --git a/src/main/java/rip/reflex/util/time/FullTimeUnit.java b/src/main/java/rip/reflex/util/time/FullTimeUnit.java new file mode 100644 index 0000000..94d773d --- /dev/null +++ b/src/main/java/rip/reflex/util/time/FullTimeUnit.java @@ -0,0 +1,45 @@ +package rip.reflex.util.time; + +public enum FullTimeUnit { + MILLISECONDS(0.0), + SECONDS(1000.0), + MINUTES(60.0), + HOURS(60.0), + DAYS(24.0), + WEEKS(7.0), + MONTHS(4.0), + YEARS(12.0); + + private final double factor; + + public static void main(String[] args) { + System.out.println(MONTHS.to(16.0, YEARS)); + } + + public double to(double input, FullTimeUnit result) { + int target = result.ordinal(); + int current = this.ordinal(); + boolean down = target < current; + if (target == current) { + return input; + } else { + double work = input; + + while (current != target) { + if (down) { + work *= values()[current--].factor; + } else { + FullTimeUnit[] units = values(); + current++; + work /= units[current].factor; + } + } + + return (double)Math.round(work * 100.0) / 100.0; + } + } + + private FullTimeUnit(double factor) { + this.factor = factor; + } +} diff --git a/src/main/java/rip/reflex/util/time/TimeParser.java b/src/main/java/rip/reflex/util/time/TimeParser.java new file mode 100644 index 0000000..8049793 --- /dev/null +++ b/src/main/java/rip/reflex/util/time/TimeParser.java @@ -0,0 +1,119 @@ +package rip.reflex.util.time; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.AbstractMap.SimpleEntry; +import java.util.Map.Entry; +import rip.reflex.util.misc.Misc; + +public class TimeParser { + private static final HashMap typeMap = new HashMap<>(); + private long millis = 0L; + + public static void main(String[] args) { + new TimeParser().parse("1w1d1h1m1s"); + } + + public TimeParser parse(String input) { + StringBuilder current = new StringBuilder(); + List list = new ArrayList<>(); + Boolean isLastChar = null; + int lastSaved = -1; + + for (char c : input.toCharArray()) { + if (!this.multiMatch(c, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'M', 'm', 'y', 'Y', 'd', 'h', 's', 'w')) { + throw new IllegalArgumentException("illegal char: " + c); + } + + boolean isCurrentChar = this.multiMatch(c, 'M', 'm', 'y', 'd', 'h', 's', 'w'); + if (isLastChar == null) { + isLastChar = isCurrentChar; + } + + if (isCurrentChar == isLastChar) { + current.append(c); + isLastChar = isCurrentChar; + } else { + isLastChar = isCurrentChar; + list.add(current.toString()); + current = new StringBuilder(); + current.append(c); + if (lastSaved != -1) { + int currentSave = isCurrentChar ? 1 : 0; + if (lastSaved == currentSave) { + throw new IllegalArgumentException("Same save (impossible)"); + } + + lastSaved = currentSave; + } + } + } + + list.add(current.toString()); + if (list.size() % 2 != 0) { + throw new IllegalArgumentException("Could not find same amount of numbers and time chars"); + } else { + List> stringList = new ArrayList<>(); + String[] pair = new String[2]; + list.forEach(s -> { + if (pair[0] == null) { + pair[0] = s; + } else if (pair[1] == null) { + pair[1] = s; + } else { + stringList.add(new SimpleEntry<>(pair[0], pair[1])); + pair[0] = s; + pair[1] = null; + } + }); + stringList.add(new SimpleEntry<>(pair[0], pair[1])); + List> timeList = new ArrayList<>(); + stringList.forEach(entry -> { + if (Misc.isNumeric(entry.getKey()) && !Misc.isNumeric(entry.getValue())) { + timeList.add(new SimpleEntry<>(Integer.valueOf(entry.getKey()), typeMap.get(entry.getValue()))); + } else { + throw new IllegalArgumentException("Illegal char/digit sorting."); + } + }); + Collections.reverse(timeList); + FullTimeUnit[] last = new FullTimeUnit[]{null}; + timeList.forEach(entry -> { + this.millis = (long)((double)this.millis + entry.getValue().to((double)entry.getKey().intValue(), FullTimeUnit.MILLISECONDS)); + if (last[0] == null) { + last[0] = entry.getValue(); + } else if (last[0].ordinal() > entry.getValue().ordinal()) { + throw new IllegalArgumentException("Wrong order of time types"); + } else { + last[0] = entry.getValue(); + } + }); + return this; + } + } + + public long get() { + return this.millis; + } + + private boolean multiMatch(char c, char... chars) { + for (char aChar : chars) { + if (aChar == c) { + return true; + } + } + + return false; + } + + static { + typeMap.put("s", FullTimeUnit.SECONDS); + typeMap.put("m", FullTimeUnit.MINUTES); + typeMap.put("h", FullTimeUnit.HOURS); + typeMap.put("d", FullTimeUnit.DAYS); + typeMap.put("w", FullTimeUnit.WEEKS); + typeMap.put("M", FullTimeUnit.MONTHS); + typeMap.put("y", FullTimeUnit.YEARS); + } +} diff --git a/src/main/java/rip/reflex/util/time/Timer.java b/src/main/java/rip/reflex/util/time/Timer.java new file mode 100644 index 0000000..8a78635 --- /dev/null +++ b/src/main/java/rip/reflex/util/time/Timer.java @@ -0,0 +1,97 @@ +package rip.reflex.util.time; + +import java.io.Serializable; + +public class Timer implements Serializable { + private static final int integrityDataFingerprint_a = -578162988; + private static final int integrityDataArrInfo_a = 128319532; + private long startTime; + + public Timer(long startTime) { + this.startTime = startTime; + } + + public Timer() { + this(System.currentTimeMillis()); + } + + public Timer add(long millis) { + this.startTime = this.startTime + Math.abs(millis); + return this; + } + + public Timer addTicks(long ticks) { + this.startTime = this.startTime + Math.abs(ticks * 50L); + return this; + } + + public Timer addSeconds(long seconds) { + this.startTime = this.startTime + Math.abs(seconds * 1000L); + return this; + } + + public Timer subtract(long millis) { + this.startTime = this.startTime - Math.abs(millis); + return this; + } + + public Timer subtractTicks(long ticks) { + this.startTime = this.startTime - Math.abs(ticks) * 50L; + return this; + } + + public Timer subtractSeconds(long seconds) { + this.startTime = this.startTime - Math.abs(seconds * 1000L); + return this; + } + + public Timer offset(long millis) { + this.startTime += millis; + return this; + } + + public Timer offsetTicks(long ticks) { + this.startTime += ticks * 50L; + return this; + } + + public Timer offsetSeconds(long seconds) { + this.startTime += seconds * 1000L; + return this; + } + + public boolean hasPassed(long millis) { + return this.getTimePassed() >= millis; + } + + public boolean hasTicked(long ticks) { + return this.getTimeTicked() >= ticks; + } + + public long getTimePassed() { + return System.currentTimeMillis() - this.startTime; + } + + public long getTimeTicked() { + return this.getTimePassed() / 50L; + } + + public long getStartTime() { + return this.startTime; + } + + public Timer setStartTime(long newTime) { + if (newTime < 1L) { + this.reset(); + } else { + this.startTime = newTime; + } + + return this; + } + + public Timer reset() { + this.setStartTime(System.currentTimeMillis()); + return this; + } +} diff --git a/src/main/java/rip/reflex/util/time/date/ReflexFormatter.java b/src/main/java/rip/reflex/util/time/date/ReflexFormatter.java new file mode 100644 index 0000000..0d1d28f --- /dev/null +++ b/src/main/java/rip/reflex/util/time/date/ReflexFormatter.java @@ -0,0 +1,49 @@ +package rip.reflex.util.time.date; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; +import java.util.regex.Pattern; +import rip.reflex.Reflex; + +public class ReflexFormatter { + private static final ConcurrentHashMap formats = new ConcurrentHashMap<>(); + + public static String formatTime(String format, Date d) { + return getFormat(format).format(d); + } + + public static String formatTimeDefault(Date d) { + return getFormat("dd.MM.YYYY HH:mm:ss").format(d); + } + + public static SimpleDateFormat getFormat(String format) { + SimpleDateFormat f; + if (!formats.containsKey(format)) { + formats.put(format, f = new SimpleDateFormat(format)); + } else { + f = formats.get(format); + } + + return f; + } + + public static String formatLog(Level level, String message, Object... o) { + message = Pattern.quote(message); + return "[Reflex " + + Reflex.getReflex().getDescription().getVersion() + + "/" + + Reflex.getReflex().getDataVersion() + + "] " + + formatTime("dd.MM.YYYY HH:mm:ss", new Date(System.currentTimeMillis())) + + ' ' + + level.getName() + + ": " + + String.format(message, o); + } + + static { + formats.put("dd.MM.YYYY HH:mm:ss", new SimpleDateFormat("dd.MM.YYYY HH:mm:ss")); + } +} diff --git a/src/main/resources/advcfg.yml b/src/main/resources/advcfg.yml new file mode 100644 index 0000000..2839bba --- /dev/null +++ b/src/main/resources/advcfg.yml @@ -0,0 +1,584 @@ +#### Reflex Advanced Configuration ##################################### +# +# Welcome here! Looks like you want to change something, am +# I right? Before doing so, please note one thing: all the +# settings were tested a lot to work properly. If Reflex breaks +# after you touched anything, it's YOUR fault. +# +# For any configuration assistance please private message +# DarksideCode on Spigot, open an issue at go.reflex.rip/bug +# or write us in Discord: g.reflex.rip/discord +# +# PLEASE REFRAIN FROM TOUCHING ANYTHING WITHOUT SERIOUS REASONS TO! +# +# Also keep in mind that this is ADVANCED configuration. +# One tweak can break everything. Literally. Even your arm. +# +# Learn more about Reflex AdvCfg: +# --> https://g.reflex.rip/advcfg +# +# Useful links: +# +# 1. Report bugs/false positives/bypasses/console errors/other: +# --> https://g.reflex.rip/contributing +# --> https://g.reflex.rip/bug +# +# 2. Reflex Wiki (information about checks, lag accounting, etc): +# --> https://g.reflex.rip/wiki +# +# 3. Reflex Discord server (quick live support, bug reports, etc): +# --> https://g.reflex.rip/discord +# +# 4. Reflex on Spigot: +# --> https://g.reflex.rip/spigot +# +# With love, Reflex Development Team. +# © reflex.rip, 2016-2019. +# +######################################################################## + + + + +######################################################################## +# BASIC ADVCFG FILE INFORMATION (META) — its name (a very-very brief +# description), its author (provider) and its version number/string. +# +# MUST BE CHANGED BEFORE THIS ADVCFG GETS USED! +######################################################################## +name: 'Default Configuration' +provider: 'Reflex Development Team' +version: '2' + + + + +######################################################################## +# THE CONFIGURATION ITSELF +######################################################################## + +# Advanced KillAura options +ka: + + # Advanced options for component ka.cbd + # + # Combines all other Killaura components and looks at general + # violation density. Used to detect "half-legit-half-blatant" hacks. + # + # Accuracy: ★★★★★ (5/5 - awesome) + # Efficiency: ★★☆☆☆ (2/5 - useful in some cases or for some certain types of cheats) + cbd: + + # How many violations* does a player need to score within + # {period} ticks in order to be flagged? This check is used to detect + # blatant cheaters that are suspected very often but not heavily. + # + # * [Each check gives 'individual' (usually dynamic) number of + # violations, which also often differs from the one shown in + # verbose, because VLs going to ka.cbd and VLs going to player + # are different. The basic rule is same, though: the more the + # check is trusted, the more violation points it gives.] + threshold: 35 + + # Checking period in ticks*. + # (!) NO '/REFLEX RELOAD' SUPPORT: requires full server restart to update! + # + # * [1 second = 20 ticks, 2.5 s = 50 ticks, etc.] + period: 600 + + # Advanced options for component ka.clk + # + # Monitors players' clicking rates and detects various non-vanilla + # behavior, including fast / double-(multiple-) / consistent clicking. + # + # Accuracy: ★★★★☆ (4/5 - may have a few very rare false detections) + # Efficiency: ★★★☆☆ (3/5 - efficient for certain types of cheats) + clk: + + # Maximal allowed number of clicks players are allowed to + # do in one second (20 ticks). Legit jitter is usually ≤ 16 + # (keep in mind that Reflex's CPS calculation is kind of "unusual" and + # therefore the CPS it shows will be different to CPS shown by CPS meter + # software/mods; 18+ CPS should be impossible for a legitimate player to + # get on **Reflex's** click rate meter) + max_cps: 18 + + # Minimal allowed clicking variance. Used to detect consistent click rates. + # Higher - more strict. Lower - more lenient. 0 - disable the check. + # NOTE: this check is very stable and is not known to have any false positives. + min_click_variance: 2 + + # Minimal delay that Reflex will enforce between clicks, in milliseconds*. + # If a player constantly clicks at delays lower than this, then they are + # very likely to be using double-/triple-/N-click cheats or AutoClicker. + # For example, clicking with delay of 20 ms is approximately equal to + # 1000/20 = 50 clicks per second, which is absolutely not legitimate. + # + # * [1 second = 1000 milliseconds, 2.5 s = 2500 ms, etc.] + min_click_delay: 25 + + # Advanced options for component ka.fe + # + # Spawns many invisible entities in front of player's cursor when they are + # in combat. A legitimate player will always hit them, but many Killauras + # (especially Vanilla/NCP ones) may hit through and get caught by this check. + # + # Accuracy: ★★★★★ (5/5 - awesome) + # Efficiency: ★★★★☆ (4/5 - pretty efficient, detects many known types of cheats) + fe: + + # How many violations will the FrontEntity check add at once? + # The check itself is very well-known and has been stable for + # years, however, it might produce a few false positives in + # rare cases. It is not adviced to set the weight of this check + # to anything lower than 4-5 because that will make it barely + # effective. Setting this to something very high is also bad + weight: 7 + + # Advanced options for component ka.heu + # + # Uses a neural network with pre-trained (by us, the developers, with + # help of you, the community) datasets ("samples") to detect a wide + # range of combat cheats like Aimbot and Killaura/"LegitAura". + # + # (i) Settings regarding the Heuristics check do not affect the + # core (the NN and datasets) itself, but its "extra" checks + # added in release "10.9". Those parts are combined to compute + # a CP (Cheat Points) number based on neural network output. + # The number of cheat points is always shown in ka.heu verbose + # messages like "cp: N". CP is always a natural number, N∈[0..20]. + # The Heuristics check takes its final decision based both on + # NN output and on the number of cheat points, among with some + # other factors like lag status and recent behavior of a player. + # + # Accuracy: ★★★☆☆ (3/5 - known to have some false positives in some cases) + # Efficiency: ★★★★★ (5/5 - awesome) + heu: + + # If CP number of a player is greater than this (and the core decision + # is "cheater"), then, no matter the other factors, the player is considered + # cheating. This means that that player triggered too many "extra" checks + # at a time and, at the same moment, has been classified as a cheater + extreme_cp_threshold: 6 + + # If the core decision for a player is "cheater", they are not lagging + # (have a stable/"good" lag status) and have got a number of CP greater + # then this, then the final decision is going to be "cheater". + # Does not trigger on players whose lag status is considered "bad" + stable_cp_threshold: 3 + + # If the core decision for a player is "cheater" and moreover the NN + # is very sure about it (extremely high confidence), and the player's + # number of CP is greater then then the one set in this option, then + # the player is considered cheating. High confidence is pretty difficult + # for a legit player to achieve. When the NN is really "certain" the + # player is cheating, then most often they really do + certain_cp_threshold: 2 + + # Advanced options for component ka.hbx + # + # This check works by finding the best (not mandatory the most recent) + # hitbox of a player's target and then trying to reach it by "moving" + # {precision} blocks forward until the total "movement" distance exceeds + # a preliminarily calculated limit+{leniency}. If no target hitboxes + # (especially no previously mentioned "best" one) were met during + # this check, the player is suspected. If a player gets suspected by + # the Hitbox check more than {threshold} times in {suspicion_lifespan} + # milliseconds, then they are flagged and given KillAura violations. + # + # Accuracy: ★★★★☆ (4/5 - may have a few very rare false detections) + # Efficiency: ★★★★☆ (4/5 - pretty efficient, detects many known types of cheats) + hbx: + + # The size of one "hitbox tracer" "step" in blocks. + # Higher precision => higher checking accuracy, but more performance impact; + # less precision => lower checking accuracy, but less performance impact + precision: 0.005 + + # The number of additional blocks "hitbox tracer" is allowed to "travel" + # after exceeding the preliminarily calculated limit before stopping. + # Higher leniency => less effective (way more lenient) check + leniency: 0.013 + + # The maximal number of suspicions a player is allowed to obtain in + # {suspicion_lifespan} milliseconds before being flagged for cheating + threshold: 7 + + # After how many milliseconds* will Hitbox's suspicions be forgotten? + # * [1 second = 1000 milliseconds, 2.5 s = 2500 ms, etc.] + suspicion_lifespan: 3000 + + # How many violations will the Hitbox period check add at once (after + # a player will score more than {threshold} suspicions in {...lifespan} + # milliseconds)? This check is designed to kick quickly but not instantly + period_weight: 20 + + # There is also another, instant check in this component, which flags + # with first violation. It is used to a) detect very blatant Reach/Hitbox + # cheats faster; b) help Reflex detecting less blatant/"somewhat bypassing" + # Killauras. A player is flagged if the lowest distance computed by Reflex* + # is greater than {max_lowest}. + # + # Getting many "hitbox (instant)" flags usually indicates that a player + # is very likely to be using Reach/Hitbox/Killaura cheats or similar. + # + # * [Reflex stores several hitboxes of a player's target in memory, and for + # distance calculation it uses the one that it thinks fits "best" in current + # situation. There are also several nuances in distance calculation, so it is + # important that you DO NOT link Reflex's "lowest hitbox distance" with + # ordinary Minecraft distances like "number of blocks from eye to eye". + # This value is rather based on magic, so please refrain from touching it + # unless you really know what you do.] + max_lowest: 1.679 + + # How many violations will the Hitbox instant check add at once? + # See the {max_lowest} option above for more information about Hitbox Instant. + instant_weight: 15 + + # Advanced options for component ka.yrt + # + # Looks at players' aiming/rotation style during combat and finds + # any suspicious patterns in it, and then computes a "probability of + # hacking" using the `{suspicious_rotations} / {total_rotations} * 100 + # formula. Detects some Aimbots and Killauras very quickly. + # + # Accuracy: ★★★★☆ (4/5 - may have a few very rare false detections) + # Efficiency: ★★★☆☆ (3/5 - efficient for certain types of cheats) + yrt: + + # How probable (in percent, %) does a player need to be cheating + # according to the ka.yrt check in order to be flagged for KillAura + max_probability: 70 + + + + +# Advanced BlockActions options +# +# (i) One may want to reduce the values here a little bit in case of many +# "ultra-professional" players on the server who are "known" (trusted) +# to be able to build very quickly without any mods, autoclickers, etc. +blckact: + + # Advanced options for component blckact.sfd + # + # Checks for ScaffoldWalk hacks and enforces a bridging speed limit. + # + # Accuracy: ★★★★☆ (4/5 - may have a few very rare false detections) + # Efficiency: ★★★★★ (5/5 - awesome) + sfd: + + # Minimal delay between placing blocks when bridging horizontally (in ticks*). + # Higher - more strict. Lower - more lenient. 0.0 - disable the check. + # + # * [1 second = 20 ticks, 2.5 s = 50 ticks, etc.] + min_hor: 5.0 + + # Minimal delay between placing blocks when bridging diagonally (in ticks*). + # Higher - more strict. Lower - more lenient. 0.0 - disable the check. + # + # * [1 second = 20 ticks, 2.5 s = 50 ticks, etc.] + min_dia: 5.0 + + # Advanced options for component blckact.tw + # + # Checks for Tower hacks and enforces a towering speed limit. + # + # Accuracy: ★★★★☆ (4/5 - may have a few very rare false detections) + # Efficiency: ★★★★★ (5/5 - awesome) + tw: + + # Minimal delay between placing blocks when towering up (in ticks*). + # Higher - more strict. Lower - more lenient. 0.0 - disable the check. + # + # * [1 second = 20 ticks, 2.5 s = 50 ticks, etc.] + min_tw: 7.5 + + + + +# Advanced InvActions options +invact: + + # Advanced options for component invact.mov + # + # Prevents cheaters from walking/rotating with open inventory. + # + # Accuracy: ★★★★★ (5/5 - awesome) + # Efficiency: ★★★★☆ (4/5 - pretty efficient, detects many known types of cheats) + mov: + + # For how many milliseconds* are players allowed to move and/or + # rotate with open inventory? Reducing this number will speed + # detection of InventoryWalk hacks up, but may increase the number + # of false positives in various situations. + # + # * [1 second = 1000 milliseconds, 2.5 s = 2500 ms, etc.] + open_wait: 500 + + # Advanced options for component invact.fiv + # + # Restricts inventory-clicking/chest-looting rates. + # Prevents cheaters from using very blatant ChestStealer/AutoLoot hacks. + # + # NOTE: Reflex only counts clicks at items in different slots WITH SOMETHING IN THEM. + # Clicking at the same slot OR at slots without items is NOT checked. + # + # Accuracy: ★★★★☆ (4/5 - may have a few very rare false detections) + # Efficiency: ★★☆☆☆ (2/5 - useful in some cases or for some certain types of cheats) + fiv: + + # Most checks in Reflex, including the main invact.fiv subcomponent, are packet-based. + # That is, instead of listening to Bukkit events which provide no proper ways for a smooth + # lag accounting system, this check only watches packets sent by players and analyzes them. + # However, due to some changes made to the game protocol in 1.9, it became impossible to + # create a proper packet-based check on new versions. That's why our nicer (packet) check + # only works on 1.8x, sadly. + # + # In order to provide some basic (though a bit worse) protection for servers running new + # Minecraft versions, there is also a "classic" (event-based) check in Reflex. This option + # specifies whether you want to use that check or not. We advise you not to run both packet + # and event checks concurrently - that's useless and may cause problems. + # + # Possible values: + # + # (a) auto - let Reflex decide for you (RECOMMENDED). The check will be automatically + # enabled on 1.9+ and disabled on 1.8x. + # + # (b) true - enable the event-based invact.fiv check. + # + # (c) false - disable the event-based invact.fiv check. + # + # Reflex will self-disable with an error if an invalid value is set here. + enable_event_check: auto + + # If a player does more than one click in the number of milliseconds* specified below, + # they will be suspected and given violations. This only affects the event-check, and + # therefore also requires the event-check to be active (either with 'auto' + 1.9+ server + # or with 'true' set on the 'enable_event_check' option above). + # + # * [1 second = 1000 milliseconds, 2.5 s = 2500 ms, etc.] + min_event_click_delay: 75 + + # If a player does more than one click in the number of ticks* specified below, + # they will be suspected and given violations. + # + # * [1 second = 20 ticks, 2.5 s = 50 ticks, etc.] + min_click_delay: 2 + + # If a player will receive more than {const_clicking_threshold} consistent clicking + # suspicions within {const_click_lifespan} milliseconds*, they will be given many + # violations (failing this check 2-3 times is enough to be kicked from the server by default). + # + # * [1 second = 1000 milliseconds, 2.5 s = 2500 ms, etc.] + const_click_lifespan: 2250 + + # If a player has clicked more than {const_clicking_threshold} times in a row + # at an approximately equal ("consistent") rate, they will be given a suspicion. + # Learn more about this option by reading comment to the one above ('const_click_lifespan'). + const_clicking_threshold: 17 + + + + +# Advanced AntiKnockback options +vel: + + # Advanced options for component vel.act + # + # This check gives players small random velocities when they open + # any inventories (including chests, crafting tables, etc.) and makes + # sure they respond with a proper move. If a player did not move + # as expected, they are given a suspicion. Receiving more than {threshold} + # suspicions within {suspicion_lifespan} ms means that the player is very + # likely to be cheating, and therefore they are given a lot of violations + # at a time (a number that is enough for instant kick). + # + # Accuracy: ★★★★★ (5/5 - awesome) + # Efficiency: ★★★☆☆ (3/5 - efficient for certain types of cheats) + act: + + # Maximal allowed X/Z distance (in blocks) between knockback locations + # that Reflex predicts and players' actual knocknack locations + max_offset: 0.024 + + # The maximal number of suspicions a player is allowed to obtain in + # {suspicion_lifespan} milliseconds before being flagged for cheating + threshold: 2 + + # After how many milliseconds* will vel.act's suspicions be forgotten? + # * [1 second = 1000 milliseconds, 2.5 s = 2500 ms, etc.] + suspicion_lifespan: 30000 + + # How many ticks* should Reflex wait after "fatal" flags before dealing + # violations and showing the necessary verbose message(s)? For example, + # if this is set to 100, and a player scores over {threshold} suspicions + # in last {suspicion_lifespan} ms, then Reflex will wait 5 seconds before + # actually notifying about this in verbose and giving that player many + # violations (kicking them). This option is very recommended to be something + # high (100 is high enough, though it could even be higher if you wish) as + # it confuses cheaters and hardens their understanding of kick/ban reasons + # (because cheaters will be kicked "randomly", not right on their violations). + # + # (i) This does not affect "low" ("non-fatal") violations which only + # add 1 violation and exist simply to show verbose messages - these + # will always go without any delays. + # + # * [1 second = 20 ticks, 2.5 s = 50 ticks, etc.] + flag_delay: 100 + + # Advanced options for component vel.adr + # + # Checks for illegal movement direction changes in midair. + # This is normally impossible for legit players but often + # happens if a player is using knockback or other movement + # cheats, including BHop/Strafe. + # + # Accuracy: ★★★★☆ (4/5 - may have a few very rare false detections) + # Efficiency: ★★★★☆ (4/5 - pretty efficient, detects many known types of cheats) + adr: + + # Maximal allowed angle (in degrees) between player's current and + # their last movement direction vectors (180 degrees = full reverse; + # also, 180 degrees is the maximal possible angle (1 side: 360/2=180, just maths)) + max_angle: 35.0 + + # The maximal number of suspicions a player is allowed to obtain in + # {suspicion_lifespan} milliseconds before being flagged for cheating + threshold: 3 + + # After how many milliseconds* will vel.adr's suspicions be forgotten? + # * [1 second = 1000 milliseconds, 2.5 s = 2500 ms, etc.] + suspicion_lifespan: 7500 + + # Advanced options for component vel.hrz + # + # Checks whether players are being knocked back properly after being hit + # (horizontally — there is a separate, vel.vtl, component for vertical velocity + # monitoring), and if not, teleports them where they should normally be knocked + # back. Being teleported forcefully too often indicates that a player is most + # probably cheating, so when that happens, Reflex adds them a significant number + # of violations so that they are kicked for AntiKnockback soon enough. + # + # Before deciding whether to teleport a player or not, Reflex performs several + # checks, which all add different number of "pre-vl", and then looks how many + # "pre-vls" did a player get during checking. If that number is greater than + # {prevl_threshold}, the player is considered cheating (using Velocity hacks). + # When a player is considered cheating, they are added one suspicion. If that + # player gets more than {threshold} suspicions within {suspicion_lifespan} ms, + # they will be added real AntiKnockback violations, which will later lead to + # them being teleported (forced knockback) or removed from the server. + # + # Accuracy: ★★★☆☆ (3/5 - known to have some false positives in some cases) + # Efficiency: ★★★★★ (5/5 - awesome) + hrz: + + # Maximal allowed number of "pre-vls" a player is allowed to + # score during check before being flagged/teleported/kicked. + prevl_threshold: 3 + + # The maximal number of suspicions a player is allowed to obtain in + # {suspicion_lifespan} milliseconds before being flagged for cheating + threshold: 2 + + # After how many milliseconds* will vel.hrz's suspicions be forgotten? + # * [1 second = 1000 milliseconds, 2.5 s = 2500 ms, etc.] + suspicion_lifespan: 5000 + + # Reflex attempts to predict where players should land after being hit, + # and teleports them there in case they seem to be ignoring server velocity. + # If you want Reflex to simply monitor and kick, without forcing anyone to + # knock back properly, then just enable the "silent" option in config.yml. + forced_knockback: + + # How strongly should Reflex teleport players horizontally? + # 0.0 - teleport to location on hit (no forced knockback). + # Higher values - higher teleport distance. + hor_multiplier: 4.0 + + # How strongly should Reflex teleport players vertically? + # 0.0 - teleport to location on hit (no forced knockback). + # Higher values - higher teleport distance. The overall Y + # teleport distance is limited, see {max_ver_dist} below. + ver_multiplier: 2.0 + + # What's the maximum distance (in blocks) Reflex can teleport players + # vertically? Teleportation is made relatively to player's position ON HIT + # (at the moment when the check started). If the Y distance between that + # location and predicted location (plus {ver_multiplier}) is greater than + # {max_ver_dist} blocks, then the player is only teleported {max_ver_dist} + # blocks vertically. This does not affect horizontal teleportation. + max_ver_dist: 1.7 + + + + +# Advanced VehicleMove options +vehmv: + + # Advanced options for component vehmv.boat + # + # Enfores vanilla boat movement mechanics. Checks fall + # gravity and movement speed and acceleration in order to + # detect BoatFly/BoatSpeed cheats. + # + # Accuracy: ★★★★★ (5/5 - awesome) + # Efficiency: ★★★★★ (5/5 - awesome) + boat: + + # What's the maximal allowed number of blocks a player is allowed to move + # on boat per tick* in normal conditions (still surface or in midair)? + max_normal_speed: 0.52 + + # What's the maximal allowed number of blocks a player is allowed to move + # on boat per tick* on flowing water (waterfalls, flowing streams)? + max_flowing_speed: 0.58 + + # What's the maximal allowed number of blocks a player is allowed to move + # on boat per tick* on ground (yes, it is possible to drive boat like a car + # on ground in Minecraft)? This does cover ice blocks - see options below. + max_ground_speed: 0.26 + + # What's the maximal allowed number of blocks a player is allowed to move + # on boat per tick* on frozen surfaces (ice, packed ice)? NOTE: it is possible + # to use boat like a sportcar on ice in Minecraft - love its physics. + max_ice_speed: 2.08 + + # What's the maximal allowed acceleration (in m/s^2, metres per second square) + # a player is allowed to reach on boat? NOTE: acceleration is basically same in + # any conditions - on (flowing) water, ice, ground and even in midair (partially). + max_acceleration: 0.06 + + # * [1 second = 20 ticks, 2.5 s = 50 ticks, etc.] + + + + +# Advanced ElytraMove options +eltr: + + # Advanced options for component eltr.mv + # + # Enfores vanilla Elytra movement mechanics. Strictly + # limits the direction and speed in which players are + # allowed to move in different situations with Elytra. + # Detects Elytra+/ElytraFly/ElytraSpeed and similar. + # + # Accuracy: ★★★★★ (5/5 - awesome) + # Efficiency: ★★★★★ (5/5 - awesome) + mv: + + # If a player gets teleported back for violating ElytraMove more than + # {setbacks_to_unequip} times within {setback_lifespan} milliseconds*, + # Reflex will forcefully take off their Elytra. See regular config.yml + # for details on "take off". + # + # NOTE: only takes effect if all of the following is true: + # (1) "elytramove.silent" in config.yml is disabled; + # (2) "elytramove.unequip_elytra" in config.yml is enabled (which itself also requires (1) to be true). + # + # * [1 second = 1000 milliseconds, 2.5 s = 2500 ms, etc.] + setbacks_to_unequip: 12 + + # See comment to the above option (`setbacks_to_unequip`). + setback_lifespan: 3000 \ No newline at end of file diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml new file mode 100644 index 0000000..594f73a --- /dev/null +++ b/src/main/resources/config.yml @@ -0,0 +1,1132 @@ +#### Reflex Configuration ############################################## +# +# Welcome here! Looks like you want to change something, am +# I right? Before doing so, please note one thing: all the +# settings were tested a lot to work properly. If Reflex breaks +# after you touched anything, it's YOUR fault. +# +# For any configuration assistance please private message +# DarksideCode on Spigot, open an issue at go.reflex.rip/bug +# or write us in Discord: g.reflex.rip/discord +# +# PLEASE REFRAIN FROM TOUCHING ANYTHING WITHOUT SERIOUS REASONS TO! +# +# Useful links: +# +# 1. Report bugs/false positives/bypasses/console errors/other: +# --> https://g.reflex.rip/contributing +# --> https://g.reflex.rip/bug +# +# 2. Reflex Wiki (information about checks, lag accounting, etc): +# --> https://g.reflex.rip/wiki +# +# 3. Reflex Discord server (quick live support, bug reports, etc): +# --> https://g.reflex.rip/discord +# +# 4. Reflex on Spigot: +# --> https://g.reflex.rip/spigot +# +# With love, Reflex Development Team. +# © reflex.rip, 2016-2019. +# +######################################################################## + + + + +# Should Reflex show how long it takes for its files to download? +# +# PLEASE ENABLE IF YOUR SERVER IS IN ASIA AND TELL US THE RESULTS --> https://g.reflex.rip/discord +# 请启用,如果你的服务器是在中国,并告诉我们的结果 --> https://g.reflex.rip/discord +# サーバーがアジアにある場合は有効にして、結果を教えてください --> https://g.reflex.rip/discord +debug_downloads: false + + +# General plugin settings +general: + + # We have got several servers in different points of the globe to improve performance + # and speed for users who live far away from Europe or experience strange routing (e.g. GFW). + # You can choose one of the following: + # + # auto - determine best server automatically on each startup, according to + # the estimated/tested ping, download speed and routing quality. + # + # eu - our primary server, in Germany. Best for users whose servers are + # either in Europe or in Russia (specifically, in its Western part). + # + # usa_china - our second server, located in the USA. Firstly, it is the best option + # for those whose server is located in the States. Secondly, our American + # server has got DIRECT CHINA ROUTING, which means that all traffic to China + # will go directly, bypassing all third countries like Japan/Hong Kong. + # This means that this option is also good for those whose server is located + # in Asia, e.g. China, Taiwan, Hong Kong, Singapore, Japan, South Korea. + server: 'auto' + + # Should Reflex use SSL secure connections? + # (!) Disable if you are getting "SSL Handshake" errors on startup + use_ssl: true + + # Where should the data files be saved? Data files contain info + # about players banned, different constants & algorithms, etc. + # + # %default_data_folder% will be replaced with '/{your_server_folder}/plugins/Reflex/' + # + # If you have a BungeeCord network on a single VPS, and don't + # want to use MySQL, make sure to specify the same working + # directory for all your servers! + working_directory: '%default_data_folder%' + + # The selected theme dictates the design, the language and the format of all messages + # or their components Reflex sends. You can use one of pre-made themes, or create an + # own one (see the overview page for details). All themes are located in: + # {working_directory}/themes + # (i.e. if you have set the 'working_directory' setting to '/home/server/mc/Reflex', + # then the themes will be located in the '/home/server/mc/Reflex/themes' directory. + # + # If set to %default%, Reflex will pick up an appropriate variant + # of the default theme with the language matching your system locale + theme: '%default%' + + # Reflex can pickup themes individually for each player according + # to their client locale. For example, if a player will join your + # server with client language set to Russian, they will see Reflex's + # messages as in its Russian theme, even if the `theme` setting above + # is set to English. As the number of translations we provide is + # comparably low, some locales are "united" - players whose client + # language is set to Ukrainian or Belarussian will also see messages + # from the Russian locale (since all these languages are similar). + # If a player joins the server with client language that has no + # similar analogues, Reflex will use the language specified in the + # `theme` setting above for them (%default% - server system locale) + personalized_themes: + + # Enable personalized themes? This improves user-experience a lot, + # especially if you have people all over the world playing together. + # If disabled, all players will see Reflex's messages in the language + # specified in the `theme` setting above despite their client locale + enabled: true + + # Reflex themes names are designed in the following format: + # GROUP_locale[-country], + # where "GROUP" is the name of the theme (the set of messages, + # styles and colors), "locale" is the language variant of the + # theme (for example, Reflex's default, "ModernBlue", theme has + # a variety of locales, e.g. "EN", "DE", "IT", etc., which only + # differ in the language the messages are written in). If a + # language has several significantly different variations, + # for example Chinese Traditional and Simplified, "-country" + # is added to the name, where "country" is the code of the country + # the language variation is mainly used in (example: zh-TW, pt-BR). + # + # If personalized themes are enabled, Reflex will look for a + # theme of the group specified in this setting with language + # matching (or being similar to) player's client locale. If + # the specified theme group does not contain any appropriate + # translations, Reflex will use the theme specified in the + # `theme` setting above (%default% - server system locale) + theme_group: 'ModernBlue' + + # For bigger servers, Reflex provides a cloud computings system. + # This will make Reflex work this way: + # (Your Server) Collect data for player and send it to the Cloud -> (Cloud) Process the data, compute results and send back to your server -> (Your Server) Execute commands, etc. + # instead of this: + # (Your Server) Collect data for player, process it, compute results, and then execute commands etc. + # which will be a huge performance boost for your server, since it won't do any of heavy calculations itself. + # Those will be done by Reflex Cloud and returned as a result like "should kick" or "shouldn't kick" (with reasons) + cloud_computings: + + # Defaults to false to avoid getting md_5 triggered + enabled: false + + # Key is required to get access to the Cloud Computings feature. To get the key, + # contact developers on Spigot by PMing DarksideCode. Insert the key you got here + key: 'AAAAAAAAAA-BBBBBBBBBB-CCCCCCCCCC' + + # The maximal amount of reconnection attempts Reflex should + # do before giving up (used in case of getting timed out). + max_reconnections: 5 + + # When Reflex loses connection to Cloud, and is unable to reconnect after + # {max_reconnections} attempts, it gives up reconnecting and loads all the + # checks data and switches to normal mode, performing stuff that was previously + # done by Cloud on your server, just like if Cloud Computings were disabled. + # However, for big servers/networks, it might not be good as then it means that + # Reflex might start using much resources on their servers. If you want Reflex to + # simply disable the Cloud-supported components in case of Cloud inaccessibility, + # set the option below to false. NOTE: THE DISABLED CHECKS WILL NOT WORK UNTIL + # SUCCESSFULLY CONNECTED TO CLOUD, WHICH, AFTER GIVE UP, CAN ONLY BE REACHED BY + # RESTARTING THE SERVER (OR RECONNECTING USING THE REFLEX API, IF POSSIBLE) + auto_switch: true + + # There may be a variety of false positives or other types of issues with + # Reflex in case your server lags/freezes (even if that's just a few moments). + # Reflex implements some own lag-protection features to attempt to solve that. + server_performance_tracking: + + # Enable Reflex's server lag self-protection? (RECOMMENDED!) + enabled: true + + # How often (in milliseconds) (fixed rate) should Reflex check your server for + # lag using its so-called "player-packet-based" server performance tracker? + # + # NOTES: + # + # (1) 1 second contains 1000 milliseconds; e.g. 2.5 s = 2500 ms, etc. + # + # (2) the PP performance tracker works as a separate Java thread without using + # any of the Bukkit's API, which also allows it to [mostly] work even if the + # server is extremely lagging; + # + # (3) the PP performance tracker only works when there are at least 2 online players on the server. + # + # Must be between 50 and 30000, otherwise an error will be thrown and Reflex will not start. + pp_track_freq: 750 + + # If there have been completely no packets from any online players for more than no_pp_trigger + # milliseconds (1 s = 1000 ms, 2.5 s = 2500 ms, etc.) registered by Reflex, a warning will be + # shown in server console, and some Reflex's components will disable until the lag stops. + # + # Every player should normally send at least 10-20 packets per second. + # Must be between 50 and 30000, otherwise an error will be thrown and Reflex will not start. + no_pp_trigger: 150 + + # Reflex uses fixed thread pools for its asynchronous tasks. + # Here you can specify the maximal allowed number of threads Reflex will use. + # This number must be between 1 and 100. Too many threads = CPU overload. Not + # enough threads = checking queues and high outages, especially with Cloud active. + max_thread_count: 5 + + # Should Reflex kick all online players away when the + # server is reloading? Disabling this might cause some + # (or many) reload incompatibility issues + kick_on_reload: true + + # Should Reflex block attempts to join the server before the plugin + # is fully loaded? It is highly recommended to keep this option ENABLED + # in order to prevent various issues with players joined before startup + require_startup_done: true + + # Disable this if you don't want Reflex to log any violations + # at all, neither in the in-game chat, server logs nor console. + # (!) HIGHLY RECOMMENDED: YOU WILL NOT BE SUPPORTED REGARDING + # FALSE POSITIVES OR BYPASSES IF YOU DISABLE THIS OPTION! + verbose: true + + # Disable this if you don't want anyone, even with the neccessary + # permissions, to be able to see Reflex verbose in the game chat + ingame_verbose: true + + # Should Reflex send notification messages + # (the same as with /reflex verbose) in the console? + console_verbose: false + + # Enable verbose on join automatically for all players + # who have got the 'reflex.verbose' permission + verbose_on_connect: false + + # If enabled, Reflex will write verbose messages (the same + # as with /reflex verbose) in special files saved in + # {working_directory}/logs and named in format DD-MM-YYYY.log. + # Reflex makes one log per day. This means one log will contain + # everything happened in a day. 24 hours later, there will be + # a new file created with a new date containing the events of a new day + make_logs: true + + # Should Reflex perform lag accounting when checking? + # Enable this if you want Reflex to adjust violations depending on + # players' Lag Points number. You can learn more about the LP system, + # and about Reflex Lag Accounting system in general, on the overview page + lag_leniency: true + + # Reflex automatically disables or tweaks some components according to + # the server version (1.8 or 1.9+). If you are using some sort of a plugin + # that brings back legacy (1.8) combat mechanics to your 1.9+ server, + # it is recommended to set this setting to true to run more efficiently + force_legacy_mechanics: false + + # Should Reflex's checks' components acquire their settings + # from local Advanced Configuration file (advcfg.yml)? + # + # FOR MORE INFO SEE: + # + # --> https://g.reflex.rip/advcfg + # + # (!) BY ENABLING THIS SETING YOU AGREE TO THE TERMS LISTED ON THE PAGE ABOVE + unlock_advanced_settings: false + + # Annoyed of those friendly welcome messages on startup ("...Thanks for choosing Reflex...")? + # You can easily disable them - just set this option to true. Also disables Moonlight advertisements in console. + disable_welcome_message: false + + # Reflex caches (temporarily stores in RAM) some stuff in order to optimize some of + # its parts or to make it compatible with other plugins. Here you can tweak what + # Reflex should cache (true), and what it shouldn't (false) + caching: + + # Caching of config values is unlikely to be necessary unless you + # have some kind of a custom config reader that overrides Bukkit + # config caching. Disabled by default! + config: false + + # Reflex caches its permissions ("reflex.*") for players in order + # to reduce the number of calls to the permissions system/plugin + permissions: true + + # Reflex caches most of packets and their containers players send + # for around a minute in order to avoid repetitive reading of same + # packets, which can sometimes be very slow. Might take much RAM! + # DON'T ENABLE IF YOU HAVE A BUNGEECORD NETWORK WITH LOTS OF SERVERS! + packets: false + + # /reflex [kick/ban] commands settings + reflex_kick: + + # Should a player be killed if he is getting kicked using /reflex [kick/ban]? + kill: true + + # Should there be a lightning bolt visual effect if + # someone is getting kicked using /reflex [kick/ban]? + strike_lightning: true + + # Should Reflex broadcast a message when someone gets kicked using /reflex [kick/ban]? + broadcast: true + + # This will allow you to implement your own database types and hook + # them with Reflex, so that Reflex will store it's bans and ML data + # in them. By default, MySQL is used. For more info ready the API + # guide on the Reflex overview page on SpigotMC + custom_db: + + # Use custom database? + enabled: false + + # A class that implements DatabaseClient. Used by + # Reflex to connect/disconnect to/from database + client: 'fully.qualified.ClassName' + + # A class that implements DataImpl. Used by + # Reflex to store and load its ML data + data: 'fully.qualified.ClassName' + + # A class that implements BanImpl. Used by + # Reflex to store and laod its bans + ban: 'fully.qualified.ClassName' + + # A class that implements DailyLogFilePublisher. + # Used by Reflex to store its logs + log: 'fully.qualified.ClassName' + + + + +# The Killaura check covers a wide range of combat hacks and +# detects most of unfair combat enhancements such as Killaura, +# Aimbot, some sorts of AimAssist and autoclicker, and more. +killaura: + + # Enable this check? + enabled: true + + # Turn this on if you don't want this check to cancel any illegal actions + silent: false + + # Should Reflex use different cancel thresholds for each check? + # This will result in way more accurate and smart cancel system + dynamic_cancel_thresholds: true + + # If a player exceeds the number of violations below, their next + # suspicious actions will be suspended. Only effective if + # the "dynamic_cancel_thresholds" option is set to false + cancel_threshold: 10 + + # When Reflex cancels hits it belives are illegal it also prevents + # suspected players from attacking any entities for time specified + # in this option (milliseconds, 1 s = 1000 ms). Only effective if the + # `silent` option above is set to false. 0 = no attack penalty + penalty_time: 1500 + + # As of 1.9, players can collide with each other. This means that 1.9+ + # players on 1.8 ViaVersion servers (or on 1.9+ servers) might get moved + # randomly sometimes. This is caused by colliding with Reflex's NPCs. + # Should Reflex make attempts to disable these collisions? + disable_collisions: true + + # Disable this if you're experiencing lots of false + # "entity raytrace" flags (/reflex verbose to see them) + realistic_entityids: true + + # Disable this if you don't want random nametags to be floating around you + realistic_playerdata: true + + # Should Reflex's NPCs work in server's primary thread? + # Enabling this might cause a slight performance impact. + # Disabling this might cause random disconnects on some servers + sync_npcs: false + + # For how long should the NPC behind the player be visible + # after attack (millis)? Set to -1 to make it always invisible + npc_visibility_time: 3250 + + # If a player is not fighting for this number of milliseconds, their + # NPCs will move far away unless they are back to combat. Useful to + # stop Reflex from interrupting world interaction with its bots. + # Set this to -1 to always keep the NPCs near players. + npc_max_nocombat: 2900 + + # Reflex can take snapshots of players' behaviour that gets + # passed to the machine learning check and either save those + # to files or send them to other plugins using Reflex API. + # + # (!) NOT FOR NORMAL USE! Only tweak if you were asked to by us. + # + # How should the debug files be created? + # + # 0 - do not create any, and do not fire any events. + # No heuristics debugging desired (default). + # + # 1 - do not create any, but fire special events that will allow + # other plugins to handle debug files creation using Reflex API. + # + # 2 - create debug files all the time, both classified "legit" and "hacks". + # WARNING: might create A LOT of, possibly UNNECESSARY, files! + # + # 3 - only create debug files for behaviour classified as "legit". + # Useful when reporting bypasses. + # + # 4 - only create debug files for behaviour classified as "hacks". + # Useful when reporting false positives. + # + # (i) NOTE: levels higher than 1 will still fire the API events. + # Please note than enabling this might slow the ML check down significantly + debug_heuristics: 0 + + # How strict should the machine learning check be? + # + # 0 - detects many "legit-like" Aimbot/AimAssist hacks. + # Extremely unstable, might cause lots of false kicks. + # + # 1 - < RECOMMENDED ! > detects most combat cheats which give + # hacker either slight or significant unfair advantage. + # A few rare false positives may sometimes occur. + # + # 2 - only detects obvious Killaura and Aimbot hacks, + # though with minimal number of false positives. + # + # (!) Severity of 1 is pretty stable and is HIGHLY recommended. + # + # If you don't really care about bypasses, and just want + # obviously unfair cheats to be detected with as small + # number of false positives as possible, use severity of 2 + heuristics_severity: 1 + + # Here you can put a list of checks you don't wish to use for some reason. + # + # WARNING: IT IS HIGHLY RECOMMENDED THAT YOU REPORT BUGS AT go.reflex.rip/bug + # INSTEAD OF JUST DISABLING CHECKS, AS FIRST WILL RESULT IN THESE + # GETTING FIXED. IF YOU PREFER TO JUST DISABLE SOMETHING WITHOUT + # REPORTING THE ISSUES, YOU MUST NOT COMPLAIN ABOUT BYPASSES! + # + # The names of all the KillAura components can be found on our wiki: https://g.reflex.rip/wiki + disabled_checks: + - "example entry" + + # List of worlds where Reflex will not check anyone for KillAura + disabled_worlds: + - "lobby" + + # Command map + actions: + 35: + - "reflex bypass %player% %check% true" + - "reflex delay 15 reflex kick %player% + &fYou were just kicked.%break% + &fReason: &b&lDETECTED FOR CHEATING&r%break% + %break% + &r&cIf you believe that this is a false positive,%break% + &cplease contact server administrators.&r%break% + %break% + &7Kick ID: &f%id%%break% + &7%date%" + + + + +# The BadPackets check validates all packets sent by players +# to ensure that they are legit and were supposed to be sent. +# Detects an extremely wide range of various cheat types. +# +# (!) NOTE #1: this check DOES NOT replace BadPacket checks in other +# anticheats, and those do not replace this one. Reflex's +# BadPackets is supposed to be used TOGETHER with BadPackets +# in some other anticheat(s). +# +# (i) NOTE #2: this check covers many possible/potential/existing bypasses +# of other checks, thus patching many types of cheats, including +# Killaura, Scaffold, PingSpoof, etc. If you are wondering do +# you need Reflex's BadPackets or not, the answer is definite: +# YES, no matter what other anticheat(s) you are using. +badpackets: + + # Enable this check? + # < !!! RECOMMENDED !!! > + enabled: true + + # Turn this on if you don't want this check to cancel any illegal actions + silent: false + + # Should Reflex use different cancel thresholds for each check? + # This will result in way more accurate and smart cancel system + dynamic_cancel_thresholds: true + + # If a player exceeds the number of violations below, their next + # suspicious actions will be suspended. Only effective if + # "dynamic_cancel_thresholds" is set to false + cancel_threshold: 1 + + # There are cheats/modifications that allow players to slow down ticking speed of + # their client (we refer those to as "Reverse Timers" since they're basically the + # opposite thing to normal "Timers", but slow everything down instead of speeding up). + # Using those, cheaters are able to make anticheats believe they are lagging and abuse + # some stuff to make them fall down way slower than usual. With some small tweaking and + # rare midair boosts, this results in 10-20-blocks "Glide" bypasses for several popular + # anticheats. Reflex can fix that. Enabling this check tells Reflex to drag players down + # a few blocks each time they make a comparably distant move in midair while lagging. + midair_lag_dragdown: true + + # Here you can put a list of checks you don't wish to use for some reason. + # + # WARNING: IT IS HIGHLY RECOMMENDED THAT YOU REPORT BUGS AT go.reflex.rip/bug + # INSTEAD OF JUST DISABLING CHECKS, AS FIRST WILL RESULT IN THESE + # GETTING FIXED. IF YOU PREFER TO JUST DISABLE SOMETHING WITHOUT + # REPORTING THE ISSUES, YOU MUST NOT COMPLAIN ABOUT BYPASSES! + # + # The names of all the BadPackets components can be found on our wiki: https://g.reflex.rip/wiki + disabled_checks: + - "example entry" + + # List of worlds where Reflex will not check anyone for BadPackets + disabled_worlds: + - "lobby" + + # Command map + actions: + 5: + - "reflex bypass %player% %check% true" + - "reflex delay 15 reflex kick %player% + &fYou were just kicked.%break% + &fReason: &b&lDETECTED FOR CHEATING&r%break% + %break% + &r&cIf you believe that this is a false positive,%break% + &cplease contact server administrators.&r%break% + %break% + &7Kick ID: &f%id%%break% + &7%date%" + + + + +# The Criticals check prevents players from doing critical hits when it isn't technically possible. +# Most Critical hacks are already patched by Reflex's KillAura check. This check aims to detect some +# potential "packet-criticals" bypasses. +# +# (i) NOTE: Reflex MAY NOT detect "mini-jump" Criticals. Those are something that should be patched +# by a movement anticheat, so if you are using one, trust this type of hack to it. We still +# recommend you to keep this check enabled, though. +criticals: + + # Enable this check? + enabled: true + + # Turn this on if you don't want this check to cancel any illegal actions + silent: false + + # Should Reflex use different cancel thresholds for each check? + # This will result in way more accurate and smart cancel system + dynamic_cancel_thresholds: true + + # If a player exceeds the number of violations below, their next + # suspicious actions will be suspended. Only effective if + # "dynamic_cancel_thresholds" is set to false + cancel_threshold: 1 + + # Here you can put a list of checks you don't wish to use for some reason. + # + # WARNING: IT IS HIGHLY RECOMMENDED THAT YOU REPORT BUGS AT go.reflex.rip/bug + # INSTEAD OF JUST DISABLING CHECKS, AS FIRST WILL RESULT IN THESE + # GETTING FIXED. IF YOU PREFER TO JUST DISABLE SOMETHING WITHOUT + # REPORTING THE ISSUES, YOU MUST NOT COMPLAIN ABOUT BYPASSES! + # + # The names of all the Criticals components can be found on our wiki: https://g.reflex.rip/wiki + disabled_checks: + - "example entry" + + # List of worlds where Reflex will not check anyone for Criticals + disabled_worlds: + - "lobby" + + # Command map + actions: + 18: + - "reflex bypass %player% %check% true" + - "reflex delay 15 reflex kick %player% + &fYou were just kicked.%break% + &fReason: &b&lDETECTED FOR CHEATING&r%break% + %break% + &r&cIf you believe that this is a false positive,%break% + &cplease contact server administrators.&r%break% + %break% + &7Kick ID: &f%id%%break% + &7%date%" + + + + +# The BlockActions check handles basically everything related to block +# breaking/placement and prevents hackers from using Scaffold and Tower hacks. +blockactions: + + # Enable this check? + enabled: true + + # Turn this on if you don't want this check to cancel any illegal actions + silent: false + + # Should Reflex use different cancel thresholds for each check? + # This will result in way more accurate and smart cancel system + dynamic_cancel_thresholds: true + + # If a player exceeds the number of violations below, their next + # suspicious actions will be suspended. Only effective if + # "dynamic_cancel_thresholds" is set to false + cancel_threshold: 10 + + # When Reflex cancels block placements it belives are illegal it also + # prevents suspected players from placing any blocks for time specified + # in this option (milliseconds, 1 s = 1000 ms). Only effective if the + # `silent` option above is set to false. 0 = no build penalty + penalty_time: 3000 + + # Here you can put a list of checks you don't wish to use for some reason. + # + # WARNING: IT IS HIGHLY RECOMMENDED THAT YOU REPORT BUGS AT go.reflex.rip/bug + # INSTEAD OF JUST DISABLING CHECKS, AS FIRST WILL RESULT IN THESE + # GETTING FIXED. IF YOU PREFER TO JUST DISABLE SOMETHING WITHOUT + # REPORTING THE ISSUES, YOU MUST NOT COMPLAIN ABOUT BYPASSES! + # + # The names of all the BlockActions components can be found on our wiki: https://g.reflex.rip/wiki + disabled_checks: + - "example entry" + + # List of worlds where Reflex will not check anyone for BlockActions + disabled_worlds: + - "lobby" + + # Command map + actions: + 30: + - "reflex bypass %player% %check% true" + - "reflex delay 15 reflex kick %player% + &fYou were just kicked.%break% + &fReason: &b&lDETECTED FOR CHEATING&r%break% + %break% + &r&cIf you believe that this is a false positive,%break% + &cplease contact server administrators.&r%break% + %break% + &7Kick ID: &f%id%%break% + &7%date%" + + + + +# The InvActions check prevents players from doing technically impossible +# inventory actions such as moving with open inventory, clicking too quickly, and other. +invactions: + + # Enable this check? + enabled: true + + # Turn this on if you don't want this check to cancel any illegal actions + silent: false + + # Should Reflex use different cancel thresholds for each check? + # This will result in way more accurate and smart cancel system + dynamic_cancel_thresholds: true + + # If a player exceeds the number of violations below, their next + # suspicious actions will be suspended. Only effective if + # "dynamic_cancel_thresholds" is set to false + cancel_threshold: 5 + + # Prevents from walking and rotating while inventory is opened. + # Detects InvWalk and some AutoArmor/Killaura hacks + block_movement: true + + # Here you can put a list of checks you don't wish to use for some reason. + # + # WARNING: IT IS HIGHLY RECOMMENDED THAT YOU REPORT BUGS AT go.reflex.rip/bug + # INSTEAD OF JUST DISABLING CHECKS, AS FIRST WILL RESULT IN THESE + # GETTING FIXED. IF YOU PREFER TO JUST DISABLE SOMETHING WITHOUT + # REPORTING THE ISSUES, YOU MUST NOT COMPLAIN ABOUT BYPASSES! + # + # The names of all the InvActions components can be found on our wiki: https://g.reflex.rip/wiki + disabled_checks: + - "example entry" + + # List of worlds where Reflex will not check anyone for InvActions + disabled_worlds: + - "lobby" + + # Command map + actions: + 25: + - "reflex bypass %player% %check% true" + - "reflex delay 15 reflex kick %player% + &fYou were just kicked.%break% + &fReason: &b&lDETECTED FOR CHEATING&r%break% + %break% + &r&cIf you believe that this is a false positive,%break% + &cplease contact server administrators.&r%break% + %break% + &7Kick ID: &f%id%%break% + &7%date%" + + + + +# The AntiKnockback check forces players to move away when they are getting attacked +# properly. Detects "full" knockback ignorance, "Small Knockback" and "Reverse Knockback". +# This check also forbids players to change their movement direction in midair, which also +# detects many Bhop/Strafe cheats, among with a few other movement ones. +antiknockback: + + # Enable this check? + enabled: true + + # Turn this on if you don't want this check to cancel any illegal actions + silent: false + + # Should Reflex use different cancel thresholds for each check? + # This will result in way more accurate and smart cancel system + dynamic_cancel_thresholds: true + + # If a player exceeds the number of violations below, their next + # suspicious actions will be suspended. Only effective if + # "dynamic_cancel_thresholds" is set to false + cancel_threshold: 5 + + # Here you can put a list of checks you don't wish to use for some reason. + # + # WARNING: IT IS HIGHLY RECOMMENDED THAT YOU REPORT BUGS AT go.reflex.rip/bug + # INSTEAD OF JUST DISABLING CHECKS, AS FIRST WILL RESULT IN THESE + # GETTING FIXED. IF YOU PREFER TO JUST DISABLE SOMETHING WITHOUT + # REPORTING THE ISSUES, YOU MUST NOT COMPLAIN ABOUT BYPASSES! + # + # The names of all the AntiKnockback components can be found on our wiki: https://g.reflex.rip/wiki + disabled_checks: + - "example entry" + + # List of worlds where Reflex will not check anyone for AntiKnockback + disabled_worlds: + - "lobby" + + # Command map + actions: + 7: + - "reflex bypass %player% %check% true" + - "reflex delay 15 reflex kick %player% + &fYou were just kicked.%break% + &fReason: &b&lDETECTED FOR CHEATING&r%break% + %break% + &r&cIf you believe that this is a false positive,%break% + &cplease contact server administrators.&r%break% + %break% + &7Kick ID: &f%id%%break% + &7%date%" + + + + +# The VehicleMove check prevents players from moving impossibly on +# vehicles, which detects a variety of cheats, including BoatFly and +# BoatSpeed. NOTE: all vehicle cheats, and hence the check, only work +# on Minecraft 1.9 or newer. No BoatFly threats on 1.8. +vehiclemove: + + # Enable this check? + enabled: true + + # Turn this on if you don't want this check to cancel any illegal actions + silent: false + + # Should Reflex use different cancel thresholds for each check? + # This will result in way more accurate and smart cancel system + dynamic_cancel_thresholds: true + + # If a player exceeds the number of violations below, + # all their next suspicious actions will be suspended + cancel_threshold: 4 + + # Here you can put a list of checks you don't wish to use for some reason. + # + # WARNING: IT IS HIGHLY RECOMMENDED THAT YOU REPORT BUGS AT go.reflex.rip/bug + # INSTEAD OF JUST DISABLING CHECKS, AS FIRST WILL RESULT IN THESE + # GETTING FIXED. IF YOU PREFER TO JUST DISABLE SOMETHING WITHOUT + # REPORTING THE ISSUES, YOU MUST NOT COMPLAIN ABOUT BYPASSES! + # + # The names of all the VehicleMove components can be found on our wiki: https://g.reflex.rip/wiki + disabled_checks: + - "example entry" + + # List of worlds where Reflex will not check anyone for VehicleMove + disabled_worlds: + - "lobby" + + # Command map + actions: + 10: + - "reflex bypass %player% %check% true" + - "reflex delay 15 reflex kick %player% + &fYou were just kicked.%break% + &fReason: &b&lDETECTED FOR CHEATING&r%break% + %break% + &r&cIf you believe that this is a false positive,%break% + &cplease contact server administrators.&r%break% + %break% + &7Kick ID: &f%id%%break% + &7%date%" + + + + +# The ElytraMove check strictly limits Elytra movement of players, thus attempting +# to enforce vanilla Elytra movement/gliding/flying mechanics and detecting cheats +# like Elytra+/ElytraFly/ElytraSpeed and related. +elytramove: + + # Enable this check? + enabled: true + + # Turn this on if you don't want this check to cancel any illegal actions + silent: false + + # Should Reflex use different cancel thresholds for each check? + # This will result in way more accurate and smart cancel system + dynamic_cancel_thresholds: true + + # If a player exceeds the number of violations below, + # all their next suspicious actions will be suspended + cancel_threshold: 5 + + # Should Reflex forcefully take off* elytra from players who appear to be + # very suspicious (i.e. when they are continuing to get new violations even + # after being teleported back by Reflex many times)? + # + # (i) RECOMMENDED - this may help to avoid legitimate players getting kicked + # in some unusual/strange cases by this check. + # + # Has no effect if "silent" is set to "true", since in that case Reflex will + # do no setbacks, and therefore no unequips. + # + # * [Reflex will remove Elytra from player's chestplate slot and copy the item + # deeply (with all metadata, durability and everything else) in their inventory, + # if there is enough space, or drop it beneath player's feet otherwise.] + unequip_elytra: true + + # Here you can put a list of checks you don't wish to use for some reason. + # + # WARNING: IT IS HIGHLY RECOMMENDED THAT YOU REPORT BUGS AT go.reflex.rip/bug + # INSTEAD OF JUST DISABLING CHECKS, AS FIRST WILL RESULT IN THESE + # GETTING FIXED. IF YOU PREFER TO JUST DISABLE SOMETHING WITHOUT + # REPORTING THE ISSUES, YOU MUST NOT COMPLAIN ABOUT BYPASSES! + # + # The names of all the VehicleMove components can be found on our wiki: https://g.reflex.rip/wiki + disabled_checks: + - "example entry" + + # List of worlds where Reflex will not check anyone for ElytraMove + disabled_worlds: + - "lobby" + + # Command map + actions: + 240: + - "reflex bypass %player% %check% true" + - "reflex delay 15 reflex kick %player% + &fYou were just kicked.%break% + &fReason: &b&lDETECTED FOR CHEATING&r%break% + %break% + &r&cIf you believe that this is a false positive,%break% + &cplease contact server administrators.&r%break% + %break% + &7Kick ID: &f%id%%break% + &7%date%" + + + + +# The ClientControl check allows you to disable certain feature +# of certain mods, or disallow joining with them at all. +# +# NOTE: disabled by default because servers usually do not +# want to have this sort of check. It is still stable +# and it is safe to use it if you need or want to. +clientcontrol: + + # Enable this check? + enabled: false + + # Your staff members (players with the reflex.notify permission) will + # receive notifications when a player joins with a modded client + notifications: + + # Enable notifications? + enabled: false + + # Notification message. %mod% will be replaced with the name of detected client modification. + # Normal placeholders (which can be used in actions of other checks) are also applicable here + message: '&9%player% &ris using &9%mod%' + + # This will disallow joining the server with any client which's + # brand is not vanilla. Note that this does NOT and can NOT + # block hacked clients as clientbrand of those is actually "vanilla". + # However, this will decrease the chance of players using ghost or + # injectable clients based on coremods on your server + paranoid_mode: + + # Enable? Only enable this if you know what you're doing. + # You're forbidding your players to use most of mods and (legit) non-vanilla clients + enabled: false + + # Paranoid Mode suspends clients which's brand is + # not in this list from joining your server + whitelist: + - "vanilla" + - "vanilla/squidhq" + + # Commands that will be dispatched if any modifications + # have been detected on a player's client + actions: + - "kick %player% &cAccess denied.%break%%break%&rBlacklisted modifications detected.%break%&rNote that FML and LiteLoader are also forbidden.&r%break%%break% &7Kick ID: &f%id%%break%&7%date%" + + # 5zig is a mod that enhances the client by adding some more additional + # features to it, such as GUIs, CPS/FPS ingame statistics and more: + # http://5zig.net + # 5zig allows to disable its certain features + 5zig: + + # Should players be allowed to join the server with this mod? + allow_join: true + + # Which components of 5zig shall Reflex disable? + # true - disable the component, false - let the component be active + disable: + + # Draws active potions list on the screen + potion_effect_hud: true + + # Draws a specific vignette (a visual effect at the corners + # of the screen) of a different color according to the currently + # active potion (acts like a potion effect indicator) + potion_vignette: true + + # Draws the armor player is currently wearing, + # on the screen with it's actual durability + armor_hud: true + + # Renders players saturation scale under their nametags + render_saturation: true + + # Renders players health scale under their nametags + render_health: true + + # Reconnects to the server automatically after kick + auto_reconnect: true + + # If allow_join is set to false, these commands will be + # dispatched when a player joins with 5zig + actions: + - "kick %player% &cAccess denied.%break%&rBlacklisted modifications detected: &b&l5zig&r%break%%break% &7Kick ID: &f%id%%break%&7%date%" + + # BetterSprinting is a mod that enhances sprinting behaviour: + # https://minecraft.curseforge.com/projects/better-sprinting + # BSM allows to disable itself + better_sprinting: + + # Should players be allowed to join the server with this mod? + allow_join: true + + # Should Reflex disable BetterSprinting? + disable: true + + # If allow_join is set to false, these commands will be + # dispatched when a player joins with BetterSprinting + actions: + - "kick %player% &cAccess denied.%break%&rBlacklisted modifications detected: &b&lBetterSprinting&r%break%%break% &7Kick ID: &f%id%%break%&7%date%" + + # WorldDownloader lets the client download your server map: + # http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/2520465 + # WDL allows to disable itself on your server + world_downloader: + + # Should players be allowed to join the server with this mod? + allow_join: false + + # Should Reflex disable WorldDownloader? + disable: true + + # If allow_join is set to false, these commands will be + # dispatched when a player joins with WorldDownloader + actions: + - "kick %player% &cAccess denied.%break%&rBlacklisted modifications detected: &b&lWorldDownloader&r%break%%break% &7Kick ID: &f%id%%break%&7%date%" + + # The Minecraft mod API and loader most mods are based on: + # http://www.minecraftforge.net + # Cannot be disabled, but can be detected + forge: + + # Should players be allowed to join the server with this mod? + allow_join: true + + # If allow_join is set to false, these commands will be + # dispatched when a player joins with Forge + actions: + - "kick %player% &cAccess denied.%break%&rBlacklisted modifications detected: &b&lForge&r%break%%break% &7Kick ID: &f%id%%break%&7%date%" + + # A lightweight Minecraft mod API and loader: + # http://www.liteloader.com + # Cannot be disabled, but can be detected + liteloader: + + # Should players be allowed to join the server with this mod? + allow_join: true + + # If allow_join is set to false, these commands will be + # dispatched when a player joins with LiteLoader + actions: + - "kick %player% &cAccess denied.%break%&rBlacklisted modifications detected: &b&lLiteLoader&r%break%%break% &7Kick ID: &f%id%%break%&7%date%" + + # Includes several game modifications that may heavily + # enhance vanilla Minecraft giving user unfair advantages. + # Several parts of BetterPVP can be blocked or detected + betterpvp: + + # Should players be allowed to join the server with this mod? + allow_join: true + + # Which components of BetterPVP shall Reflex disable? + # true - disable the component, false - let the component be active + disable: + + # Displays a minimap with player radar in the corner of the screen + minimap: true + + # Displays current armor info on the screen + armor_status: true + + # Displays current potion info on the screen + potion_status: true + + # Displays current archery info on the screen + archery_status: true + + # Enhances sprinting behaviour + better_sprint: true + + # Enhances sneaking behaviour + toggle_sneak: true + + # Allows player to use items faster + quick_item_use: true + + # Notifies player about nearby TNTs + tnt_notifications: true + + # Draws marks showing where did the player die last time + death_points: true + + # Displays entity infos on the screen + entity_info: true + + # If allow_join is set to false, these commands will be + # dispatched when a player joins with BetterPVP + actions: + - "kick %player% &cAccess denied.%break%&rBlacklisted modifications detected: &b&lBetterPVP&r%break%%break% &7Kick ID: &f%id%%break%&7%date%" + + # A mod that lets the player to save and load schematics: + # https://minecraft.curseforge.com/projects/schematica + # Schematica allows to disable its certain parts, but can't be detected + schematica: + + # Which components of Schematica shall Reflex disable? + # true - disable the component, false - let the component be active + disable: + + # Building bot based on the given schematica + printer: true + + # Similar to WorldDownloader, but with limited region size + save: true + + # Loads one of saved schematics and prepares it for use + load: true + + # Vape is one of the most popular Minecraft ghost clients which was leaked with a backdoor + # allowing the server know about its use. NOTE: this does not detect real (uncracked) Vape! + vape: + + # Should players be allowed to join the server with this mod? + allow_join: false + + # If allow_join is set to false, these commands will be + # dispatched when a player joins with cracked Vape + actions: + - "reflex ban %player% -1 &cAccess denied.%break%&rBlacklisted modifications detected: &b&lVape&r%break%%break% &7Kick ID: &f%id%%break%&7%date%" + + # A Minecraft client with a variety of built-in modifications: + # https://client.badlion.net/ + # Badlion Client allows to disable its certain parts, but can't be detected. + # If you want Reflex to disable certain parts of the Badlion Client for users, + # make sure to configure the 'blc_config.json' file which can be found in + # Reflex's working directory. If you don't want Reflex to do anything with + # users running Badlion Client, simply set this option to false + badlion_client_support: true + + # Command map (unused) + actions: {} + + + + +#### Reflex Moonlight Configuration #################################### +# +# Reflex has also got an extended version with more cool extra +# features, which was named "Moonlight" for completely no specific +# reasons. Here you can customize the Moonlight stuff. +# +# Learn more about Reflex Moonlight: +# --> https://g.reflex.rip/moonlight +# +######################################################################## +moonlight: + + # Insert your Moonlight (NOT CLOUD!) key here in order to activate Moonlight. + # Learn more: https://g.reflex.rip/moonlight + key: 'insert your key here' + + # Should Reflex attempt to mask itself (create the feeling of non-presence) + # from non-OP (regular) players? If so, how should it do that? Allowed values: + # + # no - do not hide Reflex. (default) + # + # command - print the default Spigot unknown command message (usually from spigot.yml) + # to users who type "/reflex" without OP permissions. + # + # deep - similar to 'command', but also disables tab-complete for "/reflex" command + # for players without OP permissions. + # + # Please note that no matter what you choose, there are always ways to find out which + # anticheat(s) a server is using because all anticheats behave differently. This also + # won't enhance your server security at all. A proper anticheat will never be bypassed + # just because a hacker knows it is being used (and Reflex is one of those). + hide_reflex: 'no' diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..06853cf --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,90 @@ +################################################################################## +# +# Hello, +# +# Please do not change anything in Reflex's plugin.yml (this file). +# Modifying it may lead to unexpected plugin behavior of any kind, including +# random console errors, checks not working [properly], etc. +# +# Contact us if you have any questions. (Discord: https://g.reflex.rip/discord) +# +# With love, Reflex Development Team. +# © reflex.rip, 2016-2019. +# +################################################################################## + + +name: Reflex +main: rip.reflex.Reflex +version: 10.10-2-56528ba +authors: [DarksideCode, sinnlosername] +softdepend: [ProtocolLib, LibsForPaper, ReflexMoonlightLibs, PlaceholderAPI] +description: The next generation cheat elimination +website: https://g.reflex.rip/spigot +api-version: 1.13 +commands: + reflex: + description: Reflex commands +permissions: + reflex.command.reflex: + default: true + reflex.command.help: + default: op + reflex.command.kick: + default: op + reflex.command.ban: + default: op + reflex.command.unban: + default: op + reflex.command.verbose: + default: op + reflex.command.delay: + default: op + reflex.command.broadcast: + default: op + reflex.command.reload: + default: op + reflex.command.setdb: + default: op + reflex.command.notify: + default: op + reflex.command.tps: + default: op + reflex.command.bypass: + default: op + reflex.command.timings: + default: op + reflex.command.debug: + default: op + reflex.command.reset: + default: op + reflex.command.dump: + default: op + reflex.command.packetdebug: + default: op + reflex.verbose: + default: op + reflex.notify: + default: op + reflex.bypass: + default: false + reflex.bypass.killaura: + default: false + reflex.bypass.criticals: + default: false + reflex.bypass.badpackets: + default: false + reflex.bypass.antiknockback: + default: false + reflex.bypass.blockactions: + default: false + reflex.bypass.clientcontrol: + default: false + reflex.bypass.invactions: + default: false + reflex.bypass.speed: + default: false + reflex.bypass.vehiclemove: + default: false + reflex.bypass.elytramove: + default: false \ No newline at end of file