Compare commits

...
74 Commits
Author SHA1 Message Date
retrooper ba72ec37c6 Final 1.6.9 release 2020-09-20 10:40:35 +02:00
retrooper 9bfb696c9d 1.6.9 RELEASE 2020-09-20 10:37:06 +02:00
retrooper 4a9848f51d added java docs building to pom.xml 2020-09-20 10:22:49 +02:00
retrooper 383eacc814 PacketEvents 1.6.8.5 (1.6.9 5th pre release)
* Auto updater fully functioning
2020-09-20 10:18:01 +02:00
retrooper 860b80e2c2 PacketEvents 1.6.8.4(1.6.9 4th pre release)
* PacketEvents version reporting(if newer exists,you are on current latest, or a dev/pre released is what you are on)
2020-09-19 20:02:58 +02:00
retrooper 0259bc8d9d Progress on WrappedPacketOutPlayerInfo to add NPC support and make it possible with PacketEvents. 2020-09-19 12:04:42 +02:00
retrooper 37238e1226 WrappedPacketOutCustomPayload tested to work on 1.7.10, 1.8.8, and 1.16.3, it is assumed that the other versions work too.
* 1.8.8+ reflection issues fixed
2020-09-19 10:53:08 +02:00
retrooper c51880941b WrappedPacketOutCustomPayload bug when sending on 1.7.10 FIXED,
Sending the packet works just fine,

just about to test listening to it.
2020-09-18 17:24:38 +02:00
retrooper 451bbe7597 import error fix 2020-09-18 15:10:21 +02:00
retrooper d99e20d95e dev commit,
progress on WrappedPacketOutCustomPayload,sending should work on 1.7.10 and 1.8, unsure about 1.16, listening not supported yet

TODO: add javadoc thing in the maven thingy
2020-09-18 15:09:16 +02:00
retrooper 5eca22a9df 1.6.9 pre release 2
* Packet receive/send events not being called on second join FIX, caused by me not caching channel correctly in an optimization attempt
2020-09-18 10:37:44 +02:00
retrooper c4d6b26986 1.6.8 pre 1 (version 1.6.8.1)
* ClientVersion recoded, ClientVersion#isHigherThan(ClientVersion) and ClientVersion#isLowerThan(ClientVersion) comparisons should be much faster now
2020-09-17 15:42:09 +02:00
retrooper 197acc4d2f Merge pull request #44 from LIWKK/patch-9
Small fix
2020-09-17 14:51:42 +02:00
Johannes da5a5cf15a Small fix 2020-09-17 15:47:26 +03:00
retrooper 0797df24d2 Merge pull request #42 from LIWKK/patch-7
Fixed error i just made
2020-09-17 14:47:16 +02:00
retrooper 7fca4ac8d6 Merge pull request #41 from LIWKK/patch-6
Wrong protocolversion fix. Added 1.16.3
2020-09-17 14:46:55 +02:00
retrooper 0516513c67 Merge pull request #43 from LIWKK/patch-8
Added 1.16.3
2020-09-17 14:46:35 +02:00
Johannes 4603794436 Added 1.16.3 2020-09-17 15:44:38 +03:00
Johannes a5bbe4047b Fixed error i just made 2020-09-17 15:43:37 +03:00
Johannes 770a2d3287 Wrong protocolversion fix. Added 1.16.3 2020-09-17 15:42:23 +03:00
retrooper 3bd4b82d94 Merge pull request #40 from NikV2/master
Added update checker
2020-09-16 20:48:15 +02:00
retrooper 218b2d7782 Merge branch 'master' into master 2020-09-16 20:48:06 +02:00
Nik 76a08e6c12 Fix 2020-09-16 21:38:03 +03:00
Nik 4d28a58dcb Added update checker 2020-09-16 21:31:13 +03:00
retrooper 9347e7a133 1.6.8 STABLE release 2020-09-16 20:00:10 +02:00
retrooper 33ed5ff904 * WrappedPacketInUpdateSign issue fixed for versions > than 1.8.8
* WrappedPacket#readObjectArray() bug fix and for all other ones
2020-09-16 19:16:21 +02:00
retrooper 291994d388 * WrappedPacketInUpdateSign created, UNTESTED 2020-09-16 18:14:51 +02:00
retrooper f6ea9675bf * clearing the cached channel after the player is uninjected. 2020-09-16 17:51:17 +02:00
retrooper cc303f56a4 * a few API class movements.
* PacketEvents.getAPI().getPlayerUtils().sendPacket(Player, SendableWrapper) optimized, we no longer use reflection to send packets and we cache the channel.
2020-09-16 17:33:23 +02:00
retrooper 290bd0a8fe * nullpointer exception fixed for versions older than 1.16 in WrappedPacketOutGameStateChange 2020-09-16 16:58:40 +02:00
retrooper a8573cc8e1 * game state change nullpointer exception for 1.16 fixed 2020-09-16 16:10:53 +02:00
retrooper 814bd941c0 * outbound game state change wrapper should be working for 1.16 now, I'm about to test it 2020-09-16 15:18:32 +02:00
retrooper d3f6d32848 gamestate wrapper unfinished, need to get the value from the integer for 1.16
* todo: finish outbound game state change wrapper, outbound custompayload, outbound entitymetadata, fix alleged 1.16 performance issues
2020-09-15 23:14:24 +02:00
retrooper 5e1b82ea8a *game state wrapper attempt, UNTESTED 2020-09-15 18:00:58 +02:00
retrooper e49cae5d67 * added the setting to disable packetevents from using the ProtocolLib API if it is available,
(PacketEvents.getAPI().getSettings().setUseProtocolLibIfAvailable(boolean), default value = true)

* PacketEvents.getAPI().getSettings().isInjectAsync()
& PacketEvents.getAPI().getSettings().isUninjectAsync() are NOW set to true by default
2020-09-15 16:46:51 +02:00
retrooper 8168bb2085 Update README.md 2020-09-13 11:57:55 +02:00
retrooper 621a7c98b9 Merge pull request #38 from LIWKK/patch-5
Removed debugs
2020-09-13 11:09:22 +02:00
retrooper 28da2aafc4 Merge pull request #39 from LIWKK/patch-4
Remove debugs
2020-09-13 11:08:33 +02:00
Johannes e89e6fac28 Removed debugs 2020-09-13 12:06:50 +03:00
Johannes a5e067af9e Remove debugs 2020-09-13 12:05:56 +03:00
retrooper 04de7fd5ea Merge pull request #37 from funkemunky/feature/reflection-caching
Optimized reflection, fixed WrappedPacketInFlying error
2020-09-13 06:54:10 +02:00
Dawson Hessler 815428f35b reverting version change 2020-09-13 00:43:59 -04:00
Dawson Hessler 833f569150 Optimized reflection, fixed WrappedPacketInFlying error 2020-09-13 00:43:08 -04:00
retrooper 6b227d55aa Update WrappedPacket.java 2020-09-13 00:05:11 +02:00
retrooper 57a6c26c07 attempt to fix all errors when accessing fields 2020-09-12 23:53:14 +02:00
retrooper b2da168f6a attempt to fix fields not being found 2020-09-12 23:41:55 +02:00
retrooper 4c1e14af57 subclass util bug fixed omg 2020-09-12 23:28:56 +02:00
retrooper 5f9e82617f Update WrappedPacketInUseEntity.java 2020-09-12 23:24:50 +02:00
retrooper 9868facdde debug added cos idk why its failing 2020-09-12 22:51:24 +02:00
retrooper d45f8bddac packet class for use entity null fix attempt 2020-09-12 22:21:12 +02:00
retrooper e4b086e7e5 packet class null fix attempt 2020-09-12 22:20:07 +02:00
retrooper 7afe3c63cd fix packettype import for packetsendevent 2020-09-12 22:08:18 +02:00
retrooper 5103acf414 fix packettype import for packetreceiveevent 2020-09-12 22:07:52 +02:00
retrooper 70b763b5a3 Merge remote-tracking branch 'origin/master' into master 2020-09-12 20:53:39 +02:00
retrooper e1370b803f removed old packettype class 2020-09-12 20:53:15 +02:00
retrooper ac3ca0ddf7 Update WrappedPacketInUseEntity.java 2020-09-12 20:31:29 +02:00
retrooper 15bec5525a nms import removed 2020-09-12 18:21:03 +02:00
retrooper 0e8dcb6a40 nms import removed 2020-09-12 18:18:49 +02:00
retrooper 836efcfa03 forgot to load the updated PacketType class, and not only the deprecated one 2020-09-12 18:12:43 +02:00
retrooper 774e6decf3 debug added to see why it fails at line 94 2020-09-12 18:03:54 +02:00
retrooper 839265e0b9 removed unnecessary import of NMS 2020-09-12 17:45:28 +02:00
retrooper 32c94c85f1 attempting to debug, if the getter isn't found 2020-09-12 17:43:04 +02:00
retrooper a36df67f6f NPE in sent outbound wrapped packets FIXED 2020-09-12 17:29:27 +02:00
retrooper cdb46f476c fixed a compilation error
a fee fields weren’t initialized in the default constructor
2020-09-12 04:11:35 +02:00
retrooper 96e5e7393e Merge pull request #36 from LIWKK/patch-3
Fix error
2020-09-12 04:02:29 +02:00
Johannes 130001a44c Fix error 2020-09-11 22:47:34 +03:00
retrooper 1328ea81e8 1.6.8 might release tomorrow 2020-09-11 19:36:29 +02:00
retrooper a42153cff9 1.6.8 pre? 2020-09-11 19:13:17 +02:00
retrooper 79929f5700 temp data files to check if another pe instance exists, might not work 2020-09-11 16:16:45 +02:00
retrooper 8c3726c165 1.6.7 release
* TODO for 1.6.8:
- WrappedPacketOutCustomPayload should be finished
- WrappedPacketOutEntityMetadata should be made

Both wrappers are planned to support sending to players.
2020-09-10 19:44:32 +02:00
retrooper 51a58f79a5 now thread safe event priority system,
contains example code,
outbound custompayload wrapper is now loaded(not guaranteed to work)
2020-09-10 19:34:04 +02:00
retrooper 8691304925 WrappedPacketOutCustomPayload added, untested tho 2020-09-10 18:15:33 +02:00
retrooper 9fef95d96e CHANGELOG:
Note, this build contains debugs and example code

* creating wrappers is much easier and cleaner now with new functions
* all wrappers cleaned up
* walk speed returning the fly speed FIXED
* wrappedpacketoutchat.fromStringToJSON() debug removed
* wrappedpacketoutkickdisconnect constructor now requires a json string,
 * food saturation in wrappedpacketoutupdatehealth was equal to health value by accident
 * WrappedPacketOutEntity has subclasses, like rel entity move, ect...
 * WrappedPacketInFlying subclasses no longer extend the WrappedPacketInFlying, they are now just static classes inside it, this will mean they won't contain all functions like WrappedPacketInFlying does, you can use them to save memory? micro optimization tho XD
2020-09-10 16:19:32 +02:00
retrooper 4d42a23510 1.6.6.1 RELEASE,
* Bug where packetevents won't enable if ProtocolLib isn't present FIXED
2020-09-09 20:38:31 +02:00
83 changed files with 2925 additions and 1208 deletions

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
# packetevents by retrooper
# packetevents
A lightweight spigot packetlistener & packetsender coded by retrooper.
A spigot packet API with some nice utlities.
## About
+1 -8
View File
@@ -6,7 +6,7 @@
<groupId>io.github.retrooper</groupId>
<artifactId>packetevents</artifactId>
<version>1.6.6</version>
<version>1.6.9</version>
<!-- You can build the project with this: "mvn clean compile assembly:single" -->
<build>
@@ -115,12 +115,5 @@
<version>1.8.8-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8.8-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,152 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents;
import java.util.ArrayList;
import java.util.List;
public class PEVersion {
private final int[] version = new int[4];
public PEVersion(int... version) throws IllegalArgumentException {
if (version.length > 4) {
throw new IllegalArgumentException("You are not allowed to have more than 4 arguments!");
} else if (version.length < 2) {
throw new IllegalArgumentException("You need atleast two arguments.");
}
int len = version.length;
if (len < 4) {
this.version[0] = version[0];
this.version[1] = version[1];
if (len == 3) {
this.version[2] = version[2];
} else {
this.version[2] = 0;
this.version[3] = 0;
}
} else {
System.arraycopy(version, 0, this.version, 0, version.length);
}
}
public PEVersion(String text) {
this(stringConstructor(text));
}
private static int[] stringConstructor(String text) {
//1.2.3.4
text += ".";
int dotCount = 0;
for (char c : text.toCharArray()) {
if (c == '.') {
dotCount++;
}
}
//1.2.3.4.
int arrayIndex = 0;
int[] version = new int[4];
// String t = "1.2.3.4";
for (int i = 0; i < text.toCharArray().length; i++) {
char c = text.toCharArray()[i];
if (c == '.') {
version[arrayIndex++] =
Integer.parseInt(Character.toString(text.toCharArray()[i - 1]));
}
}
return version;
}
public boolean isNewer(PEVersion other) {
//The version length if guaranteed to be 4.
for (int i = 0; i < version.length; i++) {
if (version[i] > other.getVersionAsByteArray()[i]) {
return true;
} else if (version[i] < other.getVersionAsByteArray()[i]) {
return false;
}
}
//If they are equal, they aren't newer nor older.
return false;
}
public boolean isOlder(PEVersion other) {
//The version length if guaranteed to be 4.
for (int i = 0; i < version.length; i++) {
if (version[i] < other.getVersionAsByteArray()[i]) {
return true;
} else if (version[i] > other.getVersionAsByteArray()[i]) {
return false;
}
}
//If they are equal, they aren't newer nor older.
return false;
}
public final int[] getVersionAsByteArray() {
return version;
}
public final int[] getVersionAsByteArrayShortened() {
List<Integer> versionBoxed = new ArrayList<>();
if (version[3] == 0) {
versionBoxed.add(version[0]);
versionBoxed.add(version[1]);
versionBoxed.add(version[2]);
if (version[2] == 0) {
versionBoxed.clear();
versionBoxed.add(version[0]);
versionBoxed.add(version[1]);
}
return convertIntListToIntArray(versionBoxed);
} else {
return version;
}
}
private int[] convertIntListToIntArray(List<Integer> list) {
int[] versionArray = new int[list.size()];
for (int i = 0; i < versionArray.length; i++) {
versionArray[i] = list.get(i);
}
return versionArray;
}
@Override
public String toString() {
int[] shortenedVersion = getVersionAsByteArrayShortened();
StringBuilder text = new StringBuilder();
for (int v : shortenedVersion) {
text.append(".").append(v);
}
return text.substring(1);
}
}
@@ -24,57 +24,53 @@
package io.github.retrooper.packetevents;
import io.github.retrooper.packetevents.api.PacketEventsAPI;
import io.github.retrooper.packetevents.enums.ClientVersion;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.event.PacketEvent;
import io.github.retrooper.packetevents.event.PacketListener;
import io.github.retrooper.packetevents.event.impl.BukkitMoveEvent;
import io.github.retrooper.packetevents.packet.PacketType;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.settings.PacketEventsSettings;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.utils.nms_entityfinder.EntityFinderUtils;
import io.github.retrooper.packetevents.utils.entityfinder.EntityFinderUtils;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.versionlookup.VersionLookupUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Field;
import java.util.ArrayList;
public final class PacketEvents implements Listener {
private static final PacketEventsAPI packetEventsAPI = new PacketEventsAPI();
private static final PacketEvents instance = new PacketEvents();
private static final PacketEventsSettings settings = new PacketEventsSettings();
private static final ArrayList<Plugin> plugins = new ArrayList<Plugin>(1);
private static boolean hasLoaded, isStarted;
private static boolean loaded, initialized, isBungee;
private static final PEVersion version = new PEVersion(1, 6, 9);
/**
* This loads the PacketEvents API.
*
* <p>
* ServerVersion:
* In this method we detect and cache the server version.
*
* <p>
* NMSUtils:
* We setup some NMS utilities.
*
* <p>
* Packet ID System:
* All the packet classes we will be needing are cached in a Map with an integer ID.
*
* <p>
* Version Lookup Utils:
* We setup the client protocol version system.
* We check if ViaVersion, ProtocolSupport or ProtocolLib is present.
*
* <p>
* Wrappers:
* All PacketEvents' wrappers are setup and do all loading they need to do.
*
*/
public static void load() {
ServerVersion version = ServerVersion.getVersion();
@@ -90,28 +86,26 @@ public final class PacketEvents implements Listener {
EntityFinderUtils.load();
ClientVersion.prepareLookUp();
WrappedPacket.loadAllWrappers();
hasLoaded = true;
loaded = true;
}
/**
* Initiates PacketEvents
*
* <p>
* Loading:
* Loads PacketEvents if you haven't already.
*
* <p>
* Registering:
* Registers this class as a Bukkit listener to inject/eject players.
*
* @param pl JavaPlugin instance
*/
public static void init(final Plugin pl) {
if (!hasLoaded) {
if (!loaded) {
load();
}
if (!isStarted) {
if (!initialized) {
plugins.add(pl);
//Register Bukkit listener
Bukkit.getPluginManager().registerEvents(instance, plugins.get(0));
@@ -119,12 +113,31 @@ public final class PacketEvents implements Listener {
for (final Player p : Bukkit.getOnlinePlayers()) {
getAPI().getPlayerUtils().injectPlayer(p);
}
isStarted = true;
initialized = true;
Class<?> spigotConfigClass;
try {
spigotConfigClass = Class.forName("org.spigotmc.SpigotConfig");
Field f = spigotConfigClass.getDeclaredField("bungee");
isBungee = f.getBoolean(null);
} catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
isBungee = false;
}
if (PacketEvents.getAPI().getSettings().shouldCheckForUpdates()) {
Bukkit.getScheduler().runTask(pl, new Runnable() {
@Override
public void run() {
new UpdateChecker().handleUpdate();
}
});
}
}
}
/**
* Loads PacketEvents if you haven't already, Sets everything up, injects all players
*
* @param pl Plugin instance
* @deprecated Use {@link #init(Plugin)}
*/
@@ -137,27 +150,27 @@ public final class PacketEvents implements Listener {
*
*/
public static void stop() {
if (isStarted) {
if (initialized) {
for (final Player p : Bukkit.getOnlinePlayers()) {
getAPI().getPlayerUtils().ejectPlayer(p);
}
getAPI().getEventManager().unregisterAllListeners();
isStarted = false;
initialized = false;
}
}
public static boolean hasLoaded() {
return hasLoaded;
return loaded;
}
@Deprecated
public static boolean hasStarted() {
return isStarted;
return initialized;
}
public static boolean isInitialized() {
return isStarted;
return initialized;
}
public static PacketEventsAPI getAPI() {
@@ -174,20 +187,30 @@ public final class PacketEvents implements Listener {
}
public static String getHandlerName(final String name) {
return "pe-" + settings.getIdentifier() + "-" + name;
return "pe-" + PacketEvents.getAPI().getSettings().getIdentifier() + "-" + name;
}
public static PacketEventsSettings getSettings() {
return settings;
return PacketEvents.getAPI().getSettings();
}
public static PEVersion getVersion() {
return version;
}
@EventHandler
public void onJoin(final PlayerJoinEvent e) {
if(!VersionLookupUtils.hasLoaded()) {
if (!VersionLookupUtils.hasLoaded()) {
VersionLookupUtils.load();
}
ClientVersion version = ClientVersion.fromProtocolVersion(VersionLookupUtils.getProtocolVersion(e.getPlayer()));
PacketEvents.getAPI().getPlayerUtils().clientVersionsMap.put(e.getPlayer().getUniqueId(), version);
//for now we don't support bungee, rather handle it than have it FALSE
//and return the version of the server.
if (isBungee) {
PacketEvents.getAPI().getPlayerUtils().clientVersionsMap.put(e.getPlayer().getUniqueId(), ClientVersion.UNKNOWN);
} else {
ClientVersion version = ClientVersion.getClientVersion(VersionLookupUtils.getProtocolVersion(e.getPlayer()));
PacketEvents.getAPI().getPlayerUtils().clientVersionsMap.put(e.getPlayer().getUniqueId(), version);
}
PacketEvents.getAPI().getPlayerUtils().injectPlayer(e.getPlayer());
}
@@ -22,16 +22,19 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.api;
package io.github.retrooper.packetevents;
import io.github.retrooper.packetevents.event.manager.EventManager;
import io.github.retrooper.packetevents.utils.api.PlayerUtils;
import io.github.retrooper.packetevents.utils.api.ServerUtils;
import io.github.retrooper.packetevents.settings.PacketEventsSettings;
import io.github.retrooper.packetevents.utils.player.PlayerUtils;
import io.github.retrooper.packetevents.utils.server.ServerUtils;
public final class PacketEventsAPI {
private final EventManager eventManager = new EventManager();
private final PlayerUtils playerUtils = new PlayerUtils();
private final ServerUtils serverUtils = new ServerUtils();
private final PacketEventsSettings settings = new PacketEventsSettings();
//private final UpdateChecker updateChecker = new UpdateChecker();
/**
* Not thread safe
@@ -61,6 +64,7 @@ public final class PacketEventsAPI {
/**
* Get all utilities to do with the player
*
* @return Player Utilities
*/
public PlayerUtils getPlayerUtils() {
@@ -69,6 +73,7 @@ public final class PacketEventsAPI {
/**
* Get all utilities to do with the server
*
* @return Server Utilities
*/
public ServerUtils getServerUtils() {
@@ -79,9 +84,28 @@ public final class PacketEventsAPI {
/**
* Get the event manager
* Used to call events, register and unregister listeners
*
* @return PacketEvents' event manager
*/
public EventManager getEventManager() {
return eventManager;
}
/**
* Get the PacketEvents settings.
*
* @return Configure some settings for the API
*/
public PacketEventsSettings getSettings() {
return settings;
}
/*
/**
* Get the update checker
* @return Update Checker
*
public UpdateChecker getUpdateChecker() {
return updateChecker;
}
*/
}
@@ -0,0 +1,44 @@
package io.github.retrooper.packetevents;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class UpdateChecker {
public void handleUpdate() {
try {
String line = readLatestVersion();
PEVersion newVersion = new PEVersion(line);
PEVersion localVersion = PacketEvents.getVersion();
if (localVersion.isOlder(newVersion)) {
inform("[PacketEvents] There is an update available for the PacketEvents API! (" + newVersion.toString() + ")");
}
else if(localVersion.equals(newVersion)) {
inform("[PacketEvents] You are on the latest released version of PacketEvents. (" + newVersion.toString() + ")");
}
else if(localVersion.isNewer(newVersion)) {
inform("[PacketEvents] You are on a dev or pre released build of PacketEvents. Your build: (" + localVersion.toString() + ") | Last released build: (" + newVersion.toString() + ")");
}
} catch (IOException ignored) {
//Thats fine, Not important
}
}
private void inform(String message) {
Bukkit.getLogger().info(message);
}
private String readLatestVersion() throws IOException {
URLConnection connection = new URL("https://api.spigotmc.org/legacy/update.php?resource=80279").openConnection();
connection.addRequestProperty("User-Agent", "Mozilla/4.0");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
return reader.readLine();
}
}
@@ -30,101 +30,106 @@ import java.util.HashMap;
import java.util.Map;
public enum ClientVersion {
LESS_THAN_V_1_7_10, v_1_7_10, v_1_8, v_1_9, v_1_9_1, v_1_9_2, v_1_9_3, v_1_10, v_1_11, v_1_11_1, v_1_12, v_1_12_1, v_1_12_2,
v_1_13, v_1_13_1, v_1_13_2, v_1_14, v_1_14_1, v_1_14_2, v_1_14_3, v_1_14_4, v_1_15_PRE_1, v_1_15_PRE_2, v_1_15_PRE_3, v_1_15_PRE_4, v_1_15_PRE_5, v_1_15_PRE_6, v_1_15_PRE_7,
v_1_15, v_1_15_1, v_1_15_2, v_1_16, v_1_16_PRE_1, v_1_16_PRE_2, v_1_16_PRE_3, v_1_16_PRE_4, v_1_16_PRE_5, v_1_16_PRE_6, v_1_16_PRE_7, v_1_16_PRE_8, v_1_16_RC_1, v_1_16_1, v_1_16_2, HIGHER_THAN_V_1_16_2, INVALID, ACCESS_FAILURE;
LOWER_THAN_SUPPORTED_VERSIONS(4),
v_1_7_10(5),
v_1_8(47),
v_1_9(107),
v_1_9_1(108),
v_1_9_2(109),
v_1_9_3(110),
v_1_10(210),
v_1_11(315),
v_1_11_1(316),
v_1_12(335),
v_1_12_1(338),
v_1_12_2(340),
v_1_13(393),
v_1_13_1(401),
v_1_13_2(404),
v_1_14(477),
v_1_14_1(480),
v_1_14_2(485),
v_1_14_3(490),
v_1_14_4(498),
v_1_15(573),
v_1_15_1(575),
v_1_15_2(578),
v_1_16(735),
v_1_16_1(736),
v_1_16_2(751),
v_1_16_3(753),
HIGHER_THAN_SUPPORTED_VERSIONS(754),
/**
* Pre releases just aren't supported, we would end up with so many enum constants.
*/
ANY_PRE_RELEASE_VERSION(0),
private static final Map<Integer, ClientVersion> VERSION_LOOKUP = new HashMap<Integer, ClientVersion>();
UNKNOWN(-1);
public static void prepareLookUp() {
VERSION_LOOKUP.put(-1, ACCESS_FAILURE);
VERSION_LOOKUP.put(1, LESS_THAN_V_1_7_10);
VERSION_LOOKUP.put(2, LESS_THAN_V_1_7_10);
VERSION_LOOKUP.put(3, LESS_THAN_V_1_7_10);
VERSION_LOOKUP.put(4, LESS_THAN_V_1_7_10);
VERSION_LOOKUP.put(5, v_1_7_10);
VERSION_LOOKUP.put(47, v_1_8);
VERSION_LOOKUP.put(107, v_1_9);
VERSION_LOOKUP.put(108, v_1_9_1);
VERSION_LOOKUP.put(109, v_1_9_2);
VERSION_LOOKUP.put(110, v_1_9_3);
VERSION_LOOKUP.put(210, v_1_10);
VERSION_LOOKUP.put(315, v_1_11);
VERSION_LOOKUP.put(316, v_1_11_1);
VERSION_LOOKUP.put(335, v_1_12);
VERSION_LOOKUP.put(338, v_1_12_1);
VERSION_LOOKUP.put(340, v_1_12_2);
VERSION_LOOKUP.put(393, v_1_13);
VERSION_LOOKUP.put(401, v_1_13_1);
VERSION_LOOKUP.put(404, v_1_13_2);
VERSION_LOOKUP.put(477, v_1_14);
VERSION_LOOKUP.put(480, v_1_14_1);
VERSION_LOOKUP.put(485, v_1_14_2);
VERSION_LOOKUP.put(490, v_1_14_3);
VERSION_LOOKUP.put(498, v_1_14_4);
VERSION_LOOKUP.put(565, v_1_15_PRE_1);
VERSION_LOOKUP.put(566, v_1_15_PRE_2);
VERSION_LOOKUP.put(567, v_1_15_PRE_3);
VERSION_LOOKUP.put(569, v_1_15_PRE_4);
VERSION_LOOKUP.put(570, v_1_15_PRE_5);
VERSION_LOOKUP.put(571, v_1_15_PRE_6);
VERSION_LOOKUP.put(572, v_1_15_PRE_7);
VERSION_LOOKUP.put(573, v_1_15);
VERSION_LOOKUP.put(575, v_1_15_1);
VERSION_LOOKUP.put(578, v_1_15_2);
VERSION_LOOKUP.put(721, v_1_16_PRE_1);
VERSION_LOOKUP.put(722, v_1_16_PRE_2);
VERSION_LOOKUP.put(725, v_1_16_PRE_3);
VERSION_LOOKUP.put(727, v_1_16_PRE_4);
VERSION_LOOKUP.put(729, v_1_16_PRE_5);
VERSION_LOOKUP.put(730, v_1_16_PRE_6);
VERSION_LOOKUP.put(732, v_1_16_PRE_7);
VERSION_LOOKUP.put(733, v_1_16_PRE_8);
VERSION_LOOKUP.put(734, v_1_16_RC_1);
VERSION_LOOKUP.put(735, v_1_16);
VERSION_LOOKUP.put(736, v_1_16_1);
VERSION_LOOKUP.put(737, v_1_16_2);
private final int protocolVersion;
private static final int lowestSupportedProtocolVersion = 5;
private static final int highestSupportedProtocolVersion = 753;
ClientVersion(int protocolVersion) {
this.protocolVersion = protocolVersion;
}
public int getProtocolVersion() {
return protocolVersion;
}
public static boolean isHigherThan(ClientVersion a, ClientVersion b) {
return a.getProtocolVersion() > b.getProtocolVersion();
}
public static boolean isLowerThan(ClientVersion a, ClientVersion b) {
return a.getProtocolVersion() < b.getProtocolVersion();
}
public boolean isHigherThan(ClientVersion target) {
return protocolVersion > target.getProtocolVersion();
}
public boolean isLowerThan(ClientVersion target) {
return protocolVersion < target.getProtocolVersion();
}
public boolean equals(ClientVersion target) {
return protocolVersion == target.getProtocolVersion();
}
/**
* @deprecated Added for now just to have backwards compatibility.
* @param protocolVersion
* @return
*/
@Deprecated
public static ClientVersion fromProtocolVersion(int protocolVersion) {
if (protocolVersion == -1 && PacketEvents.getSettings().doAutoResolveClientProtocolVersion()) {
protocolVersion = ServerVersion.getVersion().toProtocolVersion();
}
final ClientVersion lookedUp = VERSION_LOOKUP.get(protocolVersion);
if (lookedUp != null) {
return lookedUp;
}
return protocolVersion > 737 ? HIGHER_THAN_V_1_16_2 : INVALID;
return getClientVersion(protocolVersion);
}
/**
* Returns if the client's version is more up to date than the argument passed version
*
* @param version The version to compare to the client's value.
* @return True if the supplied version is lower, false if it is equal or higher than the client's version.
*/
public boolean isHigherThan(final ClientVersion version) {
if (this == version) return false;
return !isLowerThan(version);
}
/**
* Returns if the client's version is more outdated than the argument passed version
*
* @param version The version to compare to the client's value.
* @return True if the supplied version is higher, false if it is equal or lower than the client's version.
*/
public boolean isLowerThan(final ClientVersion version) {
if (this == version) return false;
final int len = ClientVersion.values().length;
for (byte i = 0; i < len; i++) {
final ClientVersion v = ClientVersion.values()[i];
if (v == this) {
return true;
} else if (v == version) {
return false;
public static ClientVersion getClientVersion(int protocolVersion) {
if(protocolVersion == -1 && PacketEvents.getAPI().getSettings().doAutoResolveClientProtocolVersion()) {
protocolVersion = PacketEvents.getAPI().getServerUtils().getVersion().toProtocolVersion();
}
for(ClientVersion version : ClientVersion.values()) {
if(version.protocolVersion > protocolVersion) {
break;
}
else if(version.protocolVersion == protocolVersion) {
return version;
}
}
return false;
if(protocolVersion < lowestSupportedProtocolVersion) {
return LOWER_THAN_SUPPORTED_VERSIONS;
}
else if(protocolVersion > highestSupportedProtocolVersion) {
return HIGHER_THAN_SUPPORTED_VERSIONS;
}
else if(protocolVersion > lowestSupportedProtocolVersion
&& protocolVersion < highestSupportedProtocolVersion) {
return ANY_PRE_RELEASE_VERSION;
}
return UNKNOWN;
}
}
}
@@ -24,6 +24,7 @@
package io.github.retrooper.packetevents.enums;
@Deprecated
public enum EventSynchronization {
NORMAL, FORCE_SYNC, FORCE_ASYNC
}
@@ -23,7 +23,7 @@
*/
package io.github.retrooper.packetevents.enums;
@Deprecated
public interface PacketEventPriority {
byte LOWEST = 0;
byte LOW = 1;
@@ -37,7 +37,7 @@ public enum ServerVersion {
v_1_9, v_1_9_2, v_1_9_4, v_1_10, v_1_10_2, v_1_11, v_1_11_1, v_1_11_2,
v_1_12, v_1_12_1, v_1_12_2, v_1_13, v_1_13_1, v_1_13_2, v_1_14, v_1_14_1,
v_1_14_2, v_1_14_3, v_1_14_4, v_1_15, v_1_15_1, v_1_15_2, v_1_16, v_1_16_1,
v_1_16_2, ERROR, EMPTY;
v_1_16_2, v_1_16_3, ERROR, EMPTY;
private static final String nmsVersionSuffix = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
public static ServerVersion[] reversedValues = new ServerVersion[values().length];
@@ -193,8 +193,10 @@ public enum ServerVersion {
return 736;
case v_1_16_2:
return 751;
case v_1_16_3:
return 753;
default:
return -1;
}
}
}
}
@@ -44,7 +44,13 @@ public interface CancellableEvent {
/**
* Cancel the event.
* This is the same as just doing: CancellableEvent#setCancelled(true)
* You can achieve the same result by just using {@link #setCancelled(boolean)}
*/
void cancel();
/**
* Uncancel the event.
* You can achieve the same result by just using {@link #setCancelled(boolean)}
*/
void uncancel();
}
@@ -50,6 +50,11 @@ public final class BukkitMoveEvent extends PacketEvent implements CancellableEve
@Override
public void cancel() {
setCancelled(true);
this.cancelled = true;
}
@Override
public void uncancel() {
this.cancelled = false;
}
}
@@ -26,7 +26,7 @@ package io.github.retrooper.packetevents.event.impl;
import io.github.retrooper.packetevents.event.CancellableEvent;
import io.github.retrooper.packetevents.event.PacketEvent;
import io.github.retrooper.packetevents.packet.PacketType;
import io.github.retrooper.packetevents.packettype.PacketType;
import org.bukkit.entity.Player;
/**
@@ -91,6 +91,11 @@ public final class PacketReceiveEvent extends PacketEvent implements Cancellable
this.cancelled = true;
}
@Override
public void uncancel() {
this.cancelled = false;
}
@Override
public boolean isCancelled() {
return cancelled;
@@ -26,7 +26,7 @@ package io.github.retrooper.packetevents.event.impl;
import io.github.retrooper.packetevents.event.CancellableEvent;
import io.github.retrooper.packetevents.event.PacketEvent;
import io.github.retrooper.packetevents.packet.PacketType;
import io.github.retrooper.packetevents.packettype.PacketType;
import org.bukkit.entity.Player;
/**
@@ -101,5 +101,8 @@ public final class PacketSendEvent extends PacketEvent implements CancellableEve
public void cancel() {
this.cancelled = true;
}
@Override
public void uncancel() { this.cancelled = false;}
}
@@ -60,6 +60,9 @@ public final class PlayerInjectEvent extends PacketEvent implements CancellableE
this.cancelled = true;
}
@Override
public void uncancel() {this.cancelled = false; }
public Player getPlayer() {
return player;
}
@@ -50,6 +50,9 @@ public final class PlayerUninjectEvent extends PacketEvent implements Cancellabl
this.cancelled = true;
}
@Override
public void uncancel() {this.cancelled = false; }
@Override
public boolean isCancelled() {
return this.cancelled;
@@ -31,53 +31,45 @@ import io.github.retrooper.packetevents.event.CancellableEvent;
import io.github.retrooper.packetevents.event.PacketEvent;
import io.github.retrooper.packetevents.event.PacketListener;
import io.github.retrooper.packetevents.utils.protocollib.ProtocolLibListener;
import io.github.retrooper.packetevents.utils.protocollib.ProtocolLibUtils;
import org.bukkit.Bukkit;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
public final class EventManager {
private final HashMap<PacketListener, List<Method>> registeredMethods = new HashMap<PacketListener, List<Method>>();
private final ConcurrentHashMap<PacketListener, ConcurrentLinkedQueue<Method>> registeredMethods = new ConcurrentHashMap<>();
public void callEvent(final PacketEvent e) {
for (final PacketListener listener : registeredMethods.keySet()) {
//Annotated methods
final List<Method> methods = registeredMethods.get(listener);
final List<Boolean> isCancellingList = new ArrayList<Boolean>(methods.size());
int highestPriorityMethodListenerIndex = 0;
for(int i = 0; i < methods.size(); i++) {
Method method = methods.get(i);
final Class<?> parameterType = method.getParameterTypes()[0];
ConcurrentLinkedQueue<Method> methods = registeredMethods.get(listener);
final boolean[] isCancelled = {false};
final byte[] eventPriority = {PacketEventPriority.LOWEST};
for (Method method : methods) {
Class<?> parameterType = method.getParameterTypes()[0];
if (parameterType.equals(PacketEvent.class)
|| parameterType.isInstance(e)) {
PacketHandler annotation = methods.get(highestPriorityMethodListenerIndex).getAnnotation(PacketHandler.class);
PacketHandler competitorAnnotation = methods.get(i).getAnnotation(PacketHandler.class);
if(competitorAnnotation.priority() >= annotation.priority()) {
highestPriorityMethodListenerIndex = i;
}
boolean isCurEventCancelled = false;
final Runnable invokeMethod = new Runnable() {
PacketHandler annotation = method.getAnnotation(PacketHandler.class);
Runnable invokeMethod = new Runnable() {
@Override
public void run() {
try {
method.invoke(listener, e);
if(e instanceof CancellableEvent) {
isCancellingList.add(((CancellableEvent) e).isCancelled());
}
} catch (IllegalAccessException | InvocationTargetException ex) {
ex.printStackTrace();
}
if (e instanceof CancellableEvent) {
CancellableEvent ce = (CancellableEvent) e;
if (annotation.priority() >= eventPriority[0]) {
eventPriority[0] = annotation.priority();
isCancelled[0] = ce.isCancelled();
}
}
}
};
switch (annotation.synchronization()) {
case FORCE_ASYNC:
Bukkit.getScheduler().runTaskAsynchronously(PacketEvents.getPlugin(), invokeMethod);
@@ -91,16 +83,18 @@ public final class EventManager {
} catch (IllegalAccessException | InvocationTargetException ex) {
ex.printStackTrace();
}
isCancellingList.add(((CancellableEvent)e).isCancelled());
if (e instanceof CancellableEvent) {
CancellableEvent ce = (CancellableEvent) e;
if (annotation.priority() >= eventPriority[0]) {
eventPriority[0] = annotation.priority();
isCancelled[0] = ce.isCancelled();
}
}
break;
}
//Last iteration
if(i + 1 == methods.size()) {
if(e instanceof CancellableEvent) {
CancellableEvent cancellable = (CancellableEvent)e;
cancellable.setCancelled(isCancellingList.get(highestPriorityMethodListenerIndex));
}
if (e instanceof CancellableEvent) {
CancellableEvent cancellableEvent = (CancellableEvent) e;
cancellableEvent.setCancelled(isCancelled[0]);
}
}
}
@@ -108,11 +102,7 @@ public final class EventManager {
}
public void registerListener(final PacketListener listener) {
if (ProtocolLibListener.isProtocolLibPresent() == ProtocolLibListener.ProtocolLibPresent.UNKNOWN) {
ProtocolLibListener.load();
}
final List<Method> methods = new ArrayList<Method>();
final ConcurrentLinkedQueue<Method> methods = new ConcurrentLinkedQueue<>();
for (final Method m : listener.getClass().getDeclaredMethods()) {
if (m.isAnnotationPresent(PacketHandler.class)
&& m.getParameterTypes().length == 1) {
@@ -121,7 +111,8 @@ public final class EventManager {
}
if (!methods.isEmpty()) {
if (ProtocolLibListener.isProtocolLibPresent() == ProtocolLibListener.ProtocolLibPresent.PRESENT) {
if (ProtocolLibUtils.isAvailable()
&& PacketEvents.getAPI().getSettings().isUseProtocolLibIfAvailable()) {
ProtocolLibListener.registerProtocolLibListener(listener, methods);
} else {
registeredMethods.put(listener, methods);
@@ -0,0 +1,34 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.event.priority;
public interface PacketEventPriority {
byte LOWEST = 0;
byte LOW = 1;
byte NORMAL = 2;
byte HIGH = 3;
byte HIGHEST = 4;
byte MONITOR = 5;
}
@@ -37,11 +37,8 @@ public class MainExample extends JavaPlugin implements PacketListener {
@Override
public void onEnable() {
//Deprecated, as it is no longer needed
PacketEvents.getSettings().setIdentifier("official_api");
PacketEvents.init(this);
//PacketEvents.getAPI().getEventManager().registerListener(this);
PacketEvents.getAPI().getEventManager().registerListener(this);
}
@Override
@@ -22,13 +22,14 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.handler;
package io.github.retrooper.packetevents.nettyhandler;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.event.impl.PacketReceiveEvent;
import io.github.retrooper.packetevents.event.impl.PacketSendEvent;
import io.github.retrooper.packetevents.event.impl.PlayerInjectEvent;
import io.github.retrooper.packetevents.event.impl.PlayerUninjectEvent;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import org.bukkit.entity.Player;
import java.util.concurrent.ExecutorService;
@@ -36,7 +37,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class NettyPacketHandler {
private static boolean v1_7_nettyMode = false;
public static boolean v1_7_nettyMode = false;
private static final ExecutorService singleThreadedExecutor = Executors.newSingleThreadExecutor();
static {
@@ -75,6 +76,8 @@ public class NettyPacketHandler {
* @return {@link java.util.concurrent.Future}
*/
public static Future<?> injectPlayerAsync(final Player player) {
//Make sure we cache the channel SYNCHRONOUSLY
Object channel = NMSUtils.getChannel(player);
return singleThreadedExecutor.submit(() -> {
try {
final PlayerInjectEvent injectEvent = new PlayerInjectEvent(player, true);
@@ -98,6 +101,7 @@ public class NettyPacketHandler {
* @param player
*/
public static void ejectPlayer(final Player player) {
NMSUtils.channelCache.remove(player.getUniqueId());
try {
final PlayerUninjectEvent uninjectEvent = new PlayerUninjectEvent(player);
PacketEvents.getAPI().getEventManager().callEvent(uninjectEvent);
@@ -120,7 +124,8 @@ public class NettyPacketHandler {
* @return {@link java.util.concurrent.Future}
*/
public static Future<?> ejectPlayerAsync(final Player player) {
return singleThreadedExecutor.submit(() -> {
NMSUtils.channelCache.remove(player.getUniqueId());
Future<?> f = singleThreadedExecutor.submit(() -> {
try {
final PlayerUninjectEvent uninjectEvent = new PlayerUninjectEvent(player, true);
PacketEvents.getAPI().getEventManager().callEvent(uninjectEvent);
@@ -135,6 +140,7 @@ public class NettyPacketHandler {
}
});
return f;
}
/**
@@ -170,4 +176,12 @@ public class NettyPacketHandler {
return null;
}
public static void sendPacket(Object channel, Object packet) {
if(v1_7_nettyMode) {
NettyPacketHandler_7.sendPacket(channel, packet);
}
else {
NettyPacketHandler_8.sendPacket(channel, packet);
}
}
}
@@ -22,19 +22,18 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.handler;
package io.github.retrooper.packetevents.nettyhandler;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import net.minecraft.util.io.netty.channel.Channel;
import net.minecraft.util.io.netty.channel.ChannelDuplexHandler;
import net.minecraft.util.io.netty.channel.ChannelHandlerContext;
import net.minecraft.util.io.netty.channel.ChannelPipeline;
import net.minecraft.util.io.netty.channel.ChannelPromise;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.concurrent.Future;
final class NettyPacketHandler_7 {
/**
@@ -70,7 +69,13 @@ final class NettyPacketHandler_7 {
* @param player
*/
public static void ejectPlayer(final Player player) {
final Channel channel = (Channel) NMSUtils.getChannel(player);
Channel channel = (Channel) NMSUtils.getChannelNoCache(player);
channel.pipeline().remove(PacketEvents.getHandlerName(player.getName()));
//Make sure we are removing the cache synchronously
}
public static void sendPacket(Object rawChannel, Object packet) {
Channel channel = (Channel)rawChannel;
channel.pipeline().writeAndFlush(packet);
}
}
@@ -22,19 +22,18 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.handler;
package io.github.retrooper.packetevents.nettyhandler;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.concurrent.Future;
final class NettyPacketHandler_8 {
/**
* Inject a player with 1.8+ netty import location.
@@ -69,7 +68,20 @@ final class NettyPacketHandler_8 {
* @param player
*/
public static void ejectPlayer(final Player player) {
final Channel channel = (Channel) NMSUtils.getChannel(player);
final Channel channel = (Channel) NMSUtils.getChannelNoCache(player);
channel.pipeline().remove(PacketEvents.getHandlerName(player.getName()));
//Make sure we are removing the cache synchronously
Bukkit.getScheduler().runTask(PacketEvents.getPlugins().get(0), new Runnable() {
@Override
public void run() {
//Make sure we are removing the cache SYNCHRONOUSLY
NMSUtils.channelCache.remove(player.getUniqueId());
}
});
}
public static void sendPacket(Object rawChannel, Object packet) {
Channel channel = (Channel)rawChannel;
channel.pipeline().writeAndFlush(packet);
}
}
@@ -24,8 +24,9 @@
package io.github.retrooper.packetevents.packet;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packettype.PacketType;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
public class PacketTypeClasses {
public static class Client {
@@ -52,9 +53,9 @@ public class PacketTypeClasses {
POSITION_LOOK = NMSUtils.getNMSClass(c + "PositionLook");
LOOK = NMSUtils.getNMSClass(c + "Look");
} catch (ClassNotFoundException e) {
POSITION = Reflection.getSubClass(FLYING, c + "Position");
POSITION_LOOK = Reflection.getSubClass(FLYING, c + "PositionLook");
LOOK = Reflection.getSubClass(FLYING, c + "Look");
POSITION = SubclassUtil.getSubClass(FLYING, c + "Position");
POSITION_LOOK = SubclassUtil.getSubClass(FLYING, c + "PositionLook");
LOOK = SubclassUtil.getSubClass(FLYING, c + "Look");
}
try {
@@ -195,9 +196,9 @@ public class PacketTypeClasses {
MAP = NMSUtils.getNMSClassWithoutException(s + "Map");
OPEN_WINDOW_MERCHANT = NMSUtils.getNMSClassWithoutException(s + "OpenWindowMerchant");
ENTITY = NMSUtils.getNMSClassWithoutException(s + "Entity");
REL_ENTITY_MOVE = Reflection.getSubClass(ENTITY, s + "RelEntityMove");
REL_ENTITY_MOVE_LOOK = Reflection.getSubClass(ENTITY, s + "RelEntityMoveLook");
ENTITY_LOOK = Reflection.getSubClass(ENTITY, s + "EntityLook");
REL_ENTITY_MOVE = SubclassUtil.getSubClass(ENTITY, s + "RelEntityMove");
REL_ENTITY_MOVE_LOOK = SubclassUtil.getSubClass(ENTITY, s + "RelEntityMoveLook");
ENTITY_LOOK = SubclassUtil.getSubClass(ENTITY, s + "EntityLook");
if (REL_ENTITY_MOVE == null) {
//is not a subclass and should be accessed normally
REL_ENTITY_MOVE = NMSUtils.getNMSClassWithoutException(s + "RelEntityMove");
@@ -22,7 +22,9 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.packet;
package io.github.retrooper.packetevents.packettype;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import java.util.HashMap;
import java.util.Map;
@@ -27,6 +27,6 @@ package io.github.retrooper.packetevents.packetwrappers;
/**
* This interface indicates that a packet wrapper supports being sent to a client.
*/
public interface Sendable {
public interface SendableWrapper {
Object asNMSPacket();
}
@@ -0,0 +1,587 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.packetwrappers;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.in.abilities.WrappedPacketInAbilities;
import io.github.retrooper.packetevents.packetwrappers.in.armanimation.WrappedPacketInArmAnimation;
import io.github.retrooper.packetevents.packetwrappers.in.blockdig.WrappedPacketInBlockDig;
import io.github.retrooper.packetevents.packetwrappers.in.blockplace.WrappedPacketInBlockPlace;
import io.github.retrooper.packetevents.packetwrappers.in.chat.WrappedPacketInChat;
import io.github.retrooper.packetevents.packetwrappers.in.clientcommand.WrappedPacketInClientCommand;
import io.github.retrooper.packetevents.packetwrappers.in.custompayload.WrappedPacketInCustomPayload;
import io.github.retrooper.packetevents.packetwrappers.in.entityaction.WrappedPacketInEntityAction;
import io.github.retrooper.packetevents.packetwrappers.in.flying.WrappedPacketInFlying;
import io.github.retrooper.packetevents.packetwrappers.in.helditemslot.WrappedPacketInHeldItemSlot;
import io.github.retrooper.packetevents.packetwrappers.in.keepalive.WrappedPacketInKeepAlive;
import io.github.retrooper.packetevents.packetwrappers.in.settings.WrappedPacketInSettings;
import io.github.retrooper.packetevents.packetwrappers.in.steervehicle.WrappedPacketInSteerVehicle;
import io.github.retrooper.packetevents.packetwrappers.in.transaction.WrappedPacketInTransaction;
import io.github.retrooper.packetevents.packetwrappers.in.updatesign.WrappedPacketInUpdateSign;
import io.github.retrooper.packetevents.packetwrappers.in.useentity.WrappedPacketInUseEntity;
import io.github.retrooper.packetevents.packetwrappers.in.windowclick.WrappedPacketInWindowClick;
import io.github.retrooper.packetevents.packetwrappers.out.abilities.WrappedPacketOutAbilities;
import io.github.retrooper.packetevents.packetwrappers.out.animation.WrappedPacketOutAnimation;
import io.github.retrooper.packetevents.packetwrappers.out.chat.WrappedPacketOutChat;
import io.github.retrooper.packetevents.packetwrappers.out.custompayload.WrappedPacketOutCustomPayload;
import io.github.retrooper.packetevents.packetwrappers.out.entity.WrappedPacketOutEntity;
import io.github.retrooper.packetevents.packetwrappers.out.entityvelocity.WrappedPacketOutEntityVelocity;
import io.github.retrooper.packetevents.packetwrappers.out.gamestatechange.WrappedPacketOutGameStateChange;
import io.github.retrooper.packetevents.packetwrappers.out.keepalive.WrappedPacketOutKeepAlive;
import io.github.retrooper.packetevents.packetwrappers.out.kickdisconnect.WrappedPacketOutKickDisconnect;
import io.github.retrooper.packetevents.packetwrappers.out.position.WrappedPacketOutPosition;
import io.github.retrooper.packetevents.packetwrappers.out.transaction.WrappedPacketOutTransaction;
import io.github.retrooper.packetevents.packetwrappers.out.updatehealth.WrappedPacketOutUpdateHealth;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class WrappedPacket implements WrapperPacketReader {
private static final HashMap<Class<?>, HashMap<Class<?>, Field[]>> fieldCache = new HashMap<>();
public static ServerVersion version;
protected final Player player;
protected Object packet;
private Class<?> packetClass;
public WrappedPacket() {
this(null);
}
public WrappedPacket(final Object packet) {
this(null, packet);
}
public WrappedPacket(final Player player, final Object packet) {
if (packet == null) {
this.player = null;
return;
}
this.packetClass = packet.getClass();
if (packet.getClass().getSuperclass().equals(PacketTypeClasses.Client.FLYING)) {
packetClass = PacketTypeClasses.Client.FLYING;
} else if (packet.getClass().getSuperclass().equals(PacketTypeClasses.Server.ENTITY)) {
packetClass = PacketTypeClasses.Server.ENTITY;
}
if (!fieldCache.containsKey(packetClass)) {
final Field[] declaredFields = packetClass.getDeclaredFields();
List<Field> boolFields = new ArrayList<>();
List<Field> byteFields = new ArrayList<>();
List<Field> shortFields = new ArrayList<>();
List<Field> intFields = new ArrayList<>();
List<Field> longFields = new ArrayList<>();
List<Field> floatFields = new ArrayList<>();
List<Field> doubleFields = new ArrayList<>();
List<Field> stringFields = new ArrayList<>();
List<Field> boolArrayFields = new ArrayList<>();
List<Field> byteArrayFields = new ArrayList<>();
List<Field> shortArrayFields = new ArrayList<>();
List<Field> intArrayFields = new ArrayList<>();
List<Field> longArrayFields = new ArrayList<>();
List<Field> floatArrayFields = new ArrayList<>();
List<Field> doubleArrayFields = new ArrayList<>();
List<Field> stringArrayFields = new ArrayList<>();
for (Field f : declaredFields) {
f.setAccessible(true);
if (f.getType().equals(boolean.class)) {
boolFields.add(f);
} else if (f.getType().equals(byte.class)) {
byteFields.add(f);
} else if (f.getType().equals(short.class)) {
shortFields.add(f);
} else if (f.getType().equals(int.class)) {
intFields.add(f);
} else if (f.getType().equals(long.class)) {
longFields.add(f);
} else if (f.getType().equals(float.class)) {
floatFields.add(f);
} else if (f.getType().equals(double.class)) {
doubleFields.add(f);
} else if (f.getType().equals(String.class)) {
stringFields.add(f);
} else if (f.getType().equals(boolean[].class)) {
boolArrayFields.add(f);
} else if (f.getType().equals(byte[].class)) {
byteArrayFields.add(f);
} else if (f.getType().equals(short[].class)) {
shortArrayFields.add(f);
} else if (f.getType().equals(int[].class)) {
intArrayFields.add(f);
} else if (f.getType().equals(long[].class)) {
longArrayFields.add(f);
} else if (f.getType().equals(float[].class)) {
floatArrayFields.add(f);
} else if (f.getType().equals(double[].class)) {
doubleArrayFields.add(f);
} else if (f.getType().equals(String[].class)) {
stringArrayFields.add(f);
}
}
HashMap<Class<?>, Field[]> map = new HashMap<>();
if (!boolFields.isEmpty()) {
map.put(boolean.class, boolFields.toArray(new Field[0]));
}
if (!byteFields.isEmpty()) {
map.put(byte.class, byteFields.toArray(new Field[0]));
}
if (!shortFields.isEmpty()) {
map.put(short.class, shortFields.toArray(new Field[0]));
}
if (!intFields.isEmpty()) {
map.put(int.class, intFields.toArray(new Field[0]));
}
if (!longFields.isEmpty()) {
map.put(long.class, longFields.toArray(new Field[0]));
}
if (!floatFields.isEmpty()) {
map.put(float.class, floatFields.toArray(new Field[0]));
}
if (!doubleFields.isEmpty()) {
map.put(double.class, doubleFields.toArray(new Field[0]));
}
if (!stringFields.isEmpty()) {
map.put(String.class, stringFields.toArray(new Field[0]));
}
if (!boolArrayFields.isEmpty()) {
map.put(boolean[].class, boolArrayFields.toArray(new Field[0]));
}
if (!byteArrayFields.isEmpty()) {
map.put(byte[].class, byteArrayFields.toArray(new Field[0]));
}
if (!shortArrayFields.isEmpty()) {
map.put(short[].class, shortArrayFields.toArray(new Field[0]));
}
if (!intArrayFields.isEmpty()) {
map.put(int[].class, intArrayFields.toArray(new Field[0]));
}
if (!longArrayFields.isEmpty()) {
map.put(long[].class, longArrayFields.toArray(new Field[0]));
}
if (!floatArrayFields.isEmpty()) {
map.put(float[].class, floatArrayFields.toArray(new Field[0]));
}
if (!doubleArrayFields.isEmpty()) {
map.put(double[].class, doubleArrayFields.toArray(new Field[0]));
}
if (!stringArrayFields.isEmpty()) {
map.put(String[].class, stringArrayFields.toArray(new Field[0]));
}
fieldCache.put(packetClass, map);
}
this.player = player;
this.packet = packet;
setup();
}
public static void loadAllWrappers() {
//SERVER BOUND
WrappedPacketInAbilities.load();
WrappedPacketInArmAnimation.load();
WrappedPacketInBlockDig.load();
WrappedPacketInBlockPlace.load();
WrappedPacketInChat.load();
WrappedPacketInClientCommand.load();
WrappedPacketInCustomPayload.load();
WrappedPacketInEntityAction.load();
WrappedPacketInFlying.load();
WrappedPacketInHeldItemSlot.load();
WrappedPacketInKeepAlive.load();
WrappedPacketInSettings.load();
WrappedPacketInSteerVehicle.load();
WrappedPacketInTransaction.load();
WrappedPacketInUseEntity.load();
WrappedPacketInUpdateSign.load();
WrappedPacketInWindowClick.load();
//CLIENTBOUND
WrappedPacketOutAbilities.load();
WrappedPacketOutAnimation.load();
WrappedPacketOutChat.load();
WrappedPacketOutEntity.load();
WrappedPacketOutEntityVelocity.load();
WrappedPacketOutKeepAlive.load();
WrappedPacketOutKickDisconnect.load();
WrappedPacketOutPosition.load();
WrappedPacketOutTransaction.load();
WrappedPacketOutUpdateHealth.load();
WrappedPacketOutGameStateChange.load();
WrappedPacketOutCustomPayload.load();
}
protected void setup() {
}
@Override
public boolean readBoolean(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return fieldCache.get(packetClass).get(boolean.class)[index].getBoolean(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return false;
}
@Override
public byte readByte(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return fieldCache.get(packetClass).get(byte.class)[index].getByte(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return 0;
}
@Override
public short readShort(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return fieldCache.get(packetClass).get(short.class)[index].getShort(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return 0;
}
@Override
public int readInt(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return fieldCache.get(packetClass).get(int.class)[index].getInt(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return 0;
}
@Override
public long readLong(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return fieldCache.get(packetClass).get(long.class)[index].getLong(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return 0L;
}
@Override
public float readFloat(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return fieldCache.get(packetClass).get(float.class)[index].getFloat(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return 0.0F;
}
@Override
public double readDouble(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return fieldCache.get(packetClass).get(double.class)[index].getDouble(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return 0.0;
}
@Override
public boolean[] readBooleanArray(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return (boolean[]) fieldCache.get(packetClass).get(boolean[].class)[index].get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
int currentIndex = 0;
for (Field f : packetClass.getDeclaredFields()) {
f.setAccessible(true);
if (boolean[].class.isAssignableFrom(f.getType())) {
if (index == currentIndex++) {
try {
return (boolean[]) f.get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
return new boolean[0];
}
@Override
public byte[] readByteArray(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return (byte[]) fieldCache.get(packetClass).get(byte[].class)[index].get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
int currentIndex = 0;
for (Field f : packetClass.getDeclaredFields()) {
f.setAccessible(true);
if (byte[].class.isAssignableFrom(f.getType())) {
if (index == currentIndex++) {
try {
return (byte[]) f.get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
return new byte[0];
}
@Override
public short[] readShortArray(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return (short[]) fieldCache.get(packetClass).get(short[].class)[index].get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
int currentIndex = 0;
for (Field f : packetClass.getDeclaredFields()) {
f.setAccessible(true);
if (short[].class.isAssignableFrom(f.getType())) {
if (index == currentIndex++) {
try {
return (short[]) f.get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
return new short[0];
}
@Override
public int[] readIntArray(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return (int[]) fieldCache.get(packetClass).get(int[].class)[index].get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
int currentIndex = 0;
for (Field f : packetClass.getDeclaredFields()) {
f.setAccessible(true);
if (int[].class.isAssignableFrom(f.getType())) {
if (index == currentIndex++) {
try {
return (int[]) f.get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
return new int[0];
}
@Override
public long[] readLongArray(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return (long[]) fieldCache.get(packetClass).get(long[].class)[index].get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
int currentIndex = 0;
for (Field f : packetClass.getDeclaredFields()) {
f.setAccessible(true);
if (long[].class.isAssignableFrom(f.getType())) {
if (index == currentIndex++) {
try {
return (long[]) f.get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
return new long[0];
}
@Override
public float[] readFloatArray(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return (float[]) fieldCache.get(packetClass).get(float[].class)[index].get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
int currentIndex = 0;
for (Field f : packetClass.getDeclaredFields()) {
f.setAccessible(true);
if (float.class.isAssignableFrom(f.getType())) {
if (index == currentIndex++) {
try {
return (float[]) f.get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
return new float[0];
}
@Override
public double[] readDoubleArray(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
return (double[]) fieldCache.get(packetClass).get(double[].class)[index].get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
int currentIndex = 0;
for (Field f : packetClass.getDeclaredFields()) {
f.setAccessible(true);
if (double[].class.isAssignableFrom(f.getType())) {
if (index == currentIndex++) {
try {
return (double[]) f.get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
return new double[0];
}
@Override
public String[] readStringArray(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
Object[] array = (Object[]) fieldCache.get(packetClass).get(String[].class)[index].get(packet);
int len = array.length;
String[] stringArray = new String[len];
for (int i = 0; i < len; i++) {
stringArray[i] = array[i].toString();
}
return stringArray;
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return new String[0];
}
@Override
public String readString(int index) {
if (fieldCache.containsKey(packetClass)) {
try {
Field[] fields = fieldCache.get(packetClass).get(String.class);
Object obj = fields[index].get(packet);
return obj.toString();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return "";
}
public Object readAnyObject(int index) {
return packetClass.getDeclaredFields()[index];
}
public Object readObject(int index, Class<?> type) {
if (fieldCache.containsKey(packetClass)) {
HashMap<Class<?>, Field[]> map = fieldCache.get(packetClass);
if (!map.containsKey(type)) {
List<Field> typeFields = new ArrayList<>();
for (Field f : packetClass.getDeclaredFields()) {
f.setAccessible(true);
if (f.getType().equals(type)) {
typeFields.add(f);
}
}
if (!typeFields.isEmpty()) {
map.put(type, typeFields.toArray(new Field[0]));
}
}
}
try {
return fieldCache.get(packetClass).get(type)[index].get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public Object[] readObjectArray(int index, Class<?> type) {
Object res = readObject(index, type);
if (res == null) {
return new Object[0];
}
return (Object[]) res;
}
}
@@ -0,0 +1,66 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.packetwrappers;
public interface WrapperPacketReader {
boolean readBoolean(int index);
byte readByte(int index);
short readShort(int index);
int readInt(int index);
long readLong(int index);
float readFloat(int index);
double readDouble(int index);
boolean[] readBooleanArray(int index);
byte[] readByteArray(int index);
short[] readShortArray(int index);
int[] readIntArray(int index);
long[] readLongArray(int index);
float[] readFloatArray(int index);
double[] readDoubleArray(int index);
String[] readStringArray(int index);
String readString(int index);
Object readObject(int index, Class<?> type);
Object readAnyObject(int index);
Object[] readObjectArray(int index, Class<?> type);
}
@@ -1,124 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.packetwrappers.api;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.packetwrappers.in.abilities.WrappedPacketInAbilities;
import io.github.retrooper.packetevents.packetwrappers.in.armanimation.WrappedPacketInArmAnimation;
import io.github.retrooper.packetevents.packetwrappers.in.blockdig.WrappedPacketInBlockDig;
import io.github.retrooper.packetevents.packetwrappers.in.blockplace.WrappedPacketInBlockPlace;
import io.github.retrooper.packetevents.packetwrappers.in.chat.WrappedPacketInChat;
import io.github.retrooper.packetevents.packetwrappers.in.clientcommand.WrappedPacketInClientCommand;
import io.github.retrooper.packetevents.packetwrappers.in.custompayload.WrappedPacketInCustomPayload;
import io.github.retrooper.packetevents.packetwrappers.in.entityaction.WrappedPacketInEntityAction;
import io.github.retrooper.packetevents.packetwrappers.in.flying.WrappedPacketInFlying;
import io.github.retrooper.packetevents.packetwrappers.in.helditemslot.WrappedPacketInHeldItemSlot;
import io.github.retrooper.packetevents.packetwrappers.in.keepalive.WrappedPacketInKeepAlive;
import io.github.retrooper.packetevents.packetwrappers.in.settings.WrappedPacketInSettings;
import io.github.retrooper.packetevents.packetwrappers.in.steervehicle.WrappedPacketInSteerVehicle;
import io.github.retrooper.packetevents.packetwrappers.in.transaction.WrappedPacketInTransaction;
import io.github.retrooper.packetevents.packetwrappers.in.useentity.WrappedPacketInUseEntity;
import io.github.retrooper.packetevents.packetwrappers.in.windowclick.WrappedPacketInWindowClick;
import io.github.retrooper.packetevents.packetwrappers.out.abilities.WrappedPacketOutAbilities;
import io.github.retrooper.packetevents.packetwrappers.out.animation.WrappedPacketOutAnimation;
import io.github.retrooper.packetevents.packetwrappers.out.chat.WrappedPacketOutChat;
import io.github.retrooper.packetevents.packetwrappers.out.entity.WrappedPacketOutEntity;
import io.github.retrooper.packetevents.packetwrappers.out.entityvelocity.WrappedPacketOutEntityVelocity;
import io.github.retrooper.packetevents.packetwrappers.out.keepalive.WrappedPacketOutKeepAlive;
import io.github.retrooper.packetevents.packetwrappers.out.kickdisconnect.WrappedPacketOutKickDisconnect;
import io.github.retrooper.packetevents.packetwrappers.out.position.WrappedPacketOutPosition;
import io.github.retrooper.packetevents.packetwrappers.out.transaction.WrappedPacketOutTransaction;
import io.github.retrooper.packetevents.packetwrappers.out.updatehealth.WrappedPacketOutUpdateHealth;
import org.bukkit.entity.Player;
public class WrappedPacket {
public static ServerVersion version;
protected final Player player;
protected Object packet;
public WrappedPacket() {
this.player = null;
this.packet = null;
}
public WrappedPacket(final Object packet) {
this.player = null;
if (packet == null) return;
this.packet = packet;
try {
setup();
} catch (final Exception e) {
e.printStackTrace();
}
}
public WrappedPacket(final Player player, final Object packet) {
this.player = player;
if (packet == null) return;
this.packet = packet;
try {
setup();
} catch (final Exception e) {
e.printStackTrace();
}
}
public static void loadAllWrappers() {
//SERVER BOUND
WrappedPacketInAbilities.load();
WrappedPacketInArmAnimation.load();
WrappedPacketInBlockDig.load();
WrappedPacketInBlockPlace.load();
WrappedPacketInChat.load();
WrappedPacketInClientCommand.load();
WrappedPacketInCustomPayload.load();
WrappedPacketInEntityAction.load();
WrappedPacketInFlying.load();
WrappedPacketInHeldItemSlot.load();
WrappedPacketInKeepAlive.load();
WrappedPacketInSettings.load();
WrappedPacketInSteerVehicle.load();
WrappedPacketInTransaction.load();
WrappedPacketInUseEntity.load();
WrappedPacketInWindowClick.load();
//CLIENTBOUND
WrappedPacketOutAbilities.load();
WrappedPacketOutAnimation.load();
WrappedPacketOutChat.load();
WrappedPacketOutEntity.load();
WrappedPacketOutEntityVelocity.load();
WrappedPacketOutKeepAlive.load();
WrappedPacketOutKickDisconnect.load();
WrappedPacketOutPosition.load();
WrappedPacketOutTransaction.load();
WrappedPacketOutUpdateHealth.load();
}
protected void setup() {
}
}
@@ -24,13 +24,13 @@
package io.github.retrooper.packetevents.packetwrappers.in.abilities;
import io.github.retrooper.packetevents.annotations.NotNull;
import io.github.retrooper.packetevents.annotations.Nullable;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
public final class WrappedPacketInAbilities extends WrappedPacket {
private static Class<?> abilitiesClass;
private static boolean isMoreThanOneBoolPresent;
private boolean isVulnerable;
private boolean isFlying;
@@ -38,30 +38,26 @@ public final class WrappedPacketInAbilities extends WrappedPacket {
private boolean instantBuild;
private float flySpeed;
private float walkSpeed;
public WrappedPacketInAbilities(Object packet) {
super(packet);
}
public static void load() {
abilitiesClass = PacketTypeClasses.Client.ABILITIES;
isMoreThanOneBoolPresent = Reflection.getField(abilitiesClass, boolean.class, 1) != null;
isMoreThanOneBoolPresent = Reflection.getField(PacketTypeClasses.Client.ABILITIES, boolean.class, 1) != null;
}
@Override
protected void setup() {
try {
if (isMoreThanOneBoolPresent) {
this.isVulnerable = Reflection.getField(abilitiesClass, boolean.class, 0).getBoolean(packet);
this.isFlying = Reflection.getField(abilitiesClass, boolean.class, 1).getBoolean(packet);
this.allowFly = Reflection.getField(abilitiesClass, boolean.class, 2).getBoolean(packet);
this.instantBuild = Reflection.getField(abilitiesClass, boolean.class, 3).getBoolean(packet);
this.flySpeed = Reflection.getField(abilitiesClass, float.class, 0).getFloat(packet);
this.walkSpeed = Reflection.getField(abilitiesClass, float.class, 1).getFloat(packet);
} else {
this.isFlying = Reflection.getField(abilitiesClass, boolean.class, 0).getBoolean(packet);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
if (isMoreThanOneBoolPresent) {
this.isVulnerable = readBoolean(0);
this.isFlying = readBoolean(1);
this.allowFly = readBoolean(2);
this.instantBuild = readBoolean(3);
this.flySpeed = readFloat(0);
this.walkSpeed = readFloat(1);
} else {
this.isFlying = readBoolean(0);
}
}
@@ -76,6 +72,7 @@ public final class WrappedPacketInAbilities extends WrappedPacket {
return isVulnerable;
}
@NotNull
public boolean isFlying() {
return isFlying;
}
@@ -25,7 +25,7 @@
package io.github.retrooper.packetevents.packetwrappers.in.armanimation;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
public final class WrappedPacketInArmAnimation extends WrappedPacket {
private static Class<?> packetClass;
@@ -27,9 +27,10 @@ package io.github.retrooper.packetevents.packetwrappers.in.blockdig;
import io.github.retrooper.packetevents.enums.Direction;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
import io.github.retrooper.packetevents.utils.vector.Vector3i;
public final class WrappedPacketInBlockDig extends WrappedPacket {
@@ -59,7 +60,7 @@ public final class WrappedPacketInBlockDig extends WrappedPacket {
digTypeClass = NMSUtils.getNMSClass("EnumPlayerDigType");
} catch (ClassNotFoundException e) {
//It is probably a subclass
digTypeClass = Reflection.getSubClass(blockDigClass, "EnumPlayerDigType");
digTypeClass = SubclassUtil.getSubClass(blockDigClass, "EnumPlayerDigType");
}
}
}
@@ -72,24 +73,24 @@ public final class WrappedPacketInBlockDig extends WrappedPacket {
//1.7.10
try {
if (isVersionLowerThan_v_1_8) {
enumDigType = PlayerDigType.values()[(Reflection.getField(blockDigClass, int.class, 4).getInt(packet))];
x = Reflection.getField(blockDigClass, int.class, 0).getInt(packet);
y = Reflection.getField(blockDigClass, int.class, 1).getInt(packet);
z = Reflection.getField(blockDigClass, int.class, 2).getInt(packet);
enumDigType = PlayerDigType.values()[(readInt(4))];
x = readInt(0);
y = readInt(1);
z = readInt(2);
enumDirection = null;
} else {
//1.8+
final Object blockPosObj = Reflection.getField(blockDigClass, blockPositionClass, 0).get(packet);
final Object enumDirectionObj = Reflection.getField(blockDigClass, enumDirectionClass, 0).get(packet);
final Object digTypeObj = Reflection.getField(blockDigClass, digTypeClass, 0).get(packet);
final Object blockPosObj = readObject(0, blockPositionClass);
final Object enumDirectionObj = readObject(0, enumDirectionClass);
final Object digTypeObj = readObject(0, digTypeClass);
Class<?> blockPosSuper = blockPositionClass;
x = Reflection.getField(blockPosSuper, int.class, 0).getInt(blockPosObj);
y = Reflection.getField(blockPosSuper, int.class, 1).getInt(blockPosObj);
z = Reflection.getField(blockPosSuper, int.class, 2).getInt(blockPosObj);
x = Reflection.getField(blockPositionClass, int.class, 0).getInt(blockPosObj);
y = Reflection.getField(blockPositionClass, int.class, 1).getInt(blockPosObj);
z = Reflection.getField(blockPositionClass, int.class, 2).getInt(blockPosObj);
enumDirection = Direction.valueOf(((Enum) enumDirectionObj).name());
enumDigType = PlayerDigType.valueOf(((Enum) digTypeObj).name());
//.toString() won't work so we must do this
enumDirection = Direction.valueOf(((Enum)enumDirectionObj).name());
enumDigType = PlayerDigType.valueOf(((Enum)digTypeObj).name());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
@@ -26,7 +26,7 @@ package io.github.retrooper.packetevents.packetwrappers.in.blockplace;
import io.github.retrooper.packetevents.annotations.Nullable;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.vector.Vector3i;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
@@ -24,7 +24,7 @@
package io.github.retrooper.packetevents.packetwrappers.in.blockplace;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.vector.Vector3i;
import net.minecraft.server.v1_7_R4.PacketPlayInBlockPlace;
import org.bukkit.entity.Player;
@@ -25,9 +25,9 @@
package io.github.retrooper.packetevents.packetwrappers.in.blockplace;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.vector.Vector3i;
import org.bukkit.inventory.ItemStack;
@@ -62,7 +62,7 @@ final class WrappedPacketInBlockPlace_1_8 extends WrappedPacket {
this.blockPosition.z = (int) Reflection.getMethod(blockPositionSuperClass, "getZ", 0).invoke(nmsBlockPos);
this.itemStack = NMSUtils.toBukkitItemStack(Reflection.getField(blockPlaceClass, NMSUtils.nmsItemStackClass, 0).get(packet));
this.itemStack = NMSUtils.toBukkitItemStack(readObject(0, NMSUtils.nmsItemStackClass));
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
@@ -25,7 +25,7 @@
package io.github.retrooper.packetevents.packetwrappers.in.blockplace;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.BlockIteratorUtils;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
@@ -25,8 +25,7 @@
package io.github.retrooper.packetevents.packetwrappers.in.chat;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
public final class WrappedPacketInChat extends WrappedPacket {
private static Class<?> chatPacketClass;
@@ -42,12 +41,7 @@ public final class WrappedPacketInChat extends WrappedPacket {
@Override
protected void setup() {
try {
final Object obj = Reflection.getField(chatPacketClass, String.class, 0).get(packet);
this.message = obj.toString();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
this.message = readString(0);
}
/**
@@ -25,9 +25,9 @@
package io.github.retrooper.packetevents.packetwrappers.in.clientcommand;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
public final class WrappedPacketInClientCommand extends WrappedPacket {
private static Class<?> packetClass;
@@ -45,22 +45,19 @@ public final class WrappedPacketInClientCommand extends WrappedPacket {
enumClientCommandClass = NMSUtils.getNMSClass("EnumClientCommand");
} catch (ClassNotFoundException e) {
//Probably a subclass
enumClientCommandClass = Reflection.getSubClass(packetClass, "EnumClientCommand");
enumClientCommandClass = SubclassUtil.getSubClass(packetClass, "EnumClientCommand");
}
}
@Override
public void setup() {
try {
Object enumObj = Reflection.getField(packetClass, enumClientCommandClass, 0).get(packet);
this.clientCommand = ClientCommand.valueOf(enumObj.toString());
} catch (Exception e) {
e.printStackTrace();
}
Object enumObj = readObject(0, enumClientCommandClass);
this.clientCommand = ClientCommand.valueOf(enumObj.toString());
}
/**
* Get the Client Command enum sent in the packet
*
* @return ClientCommand
*/
public ClientCommand getClientCommand() {
@@ -26,9 +26,9 @@ package io.github.retrooper.packetevents.packetwrappers.in.custompayload;
import io.github.retrooper.packetevents.annotations.Nullable;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import java.lang.reflect.Field;
@@ -54,19 +54,15 @@ public final class WrappedPacketInCustomPayload extends WrappedPacket {
//Only on 1.13+
nmsMinecraftKey = NMSUtils.getNMSClass("MinecraftKey");
} catch (ClassNotFoundException e) {
//Its okay, this means they are on versions 1.7.10 ~ 1.12.2
//Its okay, this means they are on versions 1.7.10 - 1.12.2
}
}
@Override
public void setup() {
if (!strPresentInIndex0) {
try {
this.minecraftKey = Reflection.getField(packetClass, nmsMinecraftKey, 0).get(packet);
this.dataSerializer = Reflection.getField(packetClass, nmsPacketDataSerializer, 0).get(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
this.minecraftKey = readObject(0, nmsMinecraftKey);
this.dataSerializer = readObject(0, nmsPacketDataSerializer);
} else {
Field dataSerializerField = Reflection.getField(packetClass, nmsPacketDataSerializer, 0);
@@ -26,10 +26,9 @@ package io.github.retrooper.packetevents.packetwrappers.in.entityaction;
import io.github.retrooper.packetevents.annotations.Nullable;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
import org.bukkit.entity.Entity;
import java.util.HashMap;
@@ -45,15 +44,16 @@ public final class WrappedPacketInEntityAction extends WrappedPacket {
private int entityId;
private PlayerAction action;
private int jumpBoost;
public WrappedPacketInEntityAction(final Object packet) {
super(packet);
}
public static void load() {
entityActionClass = PacketTypeClasses.Client.ENTITY_ACTION;
entityActionClass = NMSUtils.getNMSClassWithoutException("PacketPlayInEntityAction");
isLowerThan_v_1_8 = version.isLowerThan(ServerVersion.v_1_8);
if (version.isHigherThan(ServerVersion.v_1_7_10)) {
enumPlayerActionClass = Reflection.getSubClass(entityActionClass, "EnumPlayerAction");
if (!isLowerThan_v_1_8) {
enumPlayerActionClass = SubclassUtil.getSubClass(entityActionClass, "EnumPlayerAction");
}
//All the already existing values
for (PlayerAction val : PlayerAction.values()) {
@@ -76,45 +76,46 @@ public final class WrappedPacketInEntityAction extends WrappedPacket {
@Override
protected void setup() {
try {
final int entityId = Reflection.getField(entityActionClass, int.class, 0).getInt(packet);
final int jumpBoost;
if (isLowerThan_v_1_8) {
jumpBoost = Reflection.getField(entityActionClass, int.class, 2).getInt(packet);
} else {
jumpBoost = Reflection.getField(entityActionClass, int.class, 1).getInt(packet);
}
//1.7.10
if (isLowerThan_v_1_8) {
int animationIndex = Reflection.getField(entityActionClass, int.class, 1).getInt(packet); // TODO: += if packetdataserializer.version < 16
this.action = cachedPlayerActionIDs.get(animationIndex);
} else {
final Object enumObj = Reflection.getField(entityActionClass, enumPlayerActionClass, 0).get(packet);
final String enumName = enumObj.toString();
this.action = cachedPlayerActionNames.get(enumName);
}
this.entityId = entityId;
this.jumpBoost = jumpBoost;
} catch (IllegalAccessException e) {
e.printStackTrace();
final int entityId = readInt(0);
final int jumpBoost;
if (isLowerThan_v_1_8) {
jumpBoost = readInt(2);
} else {
jumpBoost = readInt(1);
}
//1.7.10
if (isLowerThan_v_1_8) {
int animationIndex = readInt(1);
this.action = cachedPlayerActionIDs.get(animationIndex);
} else {
final Object enumObj = readObject(0, enumPlayerActionClass);
final String enumValueName = enumObj.toString();
this.action = cachedPlayerActionNames.get(enumValueName);
}
this.entityId = entityId;
this.jumpBoost = jumpBoost;
}
/**
* Lookup the associated entity by the ID that was sent in the packet.
*
* @return Entity
*/
public Entity getEntity() {
return NMSUtils.getEntityById(this.entityId);
if(entity == null) {
return entity = NMSUtils.getEntityById(this.entityId);
}
return entity;
}
/**
* Get the ID of the entity.
* If you do not want to use {@link #getEntity()},
* you lookup the entity by yourself with this entity ID.
*
* @return Entity ID
*/
public int getEntityId() {
@@ -123,6 +124,7 @@ public final class WrappedPacketInEntityAction extends WrappedPacket {
/**
* Get the player action.
*
* @return Player Action
*/
public PlayerAction getAction() {
@@ -131,6 +133,7 @@ public final class WrappedPacketInEntityAction extends WrappedPacket {
/**
* Get the jump boost integer.
*
* @return Jump Boost
*/
public int getJumpBoost() {
@@ -26,19 +26,18 @@ package io.github.retrooper.packetevents.packetwrappers.in.flying;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
public class WrappedPacketInFlying extends WrappedPacket {
private static Class<?> flyingClass;
protected double x;
protected double y;
protected double z;
protected float yaw;
protected float pitch;
protected boolean onGround;
protected boolean isPosition;
protected boolean isLook;
private double x;
private double y;
private double z;
private float yaw;
private float pitch;
private boolean onGround;
private boolean isPosition;
private boolean isLook;
public WrappedPacketInFlying(Object packet) {
super(packet);
}
@@ -49,45 +48,40 @@ public class WrappedPacketInFlying extends WrappedPacket {
@Override
protected void setup() {
try {
//x, y, z, yaw pitch, onGround, isPosition, isLook
this.x = Reflection.getField(flyingClass, double.class, 0).getDouble(packet);
this.y = Reflection.getField(flyingClass, double.class, 1).getDouble(packet);
this.z = Reflection.getField(flyingClass, double.class, 2).getDouble(packet);
x = readDouble(0);
y = readDouble(1);
z = readDouble(2);
this.yaw = Reflection.getField(flyingClass, float.class, 0).getFloat(packet);
this.pitch = Reflection.getField(flyingClass, float.class, 1).getFloat(packet);
yaw = readFloat(0);
pitch = readFloat(1);
this.onGround = Reflection.getField(flyingClass, boolean.class, 0).getBoolean(packet);
onGround = readBoolean(0);
this.isPosition = Reflection.getField(flyingClass, boolean.class, 1).getBoolean(packet);
this.isLook = Reflection.getField(flyingClass, boolean.class, 2).getBoolean(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
isPosition = readBoolean(1);
isLook = readBoolean(2);
}
public final double getX() {
public double getX() {
return x;
}
public final double getY() {
public double getY() {
return y;
}
public final double getZ() {
public double getZ() {
return z;
}
public final float getYaw() {
public float getYaw() {
return yaw;
}
public final float getPitch() {
public float getPitch() {
return pitch;
}
public final boolean isOnGround() {
public boolean isOnGround() {
return onGround;
}
@@ -99,82 +93,4 @@ public class WrappedPacketInFlying extends WrappedPacket {
return isLook;
}
public static class WrappedPacketInPosition extends WrappedPacketInFlying {
public WrappedPacketInPosition(Object packet) {
super(packet);
}
@Override
protected void setup() {
try {
this.x = Reflection.getField(flyingClass, double.class, 0).getDouble(packet);
this.y = Reflection.getField(flyingClass, double.class, 1).getDouble(packet);
this.z = Reflection.getField(flyingClass, double.class, 2).getDouble(packet);
this.yaw = Reflection.getField(flyingClass, float.class, 0).getFloat(packet);
this.pitch = Reflection.getField(flyingClass, float.class, 1).getFloat(packet);
this.onGround = Reflection.getField(flyingClass, boolean.class, 0).getBoolean(packet);
this.isPosition = Reflection.getField(flyingClass, boolean.class, 1).getBoolean(packet);
this.isLook = Reflection.getField(flyingClass, boolean.class, 2).getBoolean(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
public static class WrappedPacketInPosition_Look extends WrappedPacketInFlying {
public WrappedPacketInPosition_Look(Object packet) {
super(packet);
}
@Override
protected void setup() {
try {
this.x = Reflection.getField(flyingClass, double.class, 0).getDouble(packet);
this.y = Reflection.getField(flyingClass, double.class, 1).getDouble(packet);
this.z = Reflection.getField(flyingClass, double.class, 2).getDouble(packet);
this.yaw = Reflection.getField(flyingClass, float.class, 0).getFloat(packet);
this.pitch = Reflection.getField(flyingClass, float.class, 1).getFloat(packet);
this.onGround = Reflection.getField(flyingClass, boolean.class, 0).getBoolean(packet);
this.isPosition = Reflection.getField(flyingClass, boolean.class, 1).getBoolean(packet);
this.isLook = Reflection.getField(flyingClass, boolean.class, 2).getBoolean(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
public static class WrappedPacketInLook extends WrappedPacketInFlying {
public WrappedPacketInLook(Object packet) {
super(packet);
}
@Override
protected void setup() {
try {
this.x = Reflection.getField(flyingClass, double.class, 0).getDouble(packet);
this.y = Reflection.getField(flyingClass, double.class, 1).getDouble(packet);
this.z = Reflection.getField(flyingClass, double.class, 2).getDouble(packet);
this.yaw = Reflection.getField(flyingClass, float.class, 0).getFloat(packet);
this.pitch = Reflection.getField(flyingClass, float.class, 1).getFloat(packet);
this.onGround = Reflection.getField(flyingClass, boolean.class, 0).getBoolean(packet);
this.isPosition = Reflection.getField(flyingClass, boolean.class, 1).getBoolean(packet);
this.isLook = Reflection.getField(flyingClass, boolean.class, 2).getBoolean(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
@@ -25,8 +25,7 @@
package io.github.retrooper.packetevents.packetwrappers.in.helditemslot;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
public final class WrappedPacketInHeldItemSlot extends WrappedPacket {
private static Class<?> packetClass;
@@ -43,7 +42,7 @@ public final class WrappedPacketInHeldItemSlot extends WrappedPacket {
@Override
public void setup() {
try {
itemInHandIndex = Reflection.getField(packetClass, int.class, 0).getInt(packet);
itemInHandIndex = readInt(0);
} catch (Exception e) {
e.printStackTrace();
}
@@ -25,8 +25,8 @@
package io.github.retrooper.packetevents.packetwrappers.in.keepalive;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
public final class WrappedPacketInKeepAlive extends WrappedPacket {
private static Class<?> packetClass;
@@ -45,17 +45,9 @@ public final class WrappedPacketInKeepAlive extends WrappedPacket {
@Override
protected void setup() {
if (!integerPresentInIndex0) {
try {
this.id = Reflection.getField(packetClass, long.class, 0).getLong(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
this.id = readLong(0);
} else {
try {
this.id = Reflection.getField(packetClass, int.class, 0).getInt(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
this.id = readInt(0);
}
}
@@ -63,7 +55,7 @@ public final class WrappedPacketInKeepAlive extends WrappedPacket {
* Get the ID response from the client.
*
* You may cast this down to an int if you are on 1.7.10 - 1.12.2.
* On 1.13.2 - 1.16.2 a long is sent.
* On 1.13.2 - 1.16.3 a long is sent.
* @return response ID
*/
public long getId() {
@@ -27,9 +27,9 @@ package io.github.retrooper.packetevents.packetwrappers.in.settings;
import io.github.retrooper.packetevents.annotations.Nullable;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
import java.util.HashMap;
@@ -39,10 +39,11 @@ public class WrappedPacketInSettings extends WrappedPacket {
private static boolean isLowerThan_v_1_8;
private String locale;
private byte viewDistance;
private int viewDistance;
private ChatVisibility chatVisibility;
private boolean chatColors;
private HashMap<DisplayedSkinPart, Boolean> displayedSkinParts;
public WrappedPacketInSettings(final Object packet) {
super(packet);
}
@@ -57,7 +58,8 @@ public class WrappedPacketInSettings extends WrappedPacket {
} catch (ClassNotFoundException e) {
Class<?> entityHumanClass = NMSUtils.getNMSClassWithoutException("EntityHuman");
//They are just on an outdated version
chatVisibilityEnumClass = Reflection.getSubClass(entityHumanClass, "EnumChatVisibility");
assert entityHumanClass != null;
chatVisibilityEnumClass = SubclassUtil.getSubClass(entityHumanClass, "EnumChatVisibility");
}
}
@@ -69,12 +71,12 @@ public class WrappedPacketInSettings extends WrappedPacket {
protected void setup() {
try {
//LOCALE
this.locale = Reflection.getField(packetClass, String.class, 0).get(packet).toString();
this.locale = readString(0);
//VIEW DISTANCE
this.viewDistance = (byte) Reflection.getField(packetClass, int.class, 0).getInt(packet);
this.viewDistance = readInt(0);
//CHAT VISIBILITY
Object chatVisibilityEnumObject = Reflection.getField(packetClass, chatVisibilityEnumClass, 0).get(packet);
Object chatVisibilityEnumObject = readObject(0, chatVisibilityEnumClass);
String enumValueAsString = chatVisibilityEnumObject.toString();
if (enumValueAsString.equals("FULL")) {
chatVisibility = ChatVisibility.ENABLED;
@@ -85,18 +87,18 @@ public class WrappedPacketInSettings extends WrappedPacket {
}
//CHAT COLORS
this.chatColors = Reflection.getField(packetClass, boolean.class, 0).getBoolean(packet);
this.chatColors = readBoolean(0);
//DISPLAYED SKIN PARTS
this.displayedSkinParts = new HashMap<DisplayedSkinPart, Boolean>();
if (isLowerThan_v_1_8) {
//in 1.7.10 only the cape display skin part is sent
boolean capeEnabled = Reflection.getField(packetClass, boolean.class, 1).getBoolean(packet);
boolean capeEnabled = readBoolean(1);
displayedSkinParts.put(DisplayedSkinPart.CAPE, capeEnabled);
} else {
//in 1.8, all the skin parts are sent
int skinPartFlags = Reflection.getField(packetClass, int.class, 1).getInt(packet);
int skinPartFlags = readInt(1);
displayedSkinParts.put(DisplayedSkinPart.CAPE, (skinPartFlags & 0x01) != 0);
displayedSkinParts.put(DisplayedSkinPart.JACKET, (skinPartFlags & 0x02) != 0);
displayedSkinParts.put(DisplayedSkinPart.LEFT_SLEEVE, (skinPartFlags & 0x04) != 0);
@@ -114,6 +116,7 @@ public class WrappedPacketInSettings extends WrappedPacket {
/**
* Get language client setting
*
* @return String Locale
*/
public String getLocale() {
@@ -122,14 +125,16 @@ public class WrappedPacketInSettings extends WrappedPacket {
/**
* Get client view distance.
*
* @return View Distance
*/
public byte getViewDistance() {
public int getViewDistance() {
return viewDistance;
}
/**
* Get Chat Visibility
*
* @return Chat Visibility
*/
public ChatVisibility getChatVisibility() {
@@ -138,6 +143,7 @@ public class WrappedPacketInSettings extends WrappedPacket {
/**
* Is chat colors
*
* @return Chat Colors
*/
public boolean isChatColors() {
@@ -146,7 +152,7 @@ public class WrappedPacketInSettings extends WrappedPacket {
/**
* Get Displayed skin parts.
*
* <p>
* It is possible for some keys to not exist.
* If that is the case, the server version is 1.7.10.
* 1.7.10 only sends the cape skin part.
@@ -160,7 +166,7 @@ public class WrappedPacketInSettings extends WrappedPacket {
/**
* Is the skin part enabled.
*
* <p>
* On 1.7.10, some skin parts will default to 'false' as 1.7.10
* only sends the 'cape' skin part.
*
@@ -25,8 +25,7 @@
package io.github.retrooper.packetevents.packetwrappers.in.steervehicle;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
public class WrappedPacketInSteerVehicle extends WrappedPacket {
private static Class<?> packetClass;
@@ -42,15 +41,11 @@ public class WrappedPacketInSteerVehicle extends WrappedPacket {
@Override
protected void setup() {
try {
this.side = Reflection.getField(packetClass, float.class, 0).getFloat(packet);
this.forward = Reflection.getField(packetClass, float.class, 1).getFloat(packet);
this.side = readFloat(0);
this.forward = readFloat(1);
this.jump = Reflection.getField(packetClass, boolean.class, 0).getBoolean(packet);
this.unmount = Reflection.getField(packetClass, boolean.class, 1).getBoolean(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
this.jump = readBoolean(0);
this.unmount = readBoolean(1);
}
/**
@@ -25,8 +25,7 @@
package io.github.retrooper.packetevents.packetwrappers.in.transaction;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
public final class WrappedPacketInTransaction extends WrappedPacket {
private static Class<?> packetClass;
@@ -43,14 +42,9 @@ public final class WrappedPacketInTransaction extends WrappedPacket {
@Override
protected void setup() {
try {
this.windowId = Reflection.getField(packetClass, int.class, 0).getInt(packet);
this.actionNumber = Reflection.getField(packetClass, short.class, 0).getShort(packet);
this.accepted = Reflection.getField(packetClass, boolean.class, 0).getBoolean(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
this.windowId = readInt(0);
this.actionNumber = readShort(0);
this.accepted = readBoolean(0);
}
/**
@@ -0,0 +1,106 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.packetwrappers.in.updatesign;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.out.chat.WrappedPacketOutChat;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
public class WrappedPacketInUpdateSign extends WrappedPacket {
private static boolean v_1_7_mode, strArrayMode;
private static Class<?> blockPosClass, iChatBaseComponentClass;
private int x, y, z;
private String[] lines;
public static void load() {
v_1_7_mode = Reflection.getField(PacketTypeClasses.Client.UPDATE_SIGN, int.class, 0) != null;
strArrayMode = Reflection.getField(PacketTypeClasses.Client.UPDATE_SIGN, String[].class, 0) != null;
try {
blockPosClass = NMSUtils.getNMSClass("BlockPosition");
} catch (ClassNotFoundException e) {
if (!v_1_7_mode) {
e.printStackTrace();
}
}
try {
iChatBaseComponentClass = NMSUtils.getNMSClass("IChatBaseComponent");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public WrappedPacketInUpdateSign(Object packet) {
super(packet);
}
@Override
protected void setup() {
if (v_1_7_mode) {
x = readInt(0);
y = readInt(1);
z = readInt(2);
} else {
Object blockPos = readObject(0, blockPosClass);
try {
x = Reflection.getField(blockPosClass, int.class, 0).getInt(packet);
y = Reflection.getField(blockPosClass, int.class, 1).getInt(packet);
z = Reflection.getField(blockPosClass, int.class, 2).getInt(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
if (strArrayMode) {
//1.7.10 and the newest versions use this
lines = readStringArray(0);
} else {
//1.8 uses this for example
Object[] iChatComponents = readObjectArray(0, iChatBaseComponentClass);
for (int i = 0; i < iChatComponents.length; i++) {
lines[i] = WrappedPacketOutChat.
toStringFromIChatBaseComponent(iChatComponents[i]);
}
}
}
public int getBlockPositionX() {
return x;
}
public int getBlockPositionY() {
return y;
}
public int getBlockPositionZ() {
return z;
}
public String[] getTextLines() {
return lines;
}
}
@@ -24,15 +24,15 @@
package io.github.retrooper.packetevents.packetwrappers.in.useentity;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
import org.bukkit.entity.Entity;
public final class WrappedPacketInUseEntity extends WrappedPacket {
private static Class<?> useEntityClass;
private static Class<?> enumEntityUseActionClass;
private Entity entity;
private int entityID;
private EntityUseAction action;
public WrappedPacketInUseEntity(final Object packet) {
@@ -40,25 +40,27 @@ public final class WrappedPacketInUseEntity extends WrappedPacket {
}
public static void load() {
useEntityClass = PacketTypeClasses.Client.USE_ENTITY;
//System.out.println("USE ENTITY HAS BEEN LOADED BROOOIOII");
useEntityClass = NMSUtils.getNMSClassWithoutException("PacketPlayInUseEntity");
/*if(useEntityClass == null) {
System.out.println("failed to init use entity wtfffff");
}*/
try {
enumEntityUseActionClass = NMSUtils.getNMSClass("EnumEntityUseAction");
} catch (ClassNotFoundException e) {
//That is fine, it is probably a subclass
enumEntityUseActionClass = Reflection.getSubClass(useEntityClass, "EnumEntityUseAction");
enumEntityUseActionClass = SubclassUtil.getSubClass(useEntityClass, "EnumEntityUseAction");
}
}
@Override
protected void setup() {
try {
this.entityID = Reflection.getField(useEntityClass, int.class, 0).getInt(packet);
final Object useActionEnum = Reflection.getField(useEntityClass, enumEntityUseActionClass, 0).get(packet);
this.action = EntityUseAction.valueOf(useActionEnum.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
this.entityID = readInt(0);
if(enumEntityUseActionClass == null) {
System.out.println("cls is null");
}
final Object useActionEnum = readObject(0, enumEntityUseActionClass);
this.action = EntityUseAction.valueOf(useActionEnum.toString());
}
/**
@@ -66,7 +68,10 @@ public final class WrappedPacketInUseEntity extends WrappedPacket {
* @return Entity
*/
public Entity getEntity() {
return NMSUtils.getEntityById(this.entityID);
if(entity != null) {
return entity;
}
return entity = NMSUtils.getEntityById(this.entityID);
}
/**
@@ -24,11 +24,10 @@
package io.github.retrooper.packetevents.packetwrappers.in.windowclick;
import io.github.retrooper.packetevents.annotations.Nullable;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
@@ -114,22 +113,18 @@ public class WrappedPacketInWindowClick extends WrappedPacket {
@Override
protected void setup() {
try {
this.id = Reflection.getField(packetClass, int.class, 0).getInt(packet);
this.slot = Reflection.getField(packetClass, int.class, 1).getInt(packet);
this.button = Reflection.getField(packetClass, int.class, 2).getInt(packet);
this.actionNumber = Reflection.getField(packetClass, short.class, 0).getShort(packet);
Object nmsItemStack = Reflection.getField(packetClass, NMSUtils.nmsItemStackClass, 0).get(packet);
this.clickedItem = NMSUtils.toBukkitItemStack(nmsItemStack);
Object clickMode = Reflection.getField(packetClass, 5).get(packet);
this.id = readInt(0);
this.slot = readInt(1);
this.button = readInt(2);
this.actionNumber = readShort(0);
Object nmsItemStack = readObject(0, NMSUtils.nmsItemStackClass);
this.clickedItem = NMSUtils.toBukkitItemStack(nmsItemStack);
Object clickMode = readAnyObject(5);
if (isClickModePrimitive) {
mode = (int) clickMode;
} else {
mode = invClickTypeMapCache.get(clickMode.toString());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
if (isClickModePrimitive) {
mode = (int) clickMode;
} else {
mode = invClickTypeMapCache.get(clickMode.toString());
}
}
@@ -24,8 +24,8 @@
package io.github.retrooper.packetevents.packetwrappers.out.abilities;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
@@ -25,14 +25,13 @@
package io.github.retrooper.packetevents.packetwrappers.out.abilities;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.Sendable;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public final class WrappedPacketOutAbilities extends WrappedPacket implements Sendable {
public final class WrappedPacketOutAbilities extends WrappedPacket implements SendableWrapper {
private static Class<?> packetClass;
private static Constructor<?> packetConstructor;
private boolean vulnerable, flying, allowFlight, instantBuild;
@@ -64,18 +63,13 @@ public final class WrappedPacketOutAbilities extends WrappedPacket implements Se
@Override
protected void setup() {
try {
this.vulnerable = Reflection.getField(packetClass, boolean.class, 0).getBoolean(packet);
this.flying = Reflection.getField(packetClass, boolean.class, 1).getBoolean(packet);
this.allowFlight = Reflection.getField(packetClass, boolean.class, 2).getBoolean(packet);
this.instantBuild = Reflection.getField(packetClass, boolean.class, 3).getBoolean(packet);
this.flySpeed = Reflection.getField(packetClass, float.class, 0).getFloat(packet);
this.walkSpeed = Reflection.getField(packetClass, float.class, 0).getFloat(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
this.vulnerable = readBoolean(0);
this.flying = readBoolean(1);
this.allowFlight = readBoolean(2);
this.instantBuild = readBoolean(3);
this.flySpeed = readFloat(0);
this.walkSpeed = readFloat(1);
}
/**
@@ -25,17 +25,16 @@
package io.github.retrooper.packetevents.packetwrappers.out.animation;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.Sendable;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import org.bukkit.entity.Entity;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
public final class WrappedPacketOutAnimation extends WrappedPacket implements Sendable {
public final class WrappedPacketOutAnimation extends WrappedPacket implements SendableWrapper {
private static Class<?> animationClass, nmsEntityClass;
private static Constructor<?> animationConstructor;
@@ -85,16 +84,9 @@ public final class WrappedPacketOutAnimation extends WrappedPacket implements Se
@Override
protected void setup() {
try {
//a - ID
//b - TYPE
this.entityID = Reflection.getField(animationClass, int.class, 0).getInt(packet);
int animationID = Reflection.getField(animationClass, int.class, 1).getInt(packet);
this.type = cachedAnimationIDS.get(animationID);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
this.entityID = readInt(0);
int animationID = readInt(1);
this.type = cachedAnimationIDS.get(animationID);
}
/**
@@ -25,11 +25,13 @@
package io.github.retrooper.packetevents.packetwrappers.out.chat;
import io.github.retrooper.packetevents.annotations.Beta;
import io.github.retrooper.packetevents.annotations.NotNull;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.Sendable;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
@@ -41,7 +43,7 @@ import java.util.UUID;
* This wrapper MIGHT not be stable
*/
@Beta
public final class WrappedPacketOutChat extends WrappedPacket implements Sendable {
public final class WrappedPacketOutChat extends WrappedPacket implements SendableWrapper {
private static Constructor<?> chatClassConstructor;
private static Class<?> packetClass, iChatBaseComponentClass, chatSerializerClass, chatMessageTypeEnum;
private static Method chatMessageTypeCreatorMethod;
@@ -61,6 +63,12 @@ public final class WrappedPacketOutChat extends WrappedPacket implements Sendabl
private ChatPosition chatPosition;
private UUID uuid;
@Deprecated
public WrappedPacketOutChat(String message) {
this(message, null);
}
public WrappedPacketOutChat(final Object packet) {
super(packet);
}
@@ -70,7 +78,6 @@ public final class WrappedPacketOutChat extends WrappedPacket implements Sendabl
}
public WrappedPacketOutChat(String message, ChatPosition chatPosition, UUID uuid) {
super();
this.uuid = uuid;
this.message = message;
this.chatPosition = chatPosition;
@@ -94,7 +101,7 @@ public final class WrappedPacketOutChat extends WrappedPacket implements Sendabl
chatSerializerClass = NMSUtils.getNMSClass("ChatSerializer");
} catch (ClassNotFoundException e) {
//That is fine, it is probably a subclass
chatSerializerClass = Reflection.getSubClass(iChatBaseComponentClass, "ChatSerializer");
chatSerializerClass = SubclassUtil.getSubClass(iChatBaseComponentClass, "ChatSerializer");
}
@@ -152,7 +159,7 @@ public final class WrappedPacketOutChat extends WrappedPacket implements Sendabl
}
public static String fromStringToJSON(String message) {
return "{\"text\": \"" + "use entity action name: " + message + "\"}";
return "{\"text\": \"" + message + "\"}";
}
public static String toStringFromIChatBaseComponent(Object obj) {
@@ -177,7 +184,7 @@ public final class WrappedPacketOutChat extends WrappedPacket implements Sendabl
@Override
protected void setup() {
try {
final Object iChatBaseObj = Reflection.getField(packetClass, iChatBaseComponentClass, 0).get(packet);
final Object iChatBaseObj = readObject(0, iChatBaseComponentClass);
final Object contentString = Reflection.getMethod(iChatBaseComponentClass, String.class, 0).invoke(iChatBaseObj);
@@ -186,14 +193,14 @@ public final class WrappedPacketOutChat extends WrappedPacket implements Sendabl
byte chatPosInteger = 0;
switch (constructorMode) {
case 0:
chatPosInteger = Reflection.getField(packetClass, byte.class, 0).getByte(packet);
chatPosInteger = readByte(0);
break;
case 1:
chatPosInteger = (byte) Reflection.getField(packetClass, int.class, 0).getInt(packet);
chatPosInteger = (byte) readInt(0);
break;
case 2:
case 3:
Object chatTypeEnumInstance = Reflection.getField(packetClass, chatMessageTypeEnum, 0).get(packet);
Object chatTypeEnumInstance = readObject(0, chatMessageTypeEnum);
chatPosInteger = cachedChatMessageTypeIntegers.get(chatTypeEnumInstance.toString());
break;
}
@@ -270,6 +277,7 @@ public final class WrappedPacketOutChat extends WrappedPacket implements Sendabl
* If an invalid chat position is sent, it will be defaulted it to CHAT.
* @return ChatPosition
*/
@NotNull
public ChatPosition getChatPosition() {
if(this.chatPosition == null) {
this.chatPosition = ChatPosition.CHAT;
@@ -0,0 +1,194 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.packetwrappers.out.custompayload;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.bytebuf.ByteBufUtil;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
public class WrappedPacketOutCustomPayload extends WrappedPacket implements SendableWrapper {
private static Class<?> packetClass;
private static Constructor<?> constructor;
private static Constructor<?> packetDataSerializerConstructor;
private static Constructor<?> minecraftKeyConstructor;
private static Class<?> byteBufClass;
private static Class<?> packetDataSerializerClass;
private static Class<?> minecraftKeyClass;
private static int minecraftKeyIndexInClass;
private static byte constructorMode = 0;
public static void load() {
packetClass = PacketTypeClasses.Server.CUSTOM_PAYLOAD;
packetDataSerializerClass = NMSUtils.getNMSClassWithoutException("PacketDataSerializer");
minecraftKeyClass = NMSUtils.getNMSClassWithoutException("MinecraftKey");
try {
byteBufClass = NMSUtils.getNettyClass("buffer.ByteBuf");
} catch (ClassNotFoundException e) {
}
try {
packetDataSerializerConstructor = packetDataSerializerClass.getConstructor(byteBufClass);
} catch (NullPointerException e) {
//Nothing
} catch (NoSuchMethodException e) {
//also nothing
}
try {
if (minecraftKeyClass != null) {
minecraftKeyConstructor = minecraftKeyClass.getConstructor(String.class);
}
} catch (NoSuchMethodException e) {
//Nothing
}
//Constructors:
//String, byte[]
//String, PacketDataSerializer
//MinecraftKey, PacketDataSerializer
try {
//1.7 constructor
constructor = packetClass.getConstructor(String.class, byte[].class);
constructorMode = 0;
} catch (NoSuchMethodException e) {
//That's fine, just a newer version
try {
constructor = packetClass.getConstructor(String.class, packetDataSerializerClass);
constructorMode = 1;
} catch (NoSuchMethodException e2) {
//That's fine, just an even newer version
try {
//Minecraft key exists
for (int i = 0; i < packetClass.getDeclaredFields().length; i++) {
Field f = packetClass.getDeclaredFields()[i];
if (!Modifier.isStatic(f.getModifiers())) {
minecraftKeyIndexInClass = i;
break;
}
}
constructor = packetClass.getConstructor(minecraftKeyClass, packetDataSerializerClass);
constructorMode = 2;
} catch (NoSuchMethodException e3) {
throw new IllegalStateException("PacketEvents is unable to resolve the PacketPlayOutCustomPayload constructor.");
}
}
}
}
private String tag;
private byte[] data;
public WrappedPacketOutCustomPayload(String tag, byte[] data) {
this.tag = tag;
this.data = data;
}
public WrappedPacketOutCustomPayload(Object packet) {
super(packet);
}
@Override
protected void setup() {
switch (constructorMode) {
case 0:
this.tag = readString(0);
this.data = readByteArray(0);
break;
case 1:
this.tag = readString(0);
Object dataSerializer = readObject(0, packetDataSerializerClass);
WrappedPacket byteBufWrapper = new WrappedPacket(dataSerializer);
Object byteBuf = byteBufWrapper.readObject(0, byteBufClass);
this.data = ByteBufUtil.getBytes(byteBuf);
break;
case 2:
Object minecraftKey = readObject(minecraftKeyIndexInClass, minecraftKeyClass);
WrappedPacket minecraftKeyWrapper = new WrappedPacket(minecraftKey);
this.tag = minecraftKeyWrapper.readString(1);
Object dataSerializer2 = readObject(0, packetDataSerializerClass);
WrappedPacket byteBuf2Wrapper = new WrappedPacket(dataSerializer2);
Object byteBuf2 = byteBuf2Wrapper.readObject(0, byteBufClass);
this.data = ByteBufUtil.getBytes(byteBuf2);
break;
}
}
public String getTag() {
return tag;
}
public byte[] getData() {
return data;
}
@Override
public Object asNMSPacket() {
Object byteBufObject = ByteBufUtil.copiedBuffer(data);
switch (constructorMode) {
case 0:
try {
return constructor.newInstance(tag, data);
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
break;
case 1:
try {
Object dataSerializer = packetDataSerializerConstructor.newInstance(byteBufObject);
return constructor.newInstance(tag, dataSerializer);
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
break;
case 2:
try {
Object minecraftKey = minecraftKeyConstructor.newInstance(tag);
Object dataSerializer = packetDataSerializerConstructor.newInstance(byteBufObject);
return constructor.newInstance(minecraftKey, dataSerializer);
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
break;
}
return null;
}
}
@@ -25,9 +25,9 @@
package io.github.retrooper.packetevents.packetwrappers.out.entity;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import org.bukkit.entity.Entity;
import java.lang.reflect.Field;
@@ -37,10 +37,12 @@ public class WrappedPacketOutEntity extends WrappedPacket {
//Byte = 1.7.10->1.8.8, Int = 1.9->1.15.x, Short = 1.16.x
private static byte mode = 0; //byte = 0, int = 1, short = 2
private static double dXYZDivisor = 0.0;
private Entity entity;
private int entityID;
private double deltaX, deltaY, deltaZ;
private byte yaw, pitch;
private boolean onGround;
public WrappedPacketOutEntity(Object packet) {
super(packet);
}
@@ -68,43 +70,40 @@ public class WrappedPacketOutEntity extends WrappedPacket {
@Override
protected void setup() {
try {
this.entityID = Reflection.getField(packetClass, int.class, 0).getInt(packet);
this.onGround = Reflection.getField(packetClass, boolean.class, 0).getBoolean(packet);
int dX = 1, dY = 1, dZ = 1;
switch (mode) {
case 0:
dX = Reflection.getField(packetClass, byte.class, 0).getByte(packet);
dY = Reflection.getField(packetClass, byte.class, 1).getByte(packet);
dZ = Reflection.getField(packetClass, byte.class, 2).getByte(packet);
this.yaw = Reflection.getField(packetClass, byte.class, 3).getByte(packet);
this.pitch = Reflection.getField(packetClass, byte.class, 4).getByte(packet);
break;
case 1:
dX = Reflection.getField(packetClass, int.class, 1).getInt(packet);
dY = Reflection.getField(packetClass, int.class, 2).getInt(packet);
dZ = Reflection.getField(packetClass, int.class, 3).getInt(packet);
this.yaw = Reflection.getField(packetClass, byte.class, 0).getByte(packet);
this.pitch = Reflection.getField(packetClass, byte.class, 1).getByte(packet);
break;
case 2:
dX = Reflection.getField(packetClass, short.class, 0).getShort(packet);
dY = Reflection.getField(packetClass, short.class, 1).getShort(packet);
dZ = Reflection.getField(packetClass, short.class, 2).getShort(packet);
this.yaw = Reflection.getField(packetClass, byte.class, 0).getByte(packet);
this.pitch = Reflection.getField(packetClass, byte.class, 1).getByte(packet);
break;
}
this.deltaX = dX / dXYZDivisor;
this.deltaY = dY / dXYZDivisor;
this.deltaZ = dZ / dXYZDivisor;
} catch (IllegalAccessException e) {
e.printStackTrace();
this.entityID = readInt(0);
this.onGround = readBoolean(0);
int dX = 1, dY = 1, dZ = 1;
switch (mode) {
case 0:
dX = readByte(0);
dY = readByte(1);
dZ = readByte(2);
this.yaw = readByte(3);
this.pitch = readByte(4);
break;
case 1:
dX = readInt(1);
dY = readInt(2);
dZ = readInt(3);
this.yaw = readByte(0);
this.pitch = readByte(1);
break;
case 2:
dX = readShort(0);
dY = readShort(1);
dZ = readShort(2);
this.yaw = readByte(0);
this.pitch = readByte(1);
break;
}
this.deltaX = dX / dXYZDivisor;
this.deltaY = dY / dXYZDivisor;
this.deltaZ = dZ / dXYZDivisor;
}
/**
* Get the pitch.
*
* @return Get Byte Pitch
*/
public byte getPitch() {
@@ -113,6 +112,7 @@ public class WrappedPacketOutEntity extends WrappedPacket {
/**
* Get the Yaw.
*
* @return Get Byte Yaw
*/
public byte getYaw() {
@@ -121,6 +121,7 @@ public class WrappedPacketOutEntity extends WrappedPacket {
/**
* Get the Delta X
*
* @return Delta X
*/
public double getDeltaX() {
@@ -129,6 +130,7 @@ public class WrappedPacketOutEntity extends WrappedPacket {
/**
* Get the Delta Y
*
* @return Delta Y
*/
public double getDeltaY() {
@@ -137,6 +139,7 @@ public class WrappedPacketOutEntity extends WrappedPacket {
/**
* Get the Delta Z
*
* @return Delta Z
*/
public double getDeltaZ() {
@@ -145,16 +148,21 @@ public class WrappedPacketOutEntity extends WrappedPacket {
/**
* Lookup the associated entity by the ID that was sent in the packet.
*
* @return Entity
*/
public Entity getEntity() {
return NMSUtils.getEntityById(this.entityID);
if (entity != null) {
return entity;
}
return entity = NMSUtils.getEntityById(this.entityID);
}
/**
* Get the ID of the entity.
* If you do not want to use {@link #getEntity()},
* you lookup the entity by yourself with this entity ID.
*
* @return Entity ID
*/
public int getEntityId() {
@@ -163,9 +171,305 @@ public class WrappedPacketOutEntity extends WrappedPacket {
/**
* Is the entity on the ground?
*
* @return On Ground
*/
public boolean isOnGround() {
return onGround;
}
public static class WrappedPacketOutRelEntityMove extends WrappedPacket {
private int entityID;
private Entity entity;
private double deltaX, deltaY, deltaZ;
private boolean onGround;
public WrappedPacketOutRelEntityMove(Object packet) {
super(packet);
}
@Override
protected void setup() {
int dX = 1, dY = 1, dZ = 1;
switch (mode) {
case 0:
dX = readByte(0);
dY = readByte(1);
dZ = readByte(2);
break;
case 1:
dX = readInt(1);
dY = readInt(2);
dZ = readInt(3);
break;
case 2:
dX = readShort(0);
dY = readShort(1);
dZ = readShort(2);
break;
}
deltaX = dX / dXYZDivisor;
deltaY = dY / dXYZDivisor;
deltaZ = dZ / dXYZDivisor;
}
/**
* Get the Delta X
*
* @return Delta X
*/
public double getDeltaX() {
return deltaX;
}
/**
* Get the Delta Y
*
* @return Delta Y
*/
public double getDeltaY() {
return deltaY;
}
/**
* Get the Delta Z
*
* @return Delta Z
*/
public double getDeltaZ() {
return deltaZ;
}
/**
* Lookup the associated entity by the ID that was sent in the packet.
*
* @return Entity
*/
public Entity getEntity() {
if (entity != null) {
return entity;
}
return entity = NMSUtils.getEntityById(this.entityID);
}
/**
* Get the ID of the entity.
* If you do not want to use {@link #getEntity()},
* you lookup the entity by yourself with this entity ID.
*
* @return Entity ID
*/
public int getEntityId() {
return entityID;
}
/**
* Is the entity on the ground?
*
* @return On Ground
*/
public boolean isOnGround() {
return onGround;
}
}
public static class WrappedPacketOutRelEntityMoveLook extends WrappedPacket {
private int entityID;
private Entity entity;
private double deltaX, deltaY, deltaZ;
private byte yaw, pitch;
private boolean onGround;
public WrappedPacketOutRelEntityMoveLook(Object packet) {
super(packet);
}
@Override
protected void setup() {
entityID = readInt(0);
onGround = readBoolean(0);
int dX = 1, dY = 1, dZ = 1;
switch (mode) {
case 0:
dX = readByte(0);
dY = readByte(1);
dZ = readByte(2);
yaw = readByte(3);
pitch = readByte(4);
break;
case 1:
dX = readInt(1);
dY = readInt(2);
dZ = readInt(3);
yaw = readByte(0);
pitch = readByte(1);
break;
case 2:
dX = readShort(0);
dY = readShort(1);
dZ = readShort(2);
yaw = readByte(0);
pitch = readByte(1);
break;
}
deltaX = dX / dXYZDivisor;
deltaY = dY / dXYZDivisor;
deltaZ = dZ / dXYZDivisor;
}
/**
* Get the pitch.
*
* @return Get Byte Pitch
*/
public byte getPitch() {
return pitch;
}
/**
* Get the Yaw.
*
* @return Get Byte Yaw
*/
public byte getYaw() {
return yaw;
}
/**
* Get the Delta X
*
* @return Delta X
*/
public double getDeltaX() {
return deltaX;
}
/**
* Get the Delta Y
*
* @return Delta Y
*/
public double getDeltaY() {
return deltaY;
}
/**
* Get the Delta Z
*
* @return Delta Z
*/
public double getDeltaZ() {
return deltaZ;
}
/**
* Lookup the associated entity by the ID that was sent in the packet.
*
* @return Entity
*/
public Entity getEntity() {
if (entity != null) {
return entity;
}
return entity = NMSUtils.getEntityById(this.entityID);
}
/**
* Get the ID of the entity.
* If you do not want to use {@link #getEntity()},
* you lookup the entity by yourself with this entity ID.
*
* @return Entity ID
*/
public int getEntityId() {
return entityID;
}
/**
* Is the entity on the ground?
*
* @return On Ground
*/
public boolean isOnGround() {
return onGround;
}
}
public static class WrappedPacketOutRelEntityLook extends WrappedPacket {
private int entityID;
private Entity entity;
private byte yaw, pitch;
private boolean onGround;
public WrappedPacketOutRelEntityLook(Object packet) {
super(packet);
}
@Override
protected void setup() {
entityID = readInt(0);
onGround = readBoolean(0);
switch (mode) {
case 0:
yaw = readByte(3);
pitch = readByte(4);
break;
case 1:
case 2:
yaw = readByte(0);
pitch = readByte(1);
break;
}
}
/**
* Get the pitch.
*
* @return Get Byte Pitch
*/
public byte getPitch() {
return pitch;
}
/**
* Get the Yaw.
*
* @return Get Byte Yaw
*/
public byte getYaw() {
return yaw;
}
/**
* Is the entity on the ground?
*
* @return On Ground
*/
public boolean isOnGround() {
return onGround;
}
/**
* Lookup the associated entity by the ID that was sent in the packet.
*
* @return Entity
*/
public Entity getEntity() {
if (entity != null) {
return entity;
}
return entity = NMSUtils.getEntityById(this.entityID);
}
/**
* Get the ID of the entity.
* If you do not want to use {@link #getEntity()},
* you lookup the entity by yourself with this entity ID.
*
* @return Entity ID
*/
public int getEntityId() {
return entityID;
}
}
}
@@ -26,20 +26,19 @@ package io.github.retrooper.packetevents.packetwrappers.out.entityvelocity;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.Sendable;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import org.bukkit.entity.Entity;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public final class WrappedPacketOutEntityVelocity extends WrappedPacket implements Sendable {
public final class WrappedPacketOutEntityVelocity extends WrappedPacket implements SendableWrapper {
private static Constructor<?> velocityConstructor, vec3dConstructor;
private static Class<?> velocityClass, vec3dClass;
private static boolean isVec3dPresent;
private int entityId;
private int entityID;
private double velocityX, velocityY, velocityZ;
private Entity entity;
public WrappedPacketOutEntityVelocity(final Object packet) {
@@ -47,14 +46,20 @@ public final class WrappedPacketOutEntityVelocity extends WrappedPacket implemen
}
public WrappedPacketOutEntityVelocity(final Entity entity, final double velocityX, final double velocityY, final double velocityZ) {
super();
this.entityId = entity.getEntityId();
this.entityID = entity.getEntityId();
this.entity = entity;
this.velocityX = velocityX;
this.velocityY = velocityY;
this.velocityZ = velocityZ;
}
public WrappedPacketOutEntityVelocity(int entityID, double velX, double velY, double velZ) {
this.entityID = entityID;
this.velocityX = velX;
this.velocityY = velY;
this.velocityZ = velZ;
}
/**
* Velocity Constructor parameter types:
* 1.7.10 -&gt; 1.13.2 use int, double, double, double style,
@@ -88,21 +93,17 @@ public final class WrappedPacketOutEntityVelocity extends WrappedPacket implemen
@Override
protected void setup() {
try {
//ENTITY ID
this.entityId = Reflection.getField(velocityClass, int.class, 0).getInt(packet);
//ENTITY ID
this.entityID = readInt(0);
int x = Reflection.getField(velocityClass, int.class, 1).getInt(packet);
int y = Reflection.getField(velocityClass, int.class, 2).getInt(packet);
int z = Reflection.getField(velocityClass, int.class, 3).getInt(packet);
int x = readInt(1);
int y = readInt(2);
int z = readInt(3);
//VELOCITY XYZ
this.velocityX = x / 8000.0D;
this.velocityY = y / 8000.0D;
this.velocityZ = z / 8000.0D;
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//VELOCITY XYZ
this.velocityX = x / 8000.0D;
this.velocityY = y / 8000.0D;
this.velocityZ = z / 8000.0D;
}
/**
@@ -110,7 +111,10 @@ public final class WrappedPacketOutEntityVelocity extends WrappedPacket implemen
* @return Entity
*/
public Entity getEntity() {
return NMSUtils.getEntityById(this.entityId);
if(entity != null) {
return entity;
}
return entity = NMSUtils.getEntityById(this.entityID);
}
/**
@@ -120,7 +124,7 @@ public final class WrappedPacketOutEntityVelocity extends WrappedPacket implemen
* @return Entity ID
*/
public int getEntityId() {
return entityId;
return entityID;
}
/**
@@ -151,13 +155,13 @@ public final class WrappedPacketOutEntityVelocity extends WrappedPacket implemen
public Object asNMSPacket() {
if (!isVec3dPresent) {
try {
return velocityConstructor.newInstance(entityId, velocityX, velocityY, velocityZ);
return velocityConstructor.newInstance(entityID, velocityX, velocityY, velocityZ);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
} else {
try {
return velocityConstructor.newInstance(entityId, vec3dConstructor.newInstance(velocityX, velocityY, velocityZ));
return velocityConstructor.newInstance(entityID, vec3dConstructor.newInstance(velocityX, velocityY, velocityZ));
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
@@ -0,0 +1,154 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.packetwrappers.out.gamestatechange;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class WrappedPacketOutGameStateChange extends WrappedPacket implements SendableWrapper {
private int reason;
private double value;
private static Constructor<?> packetConstructor, reasonClassConstructor;
private static Class<?> reasonClassType;
private static boolean reasonIntMode;
private static boolean valueFloatMode;
public static void load() {
reasonClassType = SubclassUtil.getSubClass(PacketTypeClasses.Server.GAME_STATE_CHANGE, "a");
if(reasonClassType != null) {
try {
reasonClassConstructor = reasonClassType.getConstructor(int.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
reasonIntMode = reasonClassType == null;
valueFloatMode = Reflection.getField(PacketTypeClasses.Server.GAME_STATE_CHANGE, double.class, 0) == null;
try {
Class<?> valueClassType;
if (valueFloatMode) {
valueClassType = float.class;
} else {
//Just an older version(1.7.10/1.8.x or so)
valueClassType = double.class;
}
if(reasonClassType == null) {
reasonClassType = int.class;
}
packetConstructor = PacketTypeClasses.Server.GAME_STATE_CHANGE.getConstructor(reasonClassType, valueClassType);
reasonClassType = null;
} catch (NullPointerException e) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "PacketEvents failed to find the constructor for the outbound Game state packet wrapper.");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public WrappedPacketOutGameStateChange(Object packet) {
super(packet);
}
public WrappedPacketOutGameStateChange(int reason, double value) {
this.reason = reason;
this.value = value;
}
public WrappedPacketOutGameStateChange(int reason, float value){
this(reason, (double)value);
}
@Override
protected void setup() {
if (reasonIntMode) {
reason = readInt(0);
} else {
//this packet is obfuscated quite strongly(1.16), so we must do this
Object reasonObject = readObject(12, reasonClassType);
try {
reason = Reflection.getField(reasonClassType, int.class, 0).getInt(reasonObject);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
if (valueFloatMode) {
value = readFloat(0);
} else {
value = readDouble(0);
}
}
public int getReason() {
return reason;
}
public double getValue() {
return reason;
}
@Override
public Object asNMSPacket() {
if (reasonClassType == null) {
try {
if (valueFloatMode) {
return packetConstructor.newInstance(reason, (float) value);
} else {
return packetConstructor.newInstance(reason, value);
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
} else {
Object reasonObject = null;
try {
reasonObject = reasonClassConstructor.newInstance(reason);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
try {
if (valueFloatMode) {
return packetConstructor.newInstance(reasonObject, (float) value);
} else {
return packetConstructor.newInstance(reasonObject, value);
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
return null;
}
}
@@ -25,14 +25,14 @@
package io.github.retrooper.packetevents.packetwrappers.out.keepalive;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.Sendable;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class WrappedPacketOutKeepAlive extends WrappedPacket implements Sendable {
public class WrappedPacketOutKeepAlive extends WrappedPacket implements SendableWrapper {
private static Class<?> packetClass;
private static Constructor<?> keepAliveConstructor;
private static boolean integerMode;
@@ -67,18 +67,11 @@ public class WrappedPacketOutKeepAlive extends WrappedPacket implements Sendable
@Override
protected void setup() {
if (!integerMode) {
try {
this.id = Reflection.getField(packetClass, long.class, 0).getLong(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
try {
this.id = Reflection.getField(packetClass, int.class, 0).getInt(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if(integerMode) {
this.id = readInt(0);
}
else {
this.id = readLong(0);
}
}
@@ -86,7 +79,7 @@ public class WrappedPacketOutKeepAlive extends WrappedPacket implements Sendable
* Get the Keep Alive ID.
*
* You may cast this down to an int if you are on 1.7.10 - 1.12.2.
* On 1.13.2 - 1.16.2 a long is sent.
* On 1.13.2 - 1.16.3 a long is sent.
*
* @return Get Keep Alive ID
*/
@@ -25,16 +25,15 @@
package io.github.retrooper.packetevents.packetwrappers.out.kickdisconnect;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.Sendable;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.out.chat.WrappedPacketOutChat;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public final class WrappedPacketOutKickDisconnect extends WrappedPacket implements Sendable {
public final class WrappedPacketOutKickDisconnect extends WrappedPacket implements SendableWrapper {
private static Class<?> packetClass, iChatBaseComponentClass;
private static Constructor<?> kickDisconnectConstructor;
private String kickMessage;
@@ -65,11 +64,8 @@ public final class WrappedPacketOutKickDisconnect extends WrappedPacket implemen
@Override
protected void setup() {
try {
this.kickMessage = WrappedPacketOutChat.toStringFromIChatBaseComponent(Reflection.getField(packetClass, iChatBaseComponentClass, 0).get(packet));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Object ichatbaseComponentoObject = readObject(0, iChatBaseComponentClass);
this.kickMessage = WrappedPacketOutChat.toStringFromIChatBaseComponent(ichatbaseComponentoObject);
}
/**
@@ -83,7 +79,7 @@ public final class WrappedPacketOutKickDisconnect extends WrappedPacket implemen
@Override
public Object asNMSPacket() {
try {
return kickDisconnectConstructor.newInstance(WrappedPacketOutChat.toIChatBaseComponent("{\"text\": \"" + kickMessage + "\"}"));
return kickDisconnectConstructor.newInstance(WrappedPacketOutChat.toIChatBaseComponent(WrappedPacketOutChat.fromStringToJSON(kickMessage)));
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
@@ -0,0 +1,116 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.packetwrappers.out.playerinfo;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import org.bukkit.GameMode;
import java.util.ArrayList;
import java.util.List;
class WrappedPacketOutPlayerInfo extends WrappedPacket implements SendableWrapper {
//TODO load this wrapper
private PlayerInfoAction action;
private List<PlayerInfoData> playerInfoDataList = new ArrayList<>();
private static byte mode = 0; //0 = 1.7.10
public static void load() {
}
public WrappedPacketOutPlayerInfo(Object packet) {
super(packet);
}
public WrappedPacketOutPlayerInfo(PlayerInfoAction action, Object gameProfile,
int ping, GameMode gameMode, String displayName) {
this.action = action;
playerInfoDataList.add(new PlayerInfoData(gameProfile, ping, gameMode, displayName));
}
@Override
protected void setup() {
switch (mode) {
case 0:
int actionInteger= readInt(0);
break;
case 1:
break;
case 2:
break;
}
}
@Override
public Object asNMSPacket() {
return null;
}
public PlayerInfoAction getAction() {
return action;
}
public List<PlayerInfoData> getPlayerInfoData() {
return playerInfoDataList;
}
public enum PlayerInfoAction {
ADD_PLAYER, UPDATE_GAME_MODE, UPDATE_LATENCY, UPDATE_DISPLAY_NAME, REMOVE_PLAYER;
}
public class PlayerInfoData {
private final int ping;
private final GameMode gameMode;
private final Object gameProfile;
private final String displayName;
public PlayerInfoData(Object gameProfile, int ping,
GameMode gameMode, String displayName) {
this.ping = ping;
this.gameMode = gameMode;
this.gameProfile = gameProfile;
this.displayName = displayName;
}
public int getPing() {
return ping;
}
public GameMode getGameMode() {
return gameMode;
}
public Object getGameProfile() {
return gameProfile;
}
public String getDisplayName() {
return displayName;
}
}
}
@@ -25,8 +25,7 @@
package io.github.retrooper.packetevents.packetwrappers.out.position;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
public final class WrappedPacketOutPosition extends WrappedPacket {
private static Class<?> packetClass;
@@ -47,16 +46,12 @@ public final class WrappedPacketOutPosition extends WrappedPacket {
@Override
protected void setup() {
//TODO boolean onGround and flags
try {
this.x = Reflection.getField(packetClass, double.class, 0).getDouble(packet);
this.y = Reflection.getField(packetClass, double.class, 1).getDouble(packet);
this.z = Reflection.getField(packetClass, double.class, 2).getDouble(packet);
this.x = readDouble(0);
this.y = readDouble(1);
this.z = readDouble(2);
this.yaw = Reflection.getField(packetClass, float.class, 0).getFloat(packet);
this.pitch = Reflection.getField(packetClass, float.class, 1).getFloat(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
this.yaw = readFloat(0);
this.pitch = readFloat(1);
}
/**
@@ -25,14 +25,13 @@
package io.github.retrooper.packetevents.packetwrappers.out.transaction;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.Sendable;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class WrappedPacketOutTransaction extends WrappedPacket implements Sendable {
public class WrappedPacketOutTransaction extends WrappedPacket implements SendableWrapper {
private static Class<?> packetClass;
private static Constructor<?> packetConstructor;
private int windowId;
@@ -61,13 +60,9 @@ public class WrappedPacketOutTransaction extends WrappedPacket implements Sendab
@Override
protected void setup() {
try {
this.windowId = Reflection.getField(packetClass, int.class, 0).getInt(packet);
this.actionNumber = Reflection.getField(packetClass, short.class, 0).getShort(packet);
this.accepted = Reflection.getField(packetClass, boolean.class, 0).getBoolean(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
this.windowId = readInt(0);
this.actionNumber = readShort(0);
this.accepted = readBoolean(0);
}
@@ -25,14 +25,14 @@
package io.github.retrooper.packetevents.packetwrappers.out.updatehealth;
import io.github.retrooper.packetevents.packet.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.Sendable;
import io.github.retrooper.packetevents.packetwrappers.api.WrappedPacket;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public final class WrappedPacketOutUpdateHealth extends WrappedPacket implements Sendable {
public final class WrappedPacketOutUpdateHealth extends WrappedPacket implements SendableWrapper {
private static Class<?> packetClass;
private static Constructor<?> packetConstructor;
private float health, foodSaturation;
@@ -68,8 +68,8 @@ public final class WrappedPacketOutUpdateHealth extends WrappedPacket implements
@Override
protected void setup() {
try {
this.health = Reflection.getField(packetClass, float.class, 0).getFloat(packet);
this.foodSaturation = Reflection.getField(packetClass, float.class, 0).getFloat(packet);
this.health = readFloat(0);
this.foodSaturation = readFloat(1);
this.food = Reflection.getField(packetClass, int.class, 0).getInt(packet);
} catch (IllegalAccessException e) {
e.printStackTrace();
@@ -1,213 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.reflectionutils;
import io.github.retrooper.packetevents.reflectionutils.fielddata.FieldWithIndex;
import io.github.retrooper.packetevents.reflectionutils.fielddata.FieldWithName;
import io.github.retrooper.packetevents.reflectionutils.fielddata.FieldWithTypeAndIndex;
import io.github.retrooper.packetevents.reflectionutils.methoddata.MethodWithIndexAndParams;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
/**
* @author retrooper
*/
public final class Reflection {
private static final HashMap<Class<?>, Field[]> cachedFields = new HashMap<Class<?>, Field[]>();
private static final HashMap<Class<?>, Method[]> cachedMethods = new HashMap<Class<?>, Method[]>();
private static final HashMap<Class<?>, Class<?>[]> cachedSubclasses = new HashMap<Class<?>, Class<?>[]>();
//FIELDS
private static final HashMap<FieldWithName, Field> fieldWithNameHashMap = new HashMap<FieldWithName, Field>();
private static final HashMap<FieldWithTypeAndIndex, Field> fieldWithTypeAndIndexHashMap = new HashMap<FieldWithTypeAndIndex, Field>();
private static final HashMap<FieldWithIndex, Field> fieldWithIndexHashMap = new HashMap<FieldWithIndex, Field>();
private static final HashMap<MethodWithIndexAndParams, Method> methodWithIndexAndParamsHashMap = new HashMap<MethodWithIndexAndParams, Method>();
public static Field[] getFields(final Class<?> cls) {
if (cachedFields.containsKey(cls)) {
return cachedFields.get(cls);
} else {
final Field[] fields = cls.getDeclaredFields();
for (final Field f : fields) {
f.setAccessible(true);
}
cachedFields.put(cls, fields);
return fields;
}
}
public static Field getField(final Class<?> cls, final String name) {
final FieldWithName fwn = new FieldWithName(cls, name);
if (!fieldWithNameHashMap.containsKey(fwn)) {
for (final Field f : getFields(cls)) {
if (f.getName().equals(name)) {
fieldWithNameHashMap.put(fwn, f);
return f;
}
}
} else {
return fieldWithNameHashMap.get(fwn);
}
return null;
}
public static Field getField(final Class<?> cls, final Class<?> dataType, final int index) {
final FieldWithTypeAndIndex fwtai = new FieldWithTypeAndIndex(cls, dataType, index);
if (!fieldWithTypeAndIndexHashMap.containsKey(fwtai)) {
int i = 0;
for (final Field f : getFields(cls)) {
if (f.getType().equals(dataType)) {
if (i++ == index) {
fieldWithTypeAndIndexHashMap.put(fwtai, f);
return f;
}
}
}
} else {
return fieldWithTypeAndIndexHashMap.get(fwtai);
}
return null;
}
public static Field getField(final Class<?> cls, final int index) {
final FieldWithIndex fwi = new FieldWithIndex(cls, index);
if (!fieldWithIndexHashMap.containsKey(fwi)) {
final Field[] fields = getFields(cls);
if (fields.length <= index) {
return null;
}
final Field field = fields[index];
fieldWithIndexHashMap.put(fwi, field);
return field;
} else {
return fieldWithIndexHashMap.get(fwi);
}
}
//METHODS
public static Method[] getMethods(final Class<?> cls) {
if (cachedMethods.containsKey(cls)) {
return cachedMethods.get(cls);
} else {
final Method[] methods = cls.getDeclaredMethods();
for (final Method m : methods) {
m.setAccessible(true);
}
cachedMethods.put(cls, methods);
return methods;
}
}
public static Method getMethod(final Class<?> cls, final int index, final Class<?>... params) {
final MethodWithIndexAndParams mwiap = new MethodWithIndexAndParams(cls, index, params);
if (!methodWithIndexAndParamsHashMap.containsKey(mwiap)) {
int i = 0;
for (final Method m : getMethods(cls)) {
if (Arrays.equals(m.getParameterTypes(), params) && index == i++) {
return m;
}
}
} else {
return methodWithIndexAndParamsHashMap.get(mwiap);
}
return null;
}
//THE REST LATER
public static Method getMethod(final Class<?> cls, final String name, Class<?> returning, Class<?>... params) {
for (final Method m : getMethods(cls)) {
if (m.getName().equals(name) && Arrays.equals(m.getParameterTypes(), params) && m.getReturnType().equals(returning)) {
return m;
}
}
return null;
}
public static Method getMethod(final Class<?> cls, final String name, final int index) {
int i = 0;
for (final Method m : getMethods(cls)) {
if (m.getName().equals(name) && index == i++) {
return m;
}
}
return null;
}
public static Method getMethod(final Class<?> cls, final Class<?> returning, final int index) {
int i = 0;
for (final Method m : getMethods(cls)) {
if (m.getReturnType().equals(returning) && index == i++) {
return m;
}
}
return null;
}
public static Method getMethod(final Class<?> cls, final String name, final Class<?> returning) {
int i = 0;
for (final Method m : getMethods(cls)) {
if (m.getName().equals(name) && m.getReturnType().equals(returning)) {
return m;
}
}
return null;
}
public static Class<?>[] getSubClasses(final Class<?> cls) {
if (cachedSubclasses.containsKey(cls)) {
return cachedSubclasses.get(cls);
} else {
final Class<?>[] subclasses = cls.getDeclaredClasses();
cachedSubclasses.put(cls, subclasses);
return subclasses;
}
}
public static Class<?> getSubClass(final Class<?> cls, final String name) {
for (final Class<?> subclass : getSubClasses(cls)) {
if (subclass.getSimpleName().equals(name)) {
return subclass;
}
}
return null;
}
public static Class<?> getSubClass(final Class<?> cls, final int index) {
final Class<?>[] subclasses = getSubClasses(cls);
for (int i = 0; i < index + 1; i++) {
final Class<?> c = subclasses[i];
if (i == index) {
return c;
}
}
return null;
}
}
@@ -25,33 +25,46 @@
package io.github.retrooper.packetevents.settings;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.packettype.PacketType;
import java.util.Random;
public class PacketEventsSettings {
private ServerVersion defaultServerVersion = ServerVersion.v_1_7_10;
private ServerVersion backupServerVersion = ServerVersion.v_1_7_10;
private String identifier = "";
private boolean autoResolveClientProtocolVersion;
private boolean uninjectAsync = false;
private boolean injectAsync = false;
private boolean autoResolveClientProtocolVersion = false;
private boolean uninjectAsync = true;
private boolean injectAsync = true;
private boolean useProtocolLibIfAvailable = true;
private boolean checkForUpdates = true;
/**
* If PacketEvents fails to detect your server version, it will use the recommended version
*
* @deprecated Use {@link #getBackupServerVersion()}
* @return Recommended version
*/
@Deprecated
public ServerVersion getDefaultServerVersion() {
return this.defaultServerVersion;
return this.backupServerVersion;
}
/**
* Set the default version
*
* @deprecated Use {@link #setBackupServerVersion(ServerVersion)}
* @param version ServerVersion
*/
@Deprecated
public void setDefaultServerVersion(final ServerVersion version) {
this.defaultServerVersion = version;
this.backupServerVersion = version;
}
public void setBackupServerVersion(ServerVersion version) {
this.backupServerVersion = version;
}
public ServerVersion getBackupServerVersion() {
return backupServerVersion;
}
/**
@@ -60,6 +73,7 @@ public class PacketEventsSettings {
* If you manually set the identifier using its setter '#setIdentifier(String)'.
* We will use that identifier to generate each player's handler name.
* If you do not set the identifier manually, we automatically generate one for you.
*
* @return stored identifier or new generated identifier
*/
public String getIdentifier() {
@@ -81,29 +95,48 @@ public class PacketEventsSettings {
* Set a unique Identifier (Usually something that represents your plugin, For example: MyPluginPacketHandler)
* If another present plugin uses the same Identifier, It will cause incompatibilities.
*
* This function is now unneeded as PacketEvents generates a random identifier for you already.
* @param identifier Unique string
* @deprecated This method is deprecated as you no longer need to set an identifier,
* a unique identifier is already automatically generated for you.
*/
@Deprecated
public void setIdentifier(final String identifier) {
this.identifier = identifier;
}
public boolean shouldAutoResolveClientProtocolVersion() {
return autoResolveClientProtocolVersion;
}
/**
* @deprecated Use {@link #shouldAutoResolveClientProtocolVersion()}
* @return
*/
@Deprecated
public boolean doAutoResolveClientProtocolVersion() {
return autoResolveClientProtocolVersion;
}
/**
* @deprecated Use {@link #setShouldAutoResolveClientProtocolVersion(boolean)}
* @param autoResolveClientProtocolVersion
*/
@Deprecated
public void setDoAutoResolveClientProtocolVersion(boolean autoResolveClientProtocolVersion) {
this.autoResolveClientProtocolVersion = autoResolveClientProtocolVersion;
}
/**
* If PacketEvents fails to detect a client's version
* (when ViaVersion, ProtocolLib or ProtocolSupport can't be found on the server),
* should it assume that the client is using the same version as the server?
* Returns ACCESS_FAILURE if this is set to FALSE(default value is false).
* @param autoResolveClientProtocolVersion boolean
*
* @param val boolean
*/
public void setDoAutoResolveClientProtocolVersion(boolean autoResolveClientProtocolVersion) {
this.autoResolveClientProtocolVersion = autoResolveClientProtocolVersion;
public void setShouldAutoResolveClientProtocolVersion(boolean val) {
this.autoResolveClientProtocolVersion = val;
}
/**
* Would you like PacketEvents to Uninject players Asynchronously?
@@ -132,4 +165,35 @@ public class PacketEventsSettings {
public void setInjectAsync(boolean injectAsync) {
this.injectAsync = injectAsync;
}
public boolean isUseProtocolLibIfAvailable() {
return this.useProtocolLibIfAvailable;
}
/**
* Would you like PacketEvents to make use of ProtocolLib if it is available?
* If yes, enable this, if not disable this.
* Having this on can help your plugin have compatibility
* with other plugins that might be using ProtocolLib.
* Especially if they or you are doing packet cancellations,
* PacketEvents passes the event priority to ProtocolLib.
*
* @param val boolean
*/
public void setUseProtocolLibIfAvailable(boolean val) {
this.useProtocolLibIfAvailable = val;
}
public boolean shouldCheckForUpdates() {
return checkForUpdates;
}
/**
* Would you like PacketEvents to Check for Updates on startup?
*
* @param checkForUpdates boolean
*/
public void setShouldCheckForUpdates(boolean checkForUpdates) {
this.checkForUpdates = checkForUpdates;
}
}
@@ -22,39 +22,25 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.reflectionutils.fielddata;
package io.github.retrooper.packetevents.utils.bytebuf;
import java.util.Objects;
import io.github.retrooper.packetevents.nettyhandler.NettyPacketHandler;
public class FieldWithIndex {
private final Class<?> cls;
private final int index;
public FieldWithIndex(Class<?> cls, int index) {
this.cls = cls;
this.index = index;
public class ByteBufUtil {
public static Object copiedBuffer(byte[] bytes) {
if (NettyPacketHandler.v1_7_nettyMode) {
return ByteBufUtil_7.copiedBuffer(bytes);
} else {
return ByteBufUtil_8.copiedBuffer(bytes);
}
}
public Class<?> getCls() {
return cls;
public static byte[] getBytes(Object byteBuf) {
if(NettyPacketHandler.v1_7_nettyMode) {
return ByteBufUtil_7.getBytes(byteBuf);
}
else {
return ByteBufUtil_8.getBytes(byteBuf);
}
}
public int getIndex() {
return index;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FieldWithIndex that = (FieldWithIndex) o;
return index == that.index &&
Objects.equals(cls, that.cls);
}
@Override
public int hashCode() {
return Objects.hash(cls, index);
}
}
@@ -22,40 +22,25 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.reflectionutils.fielddata;
package io.github.retrooper.packetevents.utils.bytebuf;
import java.util.Objects;
import net.minecraft.util.io.netty.buffer.ByteBuf;
import net.minecraft.util.io.netty.buffer.Unpooled;
public class FieldWithName {
private final Class<?> cls;
private final String name;
public FieldWithName(Class<?> cls, String name) {
this.cls = cls;
this.name = name;
class ByteBufUtil_7 {
public static Object copiedBuffer(byte[] bytes) {
return Unpooled.copiedBuffer(bytes);
}
public Class<?> getCls() {
return cls;
public static byte[] getBytes(Object byteBuf) {
ByteBuf bb = (ByteBuf)byteBuf;
byte[] bytes;
if (bb.hasArray()) {
bytes = bb.array();
} else {
bytes = new byte[bb.readableBytes()];
bb.getBytes(bb.readerIndex(), bytes);
}
return bytes;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FieldWithName that = (FieldWithName) o;
return name.equals(that.name) &&
Objects.equals(cls, that.cls);
}
@Override
public int hashCode() {
return Objects.hash(cls, name);
}
}
@@ -22,45 +22,25 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.reflectionutils.fielddata;
package io.github.retrooper.packetevents.utils.bytebuf;
import java.util.Objects;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
public class FieldWithTypeAndIndex {
private final Class<?> cls, type;
private final int index;
public FieldWithTypeAndIndex(Class<?> cls, Class<?> type, int index) {
this.cls = cls;
this.type = type;
this.index = index;
class ByteBufUtil_8 {
public static Object copiedBuffer(byte[] bytes) {
return Unpooled.copiedBuffer(bytes);
}
public Class<?> getCls() {
return cls;
public static byte[] getBytes(Object byteBuf) {
ByteBuf bb = (ByteBuf)byteBuf;
byte[] bytes;
if (bb.hasArray()) {
bytes = bb.array();
} else {
bytes = new byte[bb.readableBytes()];
bb.getBytes(bb.readerIndex(), bytes);
}
return bytes;
}
public Class<?> getType() {
return type;
}
public int getIndex() {
return index;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FieldWithTypeAndIndex that = (FieldWithTypeAndIndex) o;
return index == that.index &&
Objects.equals(cls, that.cls) &&
Objects.equals(type, that.type);
}
@Override
public int hashCode() {
return Objects.hash(cls, type, index);
}
}
@@ -22,11 +22,11 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.utils.nms_entityfinder;
package io.github.retrooper.packetevents.utils.entityfinder;
import io.github.retrooper.packetevents.annotations.Nullable;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Entity;
@@ -0,0 +1,40 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.utils.gameprofile;
import io.github.retrooper.packetevents.nettyhandler.NettyPacketHandler;
import java.util.UUID;
public class GameProfileUtil {
public static Object getGameProfile(UUID uuid, String username) {
if(NettyPacketHandler.v1_7_nettyMode) {
return GameProfileUtil_7.getGameProfile(uuid, username);
}
else {
return GameProfileUtil_8.getGameProfile(uuid, username);
}
}
}
@@ -0,0 +1,35 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.utils.gameprofile;
import net.minecraft.util.com.mojang.authlib.GameProfile;
import java.util.UUID;
class GameProfileUtil_7 {
public static Object getGameProfile(UUID uuid, String username) {
return new GameProfile(uuid, username);
}
}
@@ -0,0 +1,35 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.utils.gameprofile;
import com.mojang.authlib.GameProfile;
import java.util.UUID;
class GameProfileUtil_8 {
public static Object getGameProfile(UUID uuid, String username) {
return new GameProfile(uuid, username);
}
}
@@ -22,13 +22,16 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.utils;
package io.github.retrooper.packetevents.utils.nms;
import io.github.retrooper.packetevents.annotations.Nullable;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.packetwrappers.Sendable;
import io.github.retrooper.packetevents.reflectionutils.Reflection;
import io.github.retrooper.packetevents.utils.nms_entityfinder.EntityFinderUtils;
import io.github.retrooper.packetevents.nettyhandler.NettyPacketHandler;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.entityfinder.EntityFinderUtils;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
@@ -37,22 +40,25 @@ import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.UUID;
public final class NMSUtils {
public static ServerVersion version;
private static final String nmsDir = ServerVersion.getNMSDirectory();
private static final String obcDir = ServerVersion.getOBCDirectory();
public static String nettyPrefix;
public static Class<?> minecraftServerClass, craftWorldsClass,
packetClass, entityPlayerClass, playerConnectionClass,
public static String nettyPrefix = "io.netty";
public static Class<?> minecraftServerClass, craftWorldClass, playerInteractManagerClass,
packetClass, entityPlayerClass, playerConnectionClass, craftServerClass,
craftPlayerClass, serverConnectionClass, craftEntityClass,
craftItemStack, nmsItemStackClass, networkManagerClass, nettyChannelClass;
private static Method getCraftWorldHandleMethod, getServerConnection, getCraftPlayerHandle, getCraftEntityHandle, sendPacketMethod, asBukkitCopy;
private static Method craftWorldGetHandle,getCraftWorldHandleMethod, getServerConnection, getCraftPlayerHandle, getCraftEntityHandle, sendPacketMethod, asBukkitCopy;
private static Field entityPlayerPingField, playerConnectionField;
public static final HashMap<UUID, Object> channelCache = new HashMap<>();
public static void load() {
try {
nettyPrefix = "io.netty";
Class.forName(nettyPrefix + ".channel.Channel");
} catch (ClassNotFoundException e) {
nettyPrefix = "net.minecraft.util.io.netty";
@@ -65,8 +71,9 @@ public final class NMSUtils {
try {
nettyChannelClass = getNettyClass("channel.Channel");
minecraftServerClass = getNMSClass("MinecraftServer");
craftWorldsClass = getOBCClass("CraftWorld");
craftWorldClass = getOBCClass("CraftWorld");
craftPlayerClass = getOBCClass("entity.CraftPlayer");
craftServerClass = getOBCClass("CraftServer");
entityPlayerClass = getNMSClass("EntityPlayer");
packetClass = getNMSClass("Packet");
playerConnectionClass = getNMSClass("PlayerConnection");
@@ -75,18 +82,20 @@ public final class NMSUtils {
craftItemStack = getOBCClass("inventory.CraftItemStack");
nmsItemStackClass = getNMSClass("ItemStack");
networkManagerClass = getNMSClass("NetworkManager");
playerInteractManagerClass = getNMSClass("PlayerInteractManager");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//METHODS
try {
getCraftWorldHandleMethod = craftWorldsClass.getMethod("getHandle");
getCraftWorldHandleMethod = craftWorldClass.getMethod("getHandle");
getCraftPlayerHandle = craftPlayerClass.getMethod("getHandle");
getCraftEntityHandle = craftEntityClass.getMethod("getHandle");
sendPacketMethod = playerConnectionClass.getMethod("sendPacket", packetClass);
getServerConnection = minecraftServerClass.getMethod("getServerConnection");
asBukkitCopy = craftItemStack.getMethod("asBukkitCopy", nmsItemStackClass);
craftWorldGetHandle = craftWorldClass.getMethod("getHandle");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
@@ -192,6 +201,14 @@ public final class NMSUtils {
}
public static Object getChannel(final Player player) {
UUID uuid = player.getUniqueId();
if (!channelCache.containsKey(uuid)) {
channelCache.put(uuid, getChannelNoCache(player));
}
return channelCache.get(uuid);
}
public static Object getChannelNoCache(final Player player) {
try {
return Reflection.getField(networkManagerClass, nettyChannelClass, 0).get(getNetworkManager(player));
} catch (IllegalAccessException e) {
@@ -219,23 +236,55 @@ public final class NMSUtils {
return null;
}
public static void sendSendableWrapper(final Player player, final Sendable sendable) {
NMSUtils.sendNMSPacket(player, sendable.asNMSPacket());
public static Object convertBukkitServerToNMSServer(Server server) {
Object craftServer = craftServerClass.cast(server);
WrappedPacket wrapper = new WrappedPacket(craftServer);
return wrapper.readObject(0, minecraftServerClass);
}
public static Object convertBukkitWorldToNMSWorld(World world) {
Object craftWorld = craftWorldClass.cast(world);
public static void sendNMSPacket(final Player player, final Object nmsPacket) {
Object entityPlayer = getEntityPlayer(player);
Object playerConnection = null;
Object worldServer = null;
try {
playerConnection = playerConnectionField.get(entityPlayer);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
try {
sendPacketMethod.invoke(playerConnection, nmsPacket);
worldServer = craftWorldGetHandle.invoke(craftWorld);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return worldServer;
}
public static Object createNewEntityPlayer(Server server, World world, Object gameProfile) {
Object nmsServer = convertBukkitServerToNMSServer(server);
Object nmsWorld = convertBukkitWorldToNMSWorld(world);
return privateCreateNewEntityPlayer(nmsServer, nmsWorld, gameProfile);
}
private static Object privateCreateNewEntityPlayer(Object nmsServer, Object nmsWorld, Object gameProfile) {
Object playerInteractManager = null;
try {
playerInteractManager = playerInteractManagerClass.getConstructor(nmsWorld.getClass()).newInstance(nmsWorld);
} catch (InstantiationException | IllegalAccessException
| InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
try {
return entityPlayerClass.getConstructor(nmsServer.getClass(), nmsWorld.getClass(),
gameProfile.getClass(), playerConnectionClass).
newInstance(nmsServer, nmsWorld, gameProfile, playerInteractManager);
} catch (InstantiationException | IllegalAccessException
| InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
public static void sendSendableWrapper(final Player player, final SendableWrapper sendableWrapper) {
NMSUtils.sendNMSPacket(player, sendableWrapper.asNMSPacket());
}
public static void sendNMSPacket(final Player player, final Object nmsPacket) {
NettyPacketHandler.sendPacket(getChannel(player), nmsPacket);
}
}
@@ -22,13 +22,13 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.utils.api;
package io.github.retrooper.packetevents.utils.player;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.enums.ClientVersion;
import io.github.retrooper.packetevents.handler.NettyPacketHandler;
import io.github.retrooper.packetevents.packetwrappers.Sendable;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.nettyhandler.NettyPacketHandler;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.versionlookup.VersionLookupUtils;
import org.bukkit.entity.Player;
@@ -119,12 +119,12 @@ public final class PlayerUtils {
}
/**
* Send a {@link Sendable} wrapper to a player.
* Send a {@link SendableWrapper} wrapper to a player.
* @param player
* @param sendable
* @param sendableWrapper
*/
public void sendPacket(final Player player, final Sendable sendable) {
NMSUtils.sendSendableWrapper(player, sendable);
public void sendPacket(final Player player, final SendableWrapper sendableWrapper) {
NMSUtils.sendSendableWrapper(player, sendableWrapper);
}
/**
@@ -31,7 +31,7 @@ import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.annotations.PacketHandler;
import io.github.retrooper.packetevents.enums.PacketEventPriority;
import io.github.retrooper.packetevents.event.priority.PacketEventPriority;
import io.github.retrooper.packetevents.event.PacketListener;
import io.github.retrooper.packetevents.event.impl.PacketReceiveEvent;
import io.github.retrooper.packetevents.event.impl.PacketSendEvent;
@@ -39,32 +39,17 @@ import io.github.retrooper.packetevents.event.impl.PacketSendEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ProtocolLibListener {
public enum ProtocolLibPresent {
UNKNOWN, NOT_PRESENT, PRESENT
}
private static ProtocolLibPresent plibPresent = ProtocolLibPresent.UNKNOWN;
public static void load() {
public static void registerProtocolLibListener(PacketListener listener, ConcurrentLinkedQueue<Method> methods) {
if (ProtocolLibUtils.isAvailable()) {
plibPresent = ProtocolLibPresent.PRESENT;
}
}
public static ProtocolLibPresent isProtocolLibPresent() {
return plibPresent;
}
public static void registerProtocolLibListener(PacketListener listener, List<Method> methods) {
if (plibPresent == ProtocolLibPresent.PRESENT) {
for (Method m : methods) {
if (m.getParameterTypes()[0].equals(PacketReceiveEvent.class)) {
PacketHandler annot = m.getAnnotation(PacketHandler.class);
PacketHandler annotation = m.getAnnotation(PacketHandler.class);
ListenerPriority priority;
switch (annot.priority()) {
switch (annotation.priority()) {
case PacketEventPriority.LOWEST:
priority = ListenerPriority.LOWEST;
break;
@@ -76,7 +61,7 @@ public class ProtocolLibListener {
break;
case PacketEventPriority.HIGHEST:
priority = ListenerPriority.HIGHEST;
break;
break;
case PacketEventPriority.MONITOR:
priority = ListenerPriority.MONITOR;
break;
@@ -100,9 +85,9 @@ public class ProtocolLibListener {
}
});
} else if (m.getParameterTypes()[0].equals(PacketSendEvent.class)) {
PacketHandler annot = m.getAnnotation(PacketHandler.class);
PacketHandler annotation = m.getAnnotation(PacketHandler.class);
ListenerPriority priority;
switch (annot.priority()) {
switch (annotation.priority()) {
case PacketEventPriority.LOWEST:
priority = ListenerPriority.LOWEST;
break;
@@ -0,0 +1,38 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.utils.reflection;
import java.util.HashMap;
public class ClassUtil {
private static final HashMap<Class<?>, String> classSimpleNameCache = new HashMap<Class<?>, String>();
public static String getClassSimpleName(Class<?> cls) {
if(!classSimpleNameCache.containsKey(cls)) {
classSimpleNameCache.put(cls, cls.getSimpleName());
}
return classSimpleNameCache.get(cls);
}
}
@@ -0,0 +1,134 @@
/*
* MIT License
*
* Copyright (c) 2020 retrooper
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.retrooper.packetevents.utils.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
public final class Reflection {
//FIELDS
public static Field[] getFields(Class<?> cls) {
Field[] declaredFields = cls.getDeclaredFields();
for (Field f : declaredFields) {
f.setAccessible(true);
}
return declaredFields;
}
public static Field getField(final Class<?> cls, final String name) {
for (final Field f : getFields(cls)) {
if (f.getName().equals(name)) {
return f;
}
}
return null;
}
public static Field getField(final Class<?> cls, final Class<?> dataType, final int index) {
int currentIndex = 0;
for (final Field f : getFields(cls)) {
if (f.getType().equals(dataType)) {
if (currentIndex++ == index) {
return f;
}
}
}
return null;
}
public static Field getField(final Class<?> cls, final int index) {
return getFields(cls)[index];
}
//METHODS
public static Method[] getMethods(final Class<?> cls) {
Method[] declaredMethods = cls.getDeclaredMethods();
for (Method m : declaredMethods) {
m.setAccessible(true);
}
return declaredMethods;
}
public static Method getMethod(final Class<?> cls, final int index, final Class<?>... params) {
int currentIndex = 0;
for (final Method m : getMethods(cls)) {
if (Arrays.equals(m.getParameterTypes(), params) && index == currentIndex++) {
return m;
}
}
return null;
}
public static Method getMethod(Class<?> cls, Class<?> returning, int index, Class<?>... params) {
int currentIndex = 0;
for(Method m : getMethods(cls)) {
if(Arrays.equals(m.getParameterTypes(), params) && m.getReturnType().equals(returning) && index == currentIndex++) {
return m;
}
}
return null;
}
public static Method getMethod(final Class<?> cls, final String name, Class<?> returning, Class<?>... params) {
for (final Method m : getMethods(cls)) {
if (m.getName().equals(name) && Arrays.equals(m.getParameterTypes(), params) && m.getReturnType().equals(returning)) {
return m;
}
}
return null;
}
public static Method getMethod(final Class<?> cls, final String name, final int index) {
int currentIndex = 0;
for (final Method m : getMethods(cls)) {
if (m.getName().equals(name) && index == currentIndex++) {
return m;
}
}
return null;
}
public static Method getMethod(final Class<?> cls, final Class<?> returning, final int index) {
int currentIndex = 0;
for (final Method m : getMethods(cls)) {
if (returning.equals(m.getReturnType()) && index == currentIndex++) {
return m;
}
}
return null;
}
public static Method getMethod(final Class<?> cls, final String name, final Class<?> returning) {
for (final Method m : getMethods(cls)) {
if (m.getName().equals(name) && m.getReturnType().equals(returning)) {
return m;
}
}
return null;
}
}
@@ -22,46 +22,39 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.reflectionutils.methoddata;
package io.github.retrooper.packetevents.utils.reflection;
import java.util.Objects;
import java.lang.annotation.Annotation;
public class MethodWithIndexAndParams {
private final Class<?> cls;
private final int index;
private final Class<?>[] params;
public MethodWithIndexAndParams(Class<?> cls, int index, Class<?>[] params) {
this.cls = cls;
this.index = index;
this.params = params;
public class SubclassUtil {
public static Class<?> getSubClass(Class<?> cls, String name) {
for (Class<?> subClass : cls.getDeclaredClasses()) {
if (ClassUtil.getClassSimpleName(subClass).equals(name)) {
return subClass;
}
}
return null;
}
public Class<?> getCls() {
return cls;
public static Class<?> getSubClass(Class<?> cls, int index) {
int currentIndex = 0;
for (Class<?> subClass : cls.getDeclaredClasses()) {
if (index == currentIndex++) {
return subClass;
}
}
return null;
}
public int getIndex() {
return index;
public static Class<?> getSubClass(Class<?> cls, Annotation annotation, int index) {
int currentIndex = 0;
for(Class<?> subClass : cls.getDeclaredClasses()) {
if(subClass.getAnnotation(annotation.getClass()) != null) {
if(index == currentIndex++) {
return subClass;
}
}
}
return null;
}
public Class<?>[] getParams() {
return params;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MethodWithIndexAndParams that = (MethodWithIndexAndParams) o;
return index == that.index &&
Objects.equals(cls, that.cls) &&
Objects.equals(params, that.params);
}
@Override
public int hashCode() {
return Objects.hash(cls, params, index);
}
}
@@ -22,11 +22,11 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.utils.api;
package io.github.retrooper.packetevents.utils.server;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.enums.SystemOS;
import io.github.retrooper.packetevents.utils.NMSUtils;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import java.lang.reflect.InvocationTargetException;
@@ -74,7 +74,7 @@ public final class ServerUtils {
/**
* Use {@link #getOperatingSystem()}
* @deprecated Method rename pending to next minor update.
* @return
* @return Operating system of the current machine
*/
@Deprecated
public SystemOS getPlatform() {
@@ -82,10 +82,18 @@ public final class ServerUtils {
}
/**
* Get the Operating System the server is running on.
* @return Get Server Operating System
* @deprecated Use {@link #getOS()}
*/
@Deprecated
public SystemOS getOperatingSystem() {
return SystemOS.getOperatingSystem();
}
/**
* Get the operating system of the local machine
* @return Get Operating System
*/
public SystemOS getOS() {
return SystemOS.getOperatingSystem();
}
}
@@ -22,7 +22,7 @@
* SOFTWARE.
*/
package io.github.retrooper.packetevents.utils.versionlookup;
package io.github.retrooper.packetevents.utils.v_1_7_10;
import org.bukkit.entity.Player;
@@ -24,6 +24,7 @@
package io.github.retrooper.packetevents.utils.vector;
@Deprecated
public final class Vector3d {
public double x, y, z;
@@ -24,6 +24,7 @@
package io.github.retrooper.packetevents.utils.vector;
@Deprecated
public final class Vector3f {
public float x, y, z;
@@ -23,7 +23,7 @@
*/
package io.github.retrooper.packetevents.utils.vector;
@Deprecated
public final class Vector3i {
public int x, y, z;
@@ -28,6 +28,7 @@ import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.enums.ServerVersion;
import io.github.retrooper.packetevents.utils.protocollib.ProtocolLibUtils;
import io.github.retrooper.packetevents.utils.protocolsupport.ProtocolSupportUtils;
import io.github.retrooper.packetevents.utils.v_1_7_10.ProtocolVersionAccessor_v_1_7;
import io.github.retrooper.packetevents.utils.viaversion.ViaUtils;
import org.bukkit.entity.Player;