Compare commits

...
1 Commits
49 changed files with 925 additions and 964 deletions

No files matched your search

@@ -1,5 +1,6 @@
package io.github.retrooper.packetevents;
import io.github.retrooper.packetevents.annotations.NotNull;
import io.github.retrooper.packetevents.annotations.Nullable;
import io.github.retrooper.packetevents.annotations.PacketHandler;
import io.github.retrooper.packetevents.enums.ClientVersion;
@@ -26,23 +27,14 @@ import java.util.HashMap;
public final class PacketEvents implements PacketListener, Listener {
/*
* Wrappers TODO:
* Spawn entity
*/
private static boolean hasRegistered;
private static final ServerVersion version = ServerVersion.getVersion();
private static PacketEvents instance;
private static final EventManager eventManager = new EventManager();
private static int currentTick;
private static BukkitTask serverTickTask;
private static final HashMap<Object, ClientVersion> clientVersionLookup = new HashMap<Object, ClientVersion>();
private static boolean hasRegistered;
private static PacketEvents instance;
private static int currentTick;
private static BukkitTask serverTickTask;
private static boolean kickOnRestart;
public static EventManager getEventManager() {
return eventManager;
@@ -67,7 +59,7 @@ public final class PacketEvents implements PacketListener, Listener {
final Runnable tickRunnable = new Runnable() {
@Override
public void run() {
getEventManager().callEvent(new ServerTickEvent(currentTick++, PacketEvents.currentCalculatedMS()));
getEventManager().callEvent(new ServerTickEvent(currentTick++, highlyPreciseMillis()));
}
};
serverTickTask = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, tickRunnable, 0L, 1L);
@@ -76,13 +68,22 @@ public final class PacketEvents implements PacketListener, Listener {
}
/**
* Stop all tasks and unregisters all packetevent listeners
* Stop all tasks and unregisters all PacketEvents' listeners
*/
public static void stop() {
if (serverTickTask != null) {
serverTickTask.cancel();
if (!serverTickTask.isCancelled()) {
serverTickTask.cancel();
}
}
getEventManager().unregisterAllListeners();
if (shouldKickOnStop()) {
for (final Player p : Bukkit.getOnlinePlayers()) {
if (p != null) {
p.kickPlayer("Please wait till the server finishes reloading/restarting.");
}
}
}
}
/**
@@ -151,23 +152,30 @@ public final class PacketEvents implements PacketListener, Listener {
* @param player
* @return ping
*/
public static int getPing(final Player player) {
public static int getPing(@NotNull final Player player) {
return NMSUtils.getPlayerPing(player);
}
/**
* Should I use this over System.currentTimeMillis()?
* <p>
* 1. System.currentTimeMillis() isn't supported on all machines
* 2. This is way more accurate than System.currentTimeMillis()
* 3. System.currentTimeMillis() can be up to 50ms off, depending on the operating system.
*
* When to use this(nano / 1 million) over {@link System#currentTimeMillis()}
* This is preciser than System.currentTimeMillis(), System.currentTimeMillis() can be up to 50ms off on some operating systems, but using this isn't cheap.
* Java documentation recommend using nano time if you are measuring elapsed time.
* In this function nanoTime is divided by 1 million giving us milliseconds.
* It is also important to mention that using this method doesn't guarantee thread safety.
* @return nanoTime / 1 million
*/
public static long highlyPreciseMillis() {
return System.nanoTime() / 1000000;
}
/**
* This is deprecated, use {@link #highlyPreciseMillis()} as they do the same thing, this is basically just a method rename.
*/
public static long currentCalculatedMS() {
return System.nanoTime() / 1000000;
}
/**
* Get the player's version.
* Do not call this method in the PlayerInjectEvent, it is safe to call it in the PostPlayerInjectEvent.
@@ -177,7 +185,7 @@ public final class PacketEvents implements PacketListener, Listener {
* @return ClientVersion
*/
@Nullable
public static ClientVersion getClientVersion(final Player player) {
public static ClientVersion getClientVersion(@NotNull final Player player) {
final Object channel = TinyProtocolHandler.getPlayerChannel(player);
return clientVersionLookup.get(channel);
}
@@ -191,58 +199,21 @@ public final class PacketEvents implements PacketListener, Listener {
* @return ClientVersion
*/
@Nullable
public static ClientVersion getClientVersion(final Object channel) {
public static ClientVersion getClientVersion(@NotNull final Object channel) {
return clientVersionLookup.get(channel);
}
@PacketHandler
public void onLogin(final PacketLoginEvent e) {
if (e.getPacketName().equals(Packet.Login.HANDSHAKE)) {
final WrappedPacketLoginHandshake handshake = new WrappedPacketLoginHandshake(e.getPacket());
final ClientVersion clientVersion = ClientVersion.fromProtocolVersion(handshake.getProtocolVersion());
clientVersionLookup.put(e.getNettyChannel(), clientVersion);
}
public static boolean shouldKickOnStop() {
return kickOnRestart;
}
@PacketHandler
public void onPacket(final PacketEvent e) {
if(e instanceof PacketReceiveEvent) {
// System.out.println("RECEIVED");
}
}
/**
* Do not check the client version in or before the PlayerInjectEvent, use the PostPlayerInjectEvent.
* It is not recommended to do much in the PlayerInjectEvent, as some fields in the Player object are be null.
* Use the PostPlayerInjectEvent which is only called after the PlayerJoinEvent if the player was injected.
*
* @param e
*/
@PacketHandler
public void onInject(final PlayerInjectEvent e) {
final String username = e.getPlayer().getName();
}
/**
* Called after the PlayerJoinEvent ONLY if the player has been injected!
*
* @param e
*/
@PacketHandler
public void onPostInject(final PostPlayerInjectEvent e) {
//It is safe to get his client version in here.
final ClientVersion clientVersion = PacketEvents.getClientVersion(e.getPlayer());
}
@EventHandler
public void onJoin(PlayerJoinEvent e) {
if (hasInjected(e.getPlayer())) {
PacketEvents.getEventManager().callEvent(new PostPlayerInjectEvent(e.getPlayer()));
}
public static void setShouldKickOnRestart(final boolean val) {
kickOnRestart = val;
}
/**
* Version independent player injection
*
* @param player
*/
public static void injectPlayer(final Player player) {
@@ -277,4 +248,50 @@ public final class PacketEvents implements PacketListener, Listener {
public static void sendPacket(final Player player, final Sendable sendable) {
NMSUtils.sendSendableWrapper(player, sendable);
}
@PacketHandler
public void onLogin(final PacketLoginEvent e) {
if (e.getPacketName().equals(Packet.Login.HANDSHAKE)) {
final WrappedPacketLoginHandshake handshake = new WrappedPacketLoginHandshake(e.getPacket());
final ClientVersion clientVersion = ClientVersion.fromProtocolVersion(handshake.getProtocolVersion());
clientVersionLookup.put(e.getNettyChannel(), clientVersion);
}
}
@PacketHandler
public void onPacket(final PacketEvent e) {
if (e instanceof PacketReceiveEvent) {
// System.out.println("RECEIVED");
}
}
/**
* Do not check the client version in or before the PlayerInjectEvent, use the PostPlayerInjectEvent.
* It is not recommended to do much in the PlayerInjectEvent, as some fields in the Player object are be null.
* Use the PostPlayerInjectEvent which is only called after the PlayerJoinEvent if the player was injected.
*
* @param e
*/
@PacketHandler
public void onInject(final PlayerInjectEvent e) {
final String username = e.getPlayer().getName();
}
/**
* Called after the PlayerJoinEvent ONLY if the player has been injected!
*
* @param e
*/
@PacketHandler
public void onPostInject(final PostPlayerInjectEvent e) {
//It is safe to get his client version in here.
final ClientVersion clientVersion = PacketEvents.getClientVersion(e.getPlayer());
}
@EventHandler
public void onJoin(PlayerJoinEvent e) {
if (hasInjected(e.getPlayer())) {
PacketEvents.getEventManager().callEvent(new PostPlayerInjectEvent(e.getPlayer()));
}
}
}
@@ -4,8 +4,9 @@ package io.github.retrooper.packetevents.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Is for sure not null.
* Is for sure not null.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@@ -6,7 +6,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Could be null.
* Could be null.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@@ -59,7 +59,7 @@ public enum ClientVersion {
default:
remainder = protocolVersion;
}
if(remainder > 578) {
if (remainder > 578) {
return HIGHER_THAN_V_1_15_2;
}
return INVALID;
@@ -78,18 +78,18 @@ public enum ClientVersion {
/**
* Returns if the client's version is more outdated than the argument passed version
*
* @param version
* @return
*/
public boolean isLowerThan(final ClientVersion version) {
if(version == this) return false;
if (version == this) return false;
byte len = (byte) values().length;
for (byte i = 0; i < len; i++) {
final ClientVersion v = values()[i];
if(v == this) {
if (v == this) {
return true;
}
else if(v == version) {
} else if (v == version) {
return false;
}
}
@@ -1,9 +1,7 @@
package io.github.retrooper.packetevents.enums;
public enum Direction {
DOWN, UP, NORTH, SOUTH, WEST, EAST
,NORTH_EAST,
DOWN, UP, NORTH, SOUTH, WEST, EAST, NORTH_EAST,
NORTH_WEST, SOUTH_EAST,
SOUTH_WEST, WEST_NORTH_WEST,
NORTH_NORTH_WEST, NORTH_NORTH_EAST,
@@ -8,9 +8,9 @@ public enum EntityAnimationType {
}
public final int getIndex() {
for(int i = 0; i < values().length; i++) {
for (int i = 0; i < values().length; i++) {
final EntityAnimationType curType = values()[0];
if(curType == this) {
if (curType == this) {
return i;
}
}
@@ -2,5 +2,5 @@ package io.github.retrooper.packetevents.enums;
public enum Hand {
MAIN_HAND,
OFF_HAND;
OFF_HAND
}
@@ -9,6 +9,8 @@ public enum ServerVersion {
ERROR;
private static final String nmsVersionSuffix = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
public static ServerVersion getVersion() {
ServerVersion[] vals = values();
ArrayUtils.reverse(vals);
@@ -21,8 +23,6 @@ public enum ServerVersion {
return ERROR;
}
private static final String nmsVersionSuffix = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
public static String getNmsSuffix() {
return nmsVersionSuffix;
}
@@ -53,14 +53,13 @@ public enum ServerVersion {
* @return
*/
public boolean isLowerThan(final ServerVersion version) {
if(version == this) return false;
if (version == this) return false;
byte len = (byte) values().length;
for (byte i = 0; i < len; i++) {
final ServerVersion v = values()[i];
if(v == this) {
if (v == this) {
return true;
}
else if(v == version) {
} else if (v == version) {
return false;
}
}
@@ -9,11 +9,12 @@ import io.github.retrooper.packetevents.enums.ServerVersion;
* recommended to avoid non thread safe bukkit operations
*/
public class PacketEvent {
protected long timestamp = PacketEvents.currentCalculatedMS();
protected static ServerVersion version = PacketEvents.getServerVersion();
protected long timestamp = PacketEvents.currentCalculatedMS();
/**
* Timestamp of the packet
*
* @return
*/
public long getTimestamp() {
@@ -1,4 +1,4 @@
package io.github.retrooper.packetevents.event;
public interface PacketListener {
public interface PacketListener {
}
@@ -6,8 +6,9 @@ public final class PacketLoginEvent extends PacketEvent {
private final Object channel;
private final String name;
private final Object packet;
public PacketLoginEvent(final Object channel, final String packetName, final Object packet) {
this.channel =channel;
this.channel = channel;
this.name = packetName;
this.packet = packet;
}
@@ -42,15 +42,6 @@ public final class PacketReceiveEvent extends PacketEvent {
return this.packet;
}
/**
* Cancel the packet
*
* @param cancelled
*/
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
/**
* Returns if the packet has been cancelled
*
@@ -59,4 +50,13 @@ public final class PacketReceiveEvent extends PacketEvent {
public boolean isCancelled() {
return cancelled;
}
/**
* Cancel the packet
*
* @param cancelled
*/
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}
@@ -35,13 +35,12 @@ public final class PacketSendEvent extends PacketEvent {
return this.packet;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public boolean isCancelled() {
return cancelled;
}
}
@@ -6,6 +6,7 @@ import org.bukkit.entity.Player;
public final class PlayerInjectEvent extends PacketEvent {
private final Player player;
private boolean cancelled;
public PlayerInjectEvent(final Player player) {
this.player = player;
}
@@ -7,7 +7,7 @@ public final class PlayerUninjectEvent extends PacketEvent {
private final Player player;
public PlayerUninjectEvent(final Player player) {
this.player =player;
this.player = player;
}
public Player getPlayer() {
@@ -6,6 +6,7 @@ import io.github.retrooper.packetevents.event.PacketEvent;
public final class ServerTickEvent extends PacketEvent {
private final int tick;
private final double tps;
public ServerTickEvent(final int tick, final long timestamp) {
this.tick = tick;
this.timestamp = timestamp;
@@ -9,10 +9,13 @@ import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public final class EventManager {
private HashMap<PacketListener, List<Method>> registeredMethods = new HashMap<PacketListener, List<Method>>();
private static final ExecutorService executorService = Executors.newCachedThreadPool();
private final HashMap<PacketListener, List<Method>> registeredMethods = new HashMap<PacketListener, List<Method>>();
public void callEvent(final PacketEvent e) {
for (final PacketListener listener : registeredMethods.keySet()) {
@@ -32,7 +35,6 @@ public final class EventManager {
}
}
public void registerListener(final PacketListener e) {
if (registeredMethods.containsKey(e)) {
return;
@@ -57,7 +59,7 @@ public final class EventManager {
registeredMethods.clear();
}
public boolean hasRegistered(final PacketListener listener) {
public boolean isRegistered(final PacketListener listener) {
return registeredMethods.containsKey(listener);
}
}
@@ -8,10 +8,15 @@ public class MainExample extends JavaPlugin {
@Override
public void onEnable() {
PacketEvents.start(this);
PacketEvents.getServerTickTask().cancel();
//To fix bugs it is recommend to set this to TRUE
PacketEvents.setShouldKickOnRestart(true);
}
@Override
public void onDisable() {
PacketEvents.stop();
PacketEvents.stop(); //it kicks when you call the stop() function
}
}
@@ -11,8 +11,23 @@ import org.bukkit.plugin.Plugin;
public final class TinyProtocolHandler {
private static final ServerVersion version = PacketEvents.getServerVersion();
private static final FieldAccessor<?> playerConnectionAccessor, networkManagerAccessor, nettyChannelAccessor;
private static Object tinyProtocol;
private static Class<?> networkManagerClass;
private static Class<?> channelClass;
static {
try {
networkManagerClass = NMSUtils.getNMSClass("NetworkManager");
channelClass = NMSUtils.getNettyClass("channel.Channel");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
playerConnectionAccessor = Reflection.getField(NMSUtils.entityPlayerClass, NMSUtils.playerConnectionClass, 0);
networkManagerAccessor = Reflection.getField(NMSUtils.playerConnectionClass, networkManagerClass, 0);
nettyChannelAccessor = Reflection.getField(networkManagerClass, channelClass, 0);
}
public static void initTinyProtocol(final Plugin plugin) {
if (version.isLowerThan(ServerVersion.v_1_8)) {
@@ -62,31 +77,10 @@ public final class TinyProtocolHandler {
}
}
public static Object getPlayerChannel(final Player player) {
final Object entityPlayer = NMSUtils.getEntityPlayer(player);
final Object playerConnection = playerConnectionAccessor.get(entityPlayer);
final Object networkManager = networkManagerAccessor.get(playerConnection);
return nettyChannelAccessor.get(networkManager);
}
private static Class<?> networkManagerClass;
private static final FieldAccessor<?> playerConnectionAccessor, networkManagerAccessor, nettyChannelAccessor;
private static Class<?> channelClass;
static {
try {
networkManagerClass = NMSUtils.getNMSClass("NetworkManager");
channelClass = NMSUtils.getNettyClass("channel.Channel");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
playerConnectionAccessor = Reflection.getField(NMSUtils.entityPlayerClass, NMSUtils.playerConnectionClass, 0);
networkManagerAccessor = Reflection.getField(NMSUtils.playerConnectionClass, networkManagerClass, 0);
nettyChannelAccessor = Reflection.getField(networkManagerClass, channelClass, 0);
}
}
@@ -13,14 +13,13 @@ import org.bukkit.plugin.Plugin;
public final class TinyProtocolHandler_1_7 {
private final Plugin plugin;
@Nullable
public TinyProtocol7 tinyProtocol;
public TinyProtocolHandler_1_7(final Plugin plugin) {
this.plugin = plugin;
}
@Nullable
public TinyProtocol7 tinyProtocol;
public void initTinyProtocol() {
tinyProtocol = new TinyProtocol7(getPlugin()) {
@Override
@@ -37,8 +36,8 @@ public final class TinyProtocolHandler_1_7 {
@Override
public Object onPacketInAsync(Player sender, Channel channel, Object packet) {
final String packetName = packet.getClass().getSimpleName();
for(final String loginPacket : Packet.Login.LOGIN_PACKETS) {
if(packetName.equals(loginPacket)) {
for (final String loginPacket : Packet.Login.LOGIN_PACKETS) {
if (packetName.equals(loginPacket)) {
PacketEvents.getEventManager().callEvent(new PacketLoginEvent(channel, packetName, packet));
return packet;
}
@@ -15,16 +15,32 @@ import org.bukkit.plugin.Plugin;
public final class TinyProtocolHandler_1_8 {
private static final ServerVersion version = PacketEvents.getServerVersion();
private final Plugin plugin;
@Nullable
public TinyProtocol8 tinyProtocol;
public TinyProtocolHandler_1_8(final Plugin plugin) {
this.plugin = plugin;
}
@Nullable
public TinyProtocol8 tinyProtocol;
public static String getNetworkManagersFieldName() {
//1.8
if (version.equals(ServerVersion.v_1_8)) {
return "g";
}
//1.8.3->1.12
else if (version.isLowerThan(ServerVersion.v_1_13)) {
return "h";
}
//1.13->1.14
else if (version.isLowerThan(ServerVersion.v_1_15)) {
return "g";
}
//1.15
else {
return "listeningChannels";
}
}
public void initTinyProtocol() {
tinyProtocol = new TinyProtocol8(getPlugin()) {
@@ -59,25 +75,6 @@ public final class TinyProtocolHandler_1_8 {
};
}
public static String getNetworkManagersFieldName() {
//1.8
if (version.equals(ServerVersion.v_1_8)) {
return "g";
}
//1.8.3->1.12
else if (version.isLowerThan(ServerVersion.v_1_13)) {
return "h";
}
//1.13->1.14
else if (version.isLowerThan(ServerVersion.v_1_15)) {
return "g";
}
//1.15
else {
return "listeningChannels";
}
}
public Plugin getPlugin() {
return plugin;
}
@@ -39,10 +39,8 @@ public class GameProfile {
public boolean equalsMojangGameProfile(com.mojang.authlib.GameProfile profile) {
if (profile != null) {
if (profile.getId() != null && getId() != null && profile.getId() == getId()
&& profile.getName() != null && getName() != null && profile.getName().equals(getName())) {
return true;
}
return profile.getId() != null && getId() != null && profile.getId() == getId()
&& profile.getName() != null && getName() != null && profile.getName().equals(getName());
}
return false;
}
@@ -61,14 +59,8 @@ public class GameProfile {
}
if (this.name != null) {
if (this.name.equals(that.name)) {
return true;
}
} else if (that.name == null) {
return true;
}
return false;
return this.name.equals(that.name);
} else return that.name == null;
} else {
return false;
}
@@ -5,6 +5,58 @@ import io.github.retrooper.packetevents.utils.NMSUtils;
public abstract class Packet {
private static Class<?> packetPlayInFlying, packetPlayInPosition, packetPlayInPositionLook, packetPlayInLook;
static {
try {
packetPlayInFlying = NMSUtils.getNMSClass(Client.FLYING);
} catch (ClassNotFoundException e) {
//That is fine, they are on 1.9+ so we just initiate the rest of the variables
try {
packetPlayInPosition = NMSUtils.getNMSClass(Client.POSITION);
packetPlayInPositionLook = NMSUtils.getNMSClass(Client.POSITION_LOOK);
packetPlayInLook = NMSUtils.getNMSClass(Client.LOOK);
} catch (ClassNotFoundException e2) {
e2.printStackTrace();
}
}
}
/**
* Is this NMS packet an instanceof the "PacketPlayInFlying" packet in the 1.8 protocol?
* Supports 1.9->1.15.2 too!
*
* @param nmsPacket
* @return If the nms packet provided is an instanceof the "PacketPlayInFlying" packet in the 1.8 protocol!
*/
public static boolean isInstanceOfFlyingPacket(Object nmsPacket) {
//1.7->1.8.8
if (packetPlayInFlying != null) {
return packetPlayInFlying.isInstance(nmsPacket);
} else {
//1.9->1.15.2
return packetPlayInPosition.isInstance(nmsPacket)
|| packetPlayInPositionLook.isInstance(nmsPacket)
|| packetPlayInLook.isInstance(nmsPacket);
}
}
/**
* Use isInstanceOfFlyingPacket(nmsPacketObject) instead of this, as the flying packet is the only packet that has subclasses (in 1.8 atleast).
* Will be removed in newer versions of PacketEvents!
*
* @param fatherPacket
* @param childPacket
* @return isInstanceOf
*/
@Deprecated
public static boolean isInstanceOf(String fatherPacket, String childPacket) {
if (fatherPacket.equals(Client.FLYING) && childPacket.equals(Client.POSITION) || childPacket.equals(Client.POSITION_LOOK) || childPacket.equals(Client.LOOK)) {
return true;
}
return fatherPacket.equals(childPacket);
}
public static class Client {
private static final String c = "PacketPlayIn";
@@ -83,54 +135,4 @@ public abstract class Packet {
public static final String[] LOGIN_PACKETS = new String[]{"PacketHandshakingInSetProtocol", "PacketLoginInStart", "PacketLoginInEncryptionBegin"};
}
/**
* Is this NMS packet an instanceof the "PacketPlayInFlying" packet in the 1.8 protocol?
* Supports 1.9->1.15.2 too!
* @param nmsPacket
* @return If the nms packet provided is an instanceof the "PacketPlayInFlying" packet in the 1.8 protocol!
*/
public static boolean isInstanceOfFlyingPacket(Object nmsPacket) {
//1.7->1.8.8
if (packetPlayInFlying != null) {
return packetPlayInFlying.isInstance(nmsPacket);
} else {
//1.9->1.15.2
return packetPlayInPosition.isInstance(nmsPacket)
|| packetPlayInPositionLook.isInstance(nmsPacket)
|| packetPlayInLook.isInstance(nmsPacket);
}
}
/**
* Use isInstanceOfFlyingPacket(nmsPacketObject) instead of this, as the flying packet is the only packet that has subclasses (in 1.8 atleast).
* Will be removed in newer versions of PacketEvents!
* @param fatherPacket
* @param childPacket
* @return isInstanceOf
*/
@Deprecated
public static boolean isInstanceOf(String fatherPacket, String childPacket) {
if (fatherPacket.equals(Client.FLYING) && childPacket.equals(Client.POSITION) || childPacket.equals(Client.POSITION_LOOK) || childPacket.equals(Client.LOOK)) {
return true;
}
return fatherPacket.equals(childPacket);
}
private static Class<?> packetPlayInFlying, packetPlayInPosition, packetPlayInPositionLook, packetPlayInLook;
static {
try {
packetPlayInFlying = NMSUtils.getNMSClass(Client.FLYING);
} catch (ClassNotFoundException e) {
//That is fine, they are on 1.9+ so we just initiate the rest of the variables
try {
packetPlayInPosition = NMSUtils.getNMSClass(Client.POSITION);
packetPlayInPositionLook = NMSUtils.getNMSClass(Client.POSITION_LOOK);
packetPlayInLook = NMSUtils.getNMSClass(Client.LOOK);
} catch (ClassNotFoundException e2) {
e2.printStackTrace();
}
}
}
}
@@ -1,5 +1,5 @@
package io.github.retrooper.packetevents.packetwrappers;
public interface Sendable {
public Object asNMSPacket();
Object asNMSPacket();
}
@@ -4,13 +4,13 @@ import io.github.retrooper.packetevents.enums.ServerVersion;
import org.bukkit.entity.Player;
public class WrappedPacket {
protected static ServerVersion version = ServerVersion.getVersion();
protected final Player player;
protected Object packet;
protected static ServerVersion version = ServerVersion.getVersion();
public WrappedPacket(final Object packet) {
this.player = null;
if(packet == null)return;
if (packet == null) return;
this.packet = packet;
try {
setup();
@@ -21,7 +21,7 @@ public class WrappedPacket {
public WrappedPacket(final Player player, final Object packet) {
this.player = player;
if(packet == null)return;
if (packet == null) return;
this.packet = packet;
try {
setup();
@@ -30,7 +30,7 @@ public class WrappedPacket {
}
}
protected void setup() {
protected void setup() {
}
@@ -6,6 +6,36 @@ import io.github.retrooper.packetevents.utils.NMSUtils;
import java.lang.reflect.Field;
public final class WrappedPacketInAbilities extends WrappedPacket {
private static Class<?> abilitiesClass;
private static final Field[] fields = new Field[6];
static {
try {
abilitiesClass = NMSUtils.getNMSClass("PacketPlayInAbilities");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
fields[0] = abilitiesClass.getDeclaredField("a");
fields[1] = abilitiesClass.getDeclaredField("b");
fields[2] = abilitiesClass.getDeclaredField("c");
fields[3] = abilitiesClass.getDeclaredField("d");
fields[4] = abilitiesClass.getDeclaredField("e");
fields[5] = abilitiesClass.getDeclaredField("f");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
for (Field f : fields) {
if (f != null) {
f.setAccessible(true);
}
}
}
private boolean isVulnerable;
private boolean isFlying;
private boolean allowFly;
@@ -54,35 +84,4 @@ public final class WrappedPacketInAbilities extends WrappedPacket {
public float getWalkSpeed() {
return walkSpeed;
}
private static Class<?> abilitiesClass;
private static Field[] fields = new Field[6];
static {
try {
abilitiesClass = NMSUtils.getNMSClass("PacketPlayInAbilities");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
fields[0] = abilitiesClass.getDeclaredField("a");
fields[1] = abilitiesClass.getDeclaredField("b");
fields[2] = abilitiesClass.getDeclaredField("c");
fields[3] = abilitiesClass.getDeclaredField("d");
fields[4] = abilitiesClass.getDeclaredField("e");
fields[5] = abilitiesClass.getDeclaredField("f");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
for (Field f : fields) {
if (f != null) {
f.setAccessible(true);
}
}
}
}
@@ -11,79 +11,14 @@ import io.github.retrooper.packetevents.utils.vector.Vector3i;
import java.lang.reflect.Field;
public final class WrappedPacketInBlockDig extends WrappedPacket {
private Vector3i blockPosition;
private Direction direction;
private PlayerDigType digType;
public WrappedPacketInBlockDig(Object packet) {
super(packet);
}
@Override
protected void setup() {
Direction enumDirection = null;
PlayerDigType enumDigType = null;
//1.7.10
try {
if (version == ServerVersion.v_1_7_10) {
final int x = fields[0].getInt(packet);
final int y = fields[1].getInt(packet);
final int z = fields[2].getInt(packet);
this.blockPosition = new Vector3i(x, y, z);
enumDirection = Direction.get((byte) face.getInt(packet));
enumDigType = PlayerDigType.get((byte) e.getInt(packet));
} else {
//1.8+
final Object blockPosObj = fields[0].get(packet);
final Object enumDirectionObj = fields[1].get(packet);
final Object digTypeObj = fields[2].get(packet);
final int x = blockPosXYZ[0].get(blockPosObj);
final int y = blockPosXYZ[1].get(blockPosObj);
final int z = blockPosXYZ[2].get(blockPosObj);
this.blockPosition = new Vector3i(x, y, z);
enumDirection = Direction.valueOf(((Enum) enumDirectionObj).name());
enumDigType = PlayerDigType.valueOf(((Enum) digTypeObj).name());
}
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
this.direction = enumDirection;
this.digType = enumDigType;
}
public Vector3i getBlockPosition() {
return blockPosition;
}
public Direction getDirection() {
return direction;
}
public PlayerDigType getDigType() {
return digType;
}
//ALL
private static Class<?> blockDigClass;
//1.8
private static Field[] fields = new Field[3];
private static final Field[] fields = new Field[3];
private static Class<?> blockPositionClass;
private static Reflection.FieldAccessor<Integer>[] blockPosXYZ = new Reflection.FieldAccessor[3];
private static final Reflection.FieldAccessor<Integer>[] blockPosXYZ = new Reflection.FieldAccessor[3];
//1.7
private static Field face;
private static Field e;
static {
@@ -118,20 +53,77 @@ public final class WrappedPacketInBlockDig extends WrappedPacket {
e.printStackTrace();
}
for(Field f : fields) {
if(f != null) {
for (Field f : fields) {
if (f != null) {
f.setAccessible(true);
}
}
if(e != null) {
if (e != null) {
e.setAccessible(true);
}
if(face != null) {
if (face != null) {
face.setAccessible(true);
}
}
private Vector3i blockPosition;
private Direction direction;
private PlayerDigType digType;
public WrappedPacketInBlockDig(Object packet) {
super(packet);
}
@Override
protected void setup() {
Direction enumDirection = null;
PlayerDigType enumDigType = null;
//1.7.10
try {
if (version == ServerVersion.v_1_7_10) {
final int x = fields[0].getInt(packet);
final int y = fields[1].getInt(packet);
final int z = fields[2].getInt(packet);
this.blockPosition = new Vector3i(x, y, z);
enumDirection = Direction.get((byte) face.getInt(packet));
enumDigType = PlayerDigType.get((byte) e.getInt(packet));
} else {
//1.8+
final Object blockPosObj = fields[0].get(packet);
final Object enumDirectionObj = fields[1].get(packet);
final Object digTypeObj = fields[2].get(packet);
final int x = blockPosXYZ[0].get(blockPosObj);
final int y = blockPosXYZ[1].get(blockPosObj);
final int z = blockPosXYZ[2].get(blockPosObj);
this.blockPosition = new Vector3i(x, y, z);
enumDirection = Direction.valueOf(((Enum) enumDirectionObj).name());
enumDigType = PlayerDigType.valueOf(((Enum) digTypeObj).name());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
this.direction = enumDirection;
this.digType = enumDigType;
}
public Vector3i getBlockPosition() {
return blockPosition;
}
public Direction getDirection() {
return direction;
}
public PlayerDigType getDigType() {
return digType;
}
}
@@ -9,6 +9,14 @@ import org.bukkit.inventory.ItemStack;
public final class WrappedPacketInBlockPlace extends WrappedPacket {
static {
if (version.isHigherThan(ServerVersion.v_1_8_8)) {
WrappedPacketInBlockPlace_1_9.initStatic();
} else if (version.isLowerThan(ServerVersion.v_1_9) && version.isHigherThan(ServerVersion.v_1_7_10)) {
WrappedPacketInBlockPlace_1_8.initStatic();
}
}
private Vector3i blockPosition;
private ItemStack itemStack;
@@ -22,22 +30,23 @@ public final class WrappedPacketInBlockPlace extends WrappedPacket {
Vector3i position = null;
ItemStack itemStack = null;
try {
if (version.isHigherThan(ServerVersion.v_1_8_8)) {
final WrappedPacketInBlockPlace_1_9 updatedBlockPlace = new WrappedPacketInBlockPlace_1_9(getPlayer(), packet);
final Block block = updatedBlockPlace.getBlock();
position = new Vector3i(block.getX(), block.getY(), block.getZ());
itemStack = new ItemStack(block.getType());
} else {
final WrappedPacketInBlockPlace_1_8 legacyBlockPlace = new WrappedPacketInBlockPlace_1_8(packet);
position = legacyBlockPlace.getBlockPosition();
itemStack = legacyBlockPlace.getItemStack();
} }
catch(IllegalArgumentException e) {
if (version.isHigherThan(ServerVersion.v_1_8_8)) {
final WrappedPacketInBlockPlace_1_9 updatedBlockPlace = new WrappedPacketInBlockPlace_1_9(getPlayer(), packet);
final Block block = updatedBlockPlace.getBlock();
position = new Vector3i(block.getX(), block.getY(), block.getZ());
itemStack = new ItemStack(block.getType());
} else {
final WrappedPacketInBlockPlace_1_8 legacyBlockPlace = new WrappedPacketInBlockPlace_1_8(packet);
position = legacyBlockPlace.getBlockPosition();
itemStack = legacyBlockPlace.getItemStack();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
this.blockPosition = position;
this.itemStack = itemStack;
}
public Player getPlayer() {
return this.player;
}
@@ -50,12 +59,4 @@ public final class WrappedPacketInBlockPlace extends WrappedPacket {
return itemStack;
}
static {
if (version.isHigherThan(ServerVersion.v_1_8_8)) {
WrappedPacketInBlockPlace_1_9.initStatic();
} else if(version.isLowerThan(ServerVersion.v_1_9) && version.isHigherThan(ServerVersion.v_1_7_10)){
WrappedPacketInBlockPlace_1_8.initStatic();
}
}
}
@@ -10,6 +10,7 @@ final class WrappedPacketInBlockPlace_1_7_10 extends WrappedPacket {
private Vector3i blockPosition;
private ItemStack itemStack;
private int blockFace;
WrappedPacketInBlockPlace_1_7_10(final Player player, final Object packet) {
super(player, packet);
}
@@ -17,14 +18,14 @@ final class WrappedPacketInBlockPlace_1_7_10 extends WrappedPacket {
@Override
protected void setup() {
final PacketPlayInBlockPlace blockPlace = (PacketPlayInBlockPlace)packet;
final PacketPlayInBlockPlace blockPlace = (PacketPlayInBlockPlace) packet;
this.blockPosition = new Vector3i(blockPlace.c(), blockPlace.d(), blockPlace.e());
this.blockFace = blockPlace.d();
net.minecraft.server.v1_7_R4.ItemStack stack = blockPlace.getItemStack();
this.itemStack = org.bukkit.craftbukkit.v1_7_R4.inventory.CraftItemStack.asBukkitCopy(stack);
this.itemStack = org.bukkit.craftbukkit.v1_7_R4.inventory.CraftItemStack.asBukkitCopy(stack);
}
public Vector3i getBlockPosition() {
@@ -7,12 +7,34 @@ import io.github.retrooper.packetevents.utils.vector.Vector3i;
import org.bukkit.inventory.ItemStack;
final class WrappedPacketInBlockPlace_1_8 extends WrappedPacket {
private static final Reflection.MethodInvoker[] blockPositionXYZInvoker = new Reflection.MethodInvoker[3];
private static Class<?> blockPlaceClass, blockPositionClass;
private static Reflection.FieldAccessor<?> blockPositionAccessor, itemStackFieldAccessor;
private Vector3i blockPosition;
private ItemStack itemStack;
WrappedPacketInBlockPlace_1_8(final Object packet) {
super(packet);
}
protected static void initStatic() {
try {
blockPlaceClass = NMSUtils.getNMSClass("PacketPlayInBlockPlace");
blockPositionClass = NMSUtils.getNMSClass("BlockPosition");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
itemStackFieldAccessor = Reflection.getField(blockPlaceClass, NMSUtils.nmsItemStackClass, 0);
blockPositionAccessor = Reflection.getField(blockPlaceClass, blockPositionClass, 1);
blockPositionXYZInvoker[0] = Reflection.getMethod(blockPositionClass.getSuperclass(), "getX");
blockPositionXYZInvoker[1] = Reflection.getMethod(blockPositionClass.getSuperclass(), "getY");
blockPositionXYZInvoker[2] = Reflection.getMethod(blockPositionClass.getSuperclass(), "getZ");
}
@Override
protected void setup() {
Object nmsBlockPos = blockPositionAccessor.get(packet);
@@ -33,27 +55,4 @@ final class WrappedPacketInBlockPlace_1_8 extends WrappedPacket {
public ItemStack getItemStack() {
return itemStack;
}
private static Class<?> blockPlaceClass, blockPositionClass;
private static Reflection.FieldAccessor<?> blockPositionAccessor, itemStackFieldAccessor;
private static final Reflection.MethodInvoker[] blockPositionXYZInvoker = new Reflection.MethodInvoker[3];
protected static void initStatic(){
try {
blockPlaceClass = NMSUtils.getNMSClass("PacketPlayInBlockPlace");
blockPositionClass = NMSUtils.getNMSClass("BlockPosition");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
itemStackFieldAccessor = Reflection.getField(blockPlaceClass, NMSUtils.nmsItemStackClass, 0);
blockPositionAccessor = Reflection.getField(blockPlaceClass, blockPositionClass, 1);
blockPositionXYZInvoker[0] = Reflection.getMethod(blockPositionClass.getSuperclass(), "getX");
blockPositionXYZInvoker[1] = Reflection.getMethod(blockPositionClass.getSuperclass(), "getY");
blockPositionXYZInvoker[2] = Reflection.getMethod(blockPositionClass.getSuperclass(), "getZ");
}
}
@@ -10,15 +10,24 @@ import org.bukkit.entity.Player;
import java.util.HashSet;
final class WrappedPacketInBlockPlace_1_9 extends WrappedPacket {
private static Class<?> blockPlaceClass_1_9;
private Block block;
public WrappedPacketInBlockPlace_1_9(final Player player, final Object packet) {
super(player, packet);
}
protected static void initStatic() {
try {
blockPlaceClass_1_9 = NMSUtils.getNMSClass("PacketPlayInUseItem");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
@Override
protected void setup() {
this.block = getPlayer().getTargetBlock((HashSet<Material>)null, 3);
this.block = getPlayer().getTargetBlock(null, 3);
}
@@ -30,14 +39,5 @@ final class WrappedPacketInBlockPlace_1_9 extends WrappedPacket {
return block;
}
private static Class<?> blockPlaceClass_1_9;
protected static void initStatic() {
try {
blockPlaceClass_1_9 = NMSUtils.getNMSClass("PacketPlayInUseItem");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
@@ -7,28 +7,7 @@ import io.github.retrooper.packetevents.utils.NMSUtils;
import java.lang.reflect.Field;
public final class WrappedPacketInChat extends WrappedPacket {
private String message;
public WrappedPacketInChat(Object packet) {
super(packet);
}
@Override
protected void setup() {
try {
final Object obj = field.get(packet);
this.message = obj.toString();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public String getMessage() {
return message;
}
private static Class<?> chatPacketClass;
private static Field field;
static {
@@ -48,10 +27,30 @@ public final class WrappedPacketInChat extends WrappedPacket {
field.setAccessible(true);
}
private String message;
public WrappedPacketInChat(Object packet) {
super(packet);
}
private static String getChatFieldName() {
if (version == ServerVersion.v_1_7_10) {
return "message";
}
return "a";
}
@Override
protected void setup() {
try {
final Object obj = field.get(packet);
this.message = obj.toString();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public String getMessage() {
return message;
}
}
@@ -10,6 +10,40 @@ import org.bukkit.entity.Entity;
import java.lang.reflect.Field;
public final class WrappedPacketInEntityAction extends WrappedPacket {
private static Class<?> entityActionClass;
@Nullable
private static Class<?> enumPlayerActionClass;
private static final Field[] fields = new Field[3];
@Nullable
private static Object[] enumPlayerActionConstants;
static {
try {
entityActionClass = NMSUtils.getNMSClass("PacketPlayInEntityAction");
if (version.isHigherThan(ServerVersion.v_1_7_10)) {
enumPlayerActionClass = NMSUtils.getNMSClass("PacketPlayInEntityAction$EnumPlayerAction");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
//ints in 1.7.10, EnumPlayerAction in 1.8+
fields[0] = entityActionClass.getDeclaredField("a");
fields[1] = entityActionClass.getDeclaredField("animation");
fields[2] = entityActionClass.getDeclaredField("c");
if (version.isHigherThan(ServerVersion.v_1_7_10)) {
enumPlayerActionConstants = enumPlayerActionClass.getEnumConstants();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
for (final Field f : fields) {
f.setAccessible(true);
}
}
private Entity entity;
private int entityId;
private PlayerAction action;
@@ -71,41 +105,4 @@ public final class WrappedPacketInEntityAction extends WrappedPacket {
public int getJumpBoost() {
return jumpBoost;
}
private static Class<?> entityActionClass;
@Nullable
private static Class<?> enumPlayerActionClass;
private static Field[] fields = new Field[3];
@Nullable
private static Object[] enumPlayerActionConstants;
static {
try {
entityActionClass = NMSUtils.getNMSClass("PacketPlayInEntityAction");
if (version.isHigherThan(ServerVersion.v_1_7_10)) {
enumPlayerActionClass = NMSUtils.getNMSClass("PacketPlayInEntityAction$EnumPlayerAction");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
//ints in 1.7.10, EnumPlayerAction in 1.8+
fields[0] = entityActionClass.getDeclaredField("a");
fields[1] = entityActionClass.getDeclaredField("animation");
fields[2] = entityActionClass.getDeclaredField("c");
if (version.isHigherThan(ServerVersion.v_1_7_10)) {
enumPlayerActionConstants = enumPlayerActionClass.getEnumConstants();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
for (final Field f : fields) {
f.setAccessible(true);
}
}
}
@@ -8,6 +8,38 @@ import io.github.retrooper.packetevents.utils.NMSUtils;
import java.lang.reflect.Field;
public class WrappedPacketInFlying extends WrappedPacket {
private static Class<?> flyingClass;
private static final Field[] fields = new Field[8]; //x, y, z, yaw pitch, onGround, isPositionPacket, isLookPacket
static {
try {
flyingClass = NMSUtils.getNMSClass("PacketPlayInFlying");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
fields[0] = flyingClass.getDeclaredField("x");
fields[1] = flyingClass.getDeclaredField("y");
fields[2] = flyingClass.getDeclaredField("z");
fields[3] = flyingClass.getDeclaredField("yaw");
fields[4] = flyingClass.getDeclaredField("pitch");
fields[5] = flyingClass.getDeclaredField(getOnGroundFieldName());
fields[6] = flyingClass.getDeclaredField("hasPos");
fields[7] = flyingClass.getDeclaredField("hasLook");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
for (Field f : fields) {
if (f != null) {
f.setAccessible(true);
}
}
}
private double x;
private double y;
private double z;
@@ -21,6 +53,13 @@ public class WrappedPacketInFlying extends WrappedPacket {
super(packet);
}
private static String getOnGroundFieldName() {
if (version == ServerVersion.v_1_7_10) {
return "g";
}
return "f";
}
@Override
protected void setup() {
try {
@@ -40,38 +79,6 @@ public class WrappedPacketInFlying extends WrappedPacket {
}
}
public static class WrappedPacketInPosition extends WrappedPacketInFlying {
public WrappedPacketInPosition(Object packet) {
super(packet);
}
@Override
public boolean isPosition() {
return true;
}
@Override
public boolean isLook() {
return false;
}
}
public static class WrappedPacketInPosition_Look extends WrappedPacketInFlying {
public WrappedPacketInPosition_Look(Object packet) {
super(packet);
}
@Override
public boolean isLook() {
return true;
}
@Override
public boolean isPosition() {
return false;
}
}
public final double getX() {
return x;
}
@@ -104,44 +111,36 @@ public class WrappedPacketInFlying extends WrappedPacket {
return isLook;
}
private static Class<?> flyingClass;
private static Field[] fields = new Field[8]; //x, y, z, yaw pitch, onGround, isPositionPacket, isLookPacket
static {
try {
flyingClass = NMSUtils.getNMSClass("PacketPlayInFlying");
} catch (ClassNotFoundException e) {
e.printStackTrace();
public static class WrappedPacketInPosition extends WrappedPacketInFlying {
public WrappedPacketInPosition(Object packet) {
super(packet);
}
try {
fields[0] = flyingClass.getDeclaredField("x");
fields[1] = flyingClass.getDeclaredField("y");
fields[2] = flyingClass.getDeclaredField("z");
fields[3] = flyingClass.getDeclaredField("yaw");
fields[4] = flyingClass.getDeclaredField("pitch");
fields[5] = flyingClass.getDeclaredField(getOnGroundFieldName());
fields[6] = flyingClass.getDeclaredField("hasPos");
fields[7] = flyingClass.getDeclaredField("hasLook");
} catch (NoSuchFieldException e) {
e.printStackTrace();
@Override
public boolean isPosition() {
return true;
}
for (Field f : fields) {
if (f != null) {
f.setAccessible(true);
}
@Override
public boolean isLook() {
return false;
}
}
private static String getOnGroundFieldName() {
if (version == ServerVersion.v_1_7_10) {
return "g";
public static class WrappedPacketInPosition_Look extends WrappedPacketInFlying {
public WrappedPacketInPosition_Look(Object packet) {
super(packet);
}
@Override
public boolean isLook() {
return true;
}
@Override
public boolean isPosition() {
return false;
}
return "f";
}
}
@@ -7,12 +7,31 @@ import io.github.retrooper.packetevents.utils.NMSUtils;
import java.lang.reflect.Field;
public final class WrappedPacketInKeepAlive extends WrappedPacket {
public WrappedPacketInKeepAlive(final Object packet) {
super(packet);
private static Class<?> keepAliveClass;
//1.7.10->1.12.2 has int field "a", rest as long field "a"
private static Field idField;
static {
try {
keepAliveClass = NMSUtils.getNMSClass("PacketPlayInKeepAlive");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
idField = keepAliveClass.getDeclaredField("a");
idField.setAccessible(true);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
private long id;
public WrappedPacketInKeepAlive(final Object packet) {
super(packet);
}
@Override
protected void setup() {
try {
@@ -35,24 +54,4 @@ public final class WrappedPacketInKeepAlive extends WrappedPacket {
public long getId() {
return id;
}
private static Class<?> keepAliveClass;
//1.7.10->1.12.2 has int field "a", rest as long field "a"
private static Field idField;
static {
try {
keepAliveClass = NMSUtils.getNMSClass("PacketPlayInKeepAlive");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
idField = keepAliveClass.getDeclaredField("a");
idField.setAccessible(true);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
@@ -8,46 +8,9 @@ import org.bukkit.entity.Entity;
import java.lang.reflect.Field;
public final class WrappedPacketInUseEntity extends WrappedPacket {
private int entityId;
private Entity entity;
private EntityUseAction action;
public WrappedPacketInUseEntity(final Object packet) {
super(packet);
}
@Override
protected void setup() {
try {
this.entityId = fields[0].getInt(packet);
this.entity = NMSUtils.getEntityById(this.entityId);
final Object useActionEnum = fields[1].get(packet);
this.action = EntityUseAction.valueOf(useActionEnum.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public Entity getEntity() {
return entity;
}
public int getEntityId() {
return entityId;
}
public EntityUseAction getAction() {
return action;
}
private static Class<?> useEntityClass;
private static Class<?> entityClass;
private static Field[] fields = new Field[2];
private static final Field[] fields = new Field[2];
static {
@@ -75,4 +38,36 @@ public final class WrappedPacketInUseEntity extends WrappedPacket {
}
}
private int entityId;
private Entity entity;
private EntityUseAction action;
public WrappedPacketInUseEntity(final Object packet) {
super(packet);
}
@Override
protected void setup() {
try {
this.entityId = fields[0].getInt(packet);
this.entity = NMSUtils.getEntityById(this.entityId);
final Object useActionEnum = fields[1].get(packet);
this.action = EntityUseAction.valueOf(useActionEnum.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public Entity getEntity() {
return entity;
}
public int getEntityId() {
return entityId;
}
public EntityUseAction getAction() {
return action;
}
}
@@ -7,6 +7,21 @@ import io.github.retrooper.packetevents.utils.NMSUtils;
public final class WrappedPacketLoginHandshake extends WrappedPacket {
private static Class<?> loginHandshakeClass;
private static final FieldAccessor<?>[] fields = new FieldAccessor[3];
static {
try {
loginHandshakeClass = NMSUtils.getNMSClass("PacketHandshakingInSetProtocol");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
fields[0] = Reflection.getField(loginHandshakeClass, int.class, 0);
fields[1] = Reflection.getField(loginHandshakeClass, String.class, 0);
fields[2] = Reflection.getField(loginHandshakeClass, int.class, 1);
}
private int protocolVersion, port;
private String hostname;
@@ -20,9 +35,9 @@ public final class WrappedPacketLoginHandshake extends WrappedPacket {
final Object hostNameObj = fields[1].get(packet);
final Object portObj = fields[2].get(packet);
this.protocolVersion = (int)protocolVersionObj;
this.protocolVersion = (int) protocolVersionObj;
this.hostname = hostNameObj.toString();
this.port = (int)portObj;
this.port = (int) portObj;
}
public int getProtocolVersion() {
@@ -36,20 +51,4 @@ public final class WrappedPacketLoginHandshake extends WrappedPacket {
public int getPort() {
return port;
}
private static Class<?> loginHandshakeClass;
private static FieldAccessor<?>[] fields = new FieldAccessor[3];
static {
try {
loginHandshakeClass = NMSUtils.getNMSClass("PacketHandshakingInSetProtocol");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
fields[0] = Reflection.getField(loginHandshakeClass, int.class, 0);
fields[1] = Reflection.getField(loginHandshakeClass, String.class, 0);
fields[2] = Reflection.getField(loginHandshakeClass, int.class, 1);
}
}
@@ -5,7 +5,22 @@ import io.github.retrooper.packetevents.tinyprotocol.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
public final class WrappedPacketLoginInEncryptionBegin extends WrappedPacket {
private static final Reflection.FieldAccessor<byte[]>[] fields = new Reflection.FieldAccessor[2];
private static Class<?> packetClass;
static {
try {
packetClass = NMSUtils.getNMSClass("PacketLoginInEncryptionBegin");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
fields[0] = Reflection.getField(packetClass, byte[].class, 0);
fields[1] = Reflection.getField(packetClass, byte[].class, 1);
}
private byte[] publicKey, verifyToken;
public WrappedPacketLoginInEncryptionBegin(final Object packet) {
super(packet);
}
@@ -23,19 +38,4 @@ public final class WrappedPacketLoginInEncryptionBegin extends WrappedPacket {
public byte[] getVerifyToken() {
return verifyToken;
}
private static Class<?> packetClass;
private static final Reflection.FieldAccessor<byte[]>[] fields = new Reflection.FieldAccessor[2];
static {
try {
packetClass = NMSUtils.getNMSClass("PacketLoginInEncryptionBegin");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
fields[0] = Reflection.getField(packetClass, byte[].class, 0);
fields[1] = Reflection.getField(packetClass, byte[].class, 1);
}
}
@@ -8,6 +8,21 @@ import java.security.PublicKey;
public final class WrappedPacketLoginOutEncryptionBegin extends WrappedPacket {
private static final Reflection.FieldAccessor<?>[] fields = new Reflection.FieldAccessor[3];
private static Class<?> packetClass;
static {
try {
packetClass = NMSUtils.getNMSClass("PacketLoginOutEncryptionBegin");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
fields[0] = Reflection.getField(packetClass, String.class, 0);
fields[1] = Reflection.getField(packetClass, PublicKey.class, 1);
fields[2] = Reflection.getField(packetClass, byte[].class, 2);
}
private String encodedString;
private PublicKey encodedKey;
private byte[] byteArray;
@@ -38,21 +53,5 @@ public final class WrappedPacketLoginOutEncryptionBegin extends WrappedPacket {
return byteArray;
}
private static Class<?> packetClass;
private static final Reflection.FieldAccessor<?>[] fields = new Reflection.FieldAccessor[3];
static {
try {
packetClass = NMSUtils.getNMSClass("PacketLoginOutEncryptionBegin");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
fields[0] = Reflection.getField(packetClass, String.class, 0);
fields[1] = Reflection.getField(packetClass, PublicKey.class, 1);
fields[2] = Reflection.getField(packetClass, byte[].class, 2);
}
}
@@ -6,7 +6,20 @@ import io.github.retrooper.packetevents.tinyprotocol.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
public final class WrappedPacketLoginStart extends WrappedPacket {
private static final Reflection.FieldAccessor<com.mojang.authlib.GameProfile> gameProfileAccessor;
private static Class<?> packetClass;
static {
try {
packetClass = NMSUtils.getNMSClass("PacketLoginInStart");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
gameProfileAccessor = Reflection.getField(packetClass, com.mojang.authlib.GameProfile.class, 0);
}
private GameProfile gameProfile;
public WrappedPacketLoginStart(final Object packet) {
super(packet);
}
@@ -20,17 +33,4 @@ public final class WrappedPacketLoginStart extends WrappedPacket {
public GameProfile getGameProfile() {
return gameProfile;
}
private static Class<?> packetClass;
private static final Reflection.FieldAccessor<com.mojang.authlib.GameProfile> gameProfileAccessor;
static {
try {
packetClass = NMSUtils.getNMSClass("PacketLoginInStart");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
gameProfileAccessor = Reflection.getField(packetClass, com.mojang.authlib.GameProfile.class, 0);
}
}
@@ -5,7 +5,21 @@ import io.github.retrooper.packetevents.tinyprotocol.Reflection;
import io.github.retrooper.packetevents.utils.NMSUtils;
public final class WrappedPacketLoginStatusPing extends WrappedPacket {
private static final Reflection.FieldAccessor<Long> numberAccessor;
private static Class<?> packetClass;
static {
try {
packetClass = NMSUtils.getNMSClass("PacketStatusInPing");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
numberAccessor = Reflection.getField(packetClass, long.class, 0);
}
private long number;
public WrappedPacketLoginStatusPing(final Object packet) {
super(packet);
}
@@ -19,18 +33,4 @@ public final class WrappedPacketLoginStatusPing extends WrappedPacket {
return number;
}
private static Class<?> packetClass;
private static final Reflection.FieldAccessor<Long> numberAccessor;
static {
try {
packetClass = NMSUtils.getNMSClass("PacketStatusInPing");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
numberAccessor = Reflection.getField(packetClass, long.class, 0);
}
}
@@ -11,6 +11,36 @@ import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public final class WrappedPacketOutAnimation extends WrappedPacket implements Sendable {
private static Class<?> animationClass, nmsEntityClass;
private static Constructor<?> animationConstructor;
private static final Field[] fields = new Field[2];
static {
try {
animationClass = NMSUtils.getNMSClass("PacketPlayOutAnimation");
nmsEntityClass = NMSUtils.getNMSClass("Entity");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
animationConstructor = animationClass.getConstructor(nmsEntityClass, int.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
fields[0] = animationClass.getDeclaredField("a");
fields[1] = animationClass.getDeclaredField("b");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
for (final Field f : fields) {
f.setAccessible(true);
}
}
private Entity entity;
private int entityID;
private EntityAnimationType type;
@@ -52,7 +82,6 @@ public final class WrappedPacketOutAnimation extends WrappedPacket implements Se
return type;
}
@Override
public Object asNMSPacket() {
final Object nmsEntity = NMSUtils.getNMSEntity(this.entity);
@@ -64,35 +93,4 @@ public final class WrappedPacketOutAnimation extends WrappedPacket implements Se
}
return null;
}
private static Class<?> animationClass, nmsEntityClass;
private static Constructor<?> animationConstructor;
private static Field[] fields = new Field[2];
static {
try {
animationClass = NMSUtils.getNMSClass("PacketPlayOutAnimation");
nmsEntityClass = NMSUtils.getNMSClass("Entity");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
animationConstructor = animationClass.getConstructor(nmsEntityClass, int.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
fields[0] = animationClass.getDeclaredField("a");
fields[1] = animationClass.getDeclaredField("b");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
for (final Field f : fields) {
f.setAccessible(true);
}
}
}
@@ -11,71 +11,9 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public final class WrappedPacketOutChat extends WrappedPacket implements Sendable {
private String message;
public WrappedPacketOutChat(final Object packet) {
super(packet);
}
public WrappedPacketOutChat(final String message) {
super(null);
this.message = "{\"text\": \"" + message + "\"}";
}
@Override
protected void setup() {
//all fields are IChatBaseComponents, and named 'a'
try {
Object iChatBaseObj = iChatBaseField.get(packet);
Object contentString = getStringOfIChatBase.invoke(iChatBaseObj);
this.message = contentString.toString();
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
@Override
public Object asNMSPacket() {
try {
return chatClassConstructor.newInstance(toIChatBaseComponent(this.message));
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static String toStringFromIChatBaseComponent(Object obj) {
try {
return getStringOfIChatBase.invoke(obj).toString();
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public static Object toIChatBaseComponent(String msg) {
try {
return serialize.invoke(null, msg);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public String getMessage() {
return this.message;
}
private static Constructor<?> chatClassConstructor;
private static Class<?> chatClass, iChatBaseComponentClass, chatSerializerClass;
private static Field iChatBaseField;
private static Method serialize, getStringOfIChatBase;
static {
@@ -84,15 +22,14 @@ public final class WrappedPacketOutChat extends WrappedPacket implements Sendabl
iChatBaseComponentClass = NMSUtils.getNMSClass("IChatBaseComponent");
//In 1.8.3+ the ChatSerializer class is declared in the IChatBaseComponent class, so we have to handle tahat
if(version.isHigherThan(ServerVersion.v_1_8)) {
for(final Class<?> cls : iChatBaseComponentClass.getDeclaredClasses()) {
if(cls.getSimpleName().equals("ChatSerializer")) {
if (version.isHigherThan(ServerVersion.v_1_8)) {
for (final Class<?> cls : iChatBaseComponentClass.getDeclaredClasses()) {
if (cls.getSimpleName().equals("ChatSerializer")) {
chatSerializerClass = cls;
break;
}
}
}
else {
} else {
chatSerializerClass = NMSUtils.getNMSClass("ChatSerializer");
}
} catch (ClassNotFoundException e) {
@@ -121,6 +58,35 @@ public final class WrappedPacketOutChat extends WrappedPacket implements Sendabl
}
private String message;
public WrappedPacketOutChat(final Object packet) {
super(packet);
}
public WrappedPacketOutChat(final String message) {
super(null);
this.message = "{\"text\": \"" + message + "\"}";
}
public static String toStringFromIChatBaseComponent(Object obj) {
try {
return getStringOfIChatBase.invoke(obj).toString();
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public static Object toIChatBaseComponent(String msg) {
try {
return serialize.invoke(null, msg);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
private static String getTextMethodName() {
//1.7.10
if (version.isLowerThan(ServerVersion.v_1_8)) {
@@ -129,4 +95,34 @@ public final class WrappedPacketOutChat extends WrappedPacket implements Sendabl
return "getText";
}
}
@Override
protected void setup() {
//all fields are IChatBaseComponents, and named 'a'
try {
Object iChatBaseObj = iChatBaseField.get(packet);
Object contentString = getStringOfIChatBase.invoke(iChatBaseObj);
this.message = contentString.toString();
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
@Override
public Object asNMSPacket() {
try {
return chatClassConstructor.newInstance(toIChatBaseComponent(this.message));
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public String getMessage() {
return this.message;
}
}
@@ -11,6 +11,58 @@ import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public final class WrappedPacketOutEntityVelocity extends WrappedPacket implements Sendable {
private static Constructor<?> velocityConstructor, vec3dConstructor;
private static Class<?> velocityClass, vec3dClass;
private static final Field[] fields = new Field[4];
/**
* Velocity Constructor parameter types:
* 1.7.10->1.13.2 use int, double, double, double style,
* 1.14+ use int, Vec3D style
*/
static {
try {
velocityClass = NMSUtils.getNMSClass("PacketPlayOutEntityVelocity");
if (version.isHigherThan(ServerVersion.v_1_13_2)) {
vec3dClass = NMSUtils.getNMSClass("Vec3D");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
if (version.isHigherThan(ServerVersion.v_1_13_2)) {
velocityConstructor = velocityClass.getConstructor(int.class, vec3dClass);
//vec3d constructor
vec3dConstructor = vec3dClass.getConstructor(double.class, double.class, double.class);
} else {
velocityConstructor = velocityClass.getConstructor(int.class, double.class, double.class, double.class);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
//entity id
fields[0] = velocityClass.getDeclaredField("a");
//x
fields[1] = velocityClass.getDeclaredField("b");
//y
fields[2] = velocityClass.getDeclaredField("c");
//z
fields[3] = velocityClass.getDeclaredField("d");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
for (final Field f : fields) {
f.setAccessible(true);
}
}
private Entity entity;
private int entityId;
private double velocityX, velocityY, velocityZ;
@@ -87,59 +139,4 @@ public final class WrappedPacketOutEntityVelocity extends WrappedPacket implemen
return null;
}
private static Constructor<?> velocityConstructor, vec3dConstructor;
private static Class<?> velocityClass, vec3dClass;
private static Field[] fields = new Field[4];
/**
* Velocity Constructor parameter types:
* 1.7.10->1.13.2 use int, double, double, double style,
* 1.14+ use int, Vec3D style
*/
static {
try {
velocityClass = NMSUtils.getNMSClass("PacketPlayOutEntityVelocity");
if (version.isHigherThan(ServerVersion.v_1_13_2)) {
vec3dClass = NMSUtils.getNMSClass("Vec3D");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
if (version.isHigherThan(ServerVersion.v_1_13_2)) {
velocityConstructor = velocityClass.getConstructor(int.class, vec3dClass);
//vec3d constructor
vec3dConstructor = vec3dClass.getConstructor(double.class, double.class, double.class);
} else {
velocityConstructor = velocityClass.getConstructor(int.class, double.class, double.class, double.class);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
//entity id
fields[0] = velocityClass.getDeclaredField("a");
//x
fields[1] = velocityClass.getDeclaredField("b");
//y
fields[2] = velocityClass.getDeclaredField("c");
//z
fields[3] = velocityClass.getDeclaredField("d");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
for (final Field f : fields) {
f.setAccessible(true);
}
}
}
@@ -10,6 +10,26 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public final class WrappedPacketOutKickDisconnect extends WrappedPacket implements Sendable {
private static final Reflection.FieldAccessor<?> iChatBaseComponentAccessor;
private static Class<?> packetClass, iChatBaseComponentClass;
private static Constructor<?> kickDisconnectConstructor;
static {
try {
packetClass = NMSUtils.getNMSClass("PacketPlayOutKickDisconnect");
iChatBaseComponentClass = NMSUtils.getNMSClass("IChatBaseComponent");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
kickDisconnectConstructor = packetClass.getConstructor(iChatBaseComponentClass);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
iChatBaseComponentAccessor = Reflection.getField(packetClass, iChatBaseComponentClass, 0);
}
private String kickMessage;
public WrappedPacketOutKickDisconnect(final Object packet) {
@@ -39,26 +59,4 @@ public final class WrappedPacketOutKickDisconnect extends WrappedPacket implemen
}
return null;
}
private static Class<?> packetClass, iChatBaseComponentClass;
private static Constructor<?> kickDisconnectConstructor;
private static final Reflection.FieldAccessor<?> iChatBaseComponentAccessor;
static {
try {
packetClass = NMSUtils.getNMSClass("PacketPlayOutKickDisconnect");
iChatBaseComponentClass = NMSUtils.getNMSClass("IChatBaseComponent");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
kickDisconnectConstructor = packetClass.getConstructor(iChatBaseComponentClass);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
iChatBaseComponentAccessor = Reflection.getField(packetClass, iChatBaseComponentClass, 0);
}
}
@@ -15,72 +15,12 @@ import java.util.regex.Pattern;
* @author Kristian
*/
public final class Reflection {
/**
* An interface for invoking a specific constructor.
*/
public interface ConstructorInvoker {
/**
* Invoke a constructor for a specific class.
*
* @param arguments - the arguments to pass to the constructor.
* @return The constructed object.
*/
Object invoke(Object... arguments);
}
/**
* An interface for invoking a specific method.
*/
public interface MethodInvoker {
/**
* Invoke a method on a specific target object.
*
* @param target - the target object, or NULL for a static method.
* @param arguments - the arguments to pass to the method.
* @return The return value, or NULL if is void.
*/
Object invoke(Object target, Object... arguments);
}
/**
* An interface for retrieving the field content.
*
* @param <T> - field type.
*/
public interface FieldAccessor<T> {
/**
* Retrieve the content of a field.
*
* @param target - the target object, or NULL for a static field.
* @return The value of the field.
*/
T get(Object target);
/**
* Set the content of a field.
*
* @param target - the target object, or NULL for a static field.
* @param value - the new value of the field.
*/
void set(Object target, Object value);
/**
* Determine if the given object has this field.
*
* @param target - the object to test.
* @return TRUE if it does, FALSE otherwise.
*/
boolean hasField(Object target);
}
// Deduce the net.minecraft.server.v* package
private static String OBC_PREFIX = Bukkit.getServer().getClass().getPackage().getName();
private static String NMS_PREFIX = OBC_PREFIX.replace("org.bukkit.craftbukkit", "net.minecraft.server");
private static String VERSION = OBC_PREFIX.replace("org.bukkit.craftbukkit", "").replace(".", "");
private static final String OBC_PREFIX = Bukkit.getServer().getClass().getPackage().getName();
private static final String NMS_PREFIX = OBC_PREFIX.replace("org.bukkit.craftbukkit", "net.minecraft.server");
private static final String VERSION = OBC_PREFIX.replace("org.bukkit.craftbukkit", "").replace(".", "");
// Variable replacement
private static Pattern MATCH_VARIABLE = Pattern.compile("\\{([^\\}]+)\\}");
private static final Pattern MATCH_VARIABLE = Pattern.compile("\\{([^\\}]+)\\}");
private Reflection() {
// Seal class
}
@@ -88,8 +28,8 @@ public final class Reflection {
/**
* Retrieve a field accessor for a specific field type and name.
*
* @param target - the target type.
* @param name - the name of the field, or NULL to ignore.
* @param target - the target type.
* @param name - the name of the field, or NULL to ignore.
* @param fieldType - a compatible field type.
* @return The field accessor.
*/
@@ -101,7 +41,7 @@ public final class Reflection {
* Retrieve a field accessor for a specific field type and name.
*
* @param className - lookup name of the class, see {@link #getClass(String)}.
* @param name - the name of the field, or NULL to ignore.
* @param name - the name of the field, or NULL to ignore.
* @param fieldType - a compatible field type.
* @return The field accessor.
*/
@@ -112,9 +52,9 @@ public final class Reflection {
/**
* Retrieve a field accessor for a specific field type and name.
*
* @param target - the target type.
* @param target - the target type.
* @param fieldType - a compatible field type.
* @param index - the number of compatible fields to skip.
* @param index - the number of compatible fields to skip.
* @return The field accessor.
*/
public static <T> FieldAccessor<T> getField(Class<?> target, Class<T> fieldType, int index) {
@@ -126,7 +66,7 @@ public final class Reflection {
*
* @param className - lookup name of the class, see {@link #getClass(String)}.
* @param fieldType - a compatible field type.
* @param index - the number of compatible fields to skip.
* @param index - the number of compatible fields to skip.
* @return The field accessor.
*/
public static <T> FieldAccessor<T> getField(String className, Class<T> fieldType, int index) {
@@ -180,9 +120,9 @@ public final class Reflection {
/**
* Search for the first publicly and privately defined method of the given name and parameter count.
*
* @param className - lookup name of the class, see {@link #getClass(String)}.
* @param className - lookup name of the class, see {@link #getClass(String)}.
* @param methodName - the method name, or NULL to skip.
* @param params - the expected parameters.
* @param params - the expected parameters.
* @return An object that invokes this specific method.
* @throws IllegalStateException If we cannot find this method.
*/
@@ -193,9 +133,9 @@ public final class Reflection {
/**
* Search for the first publicly and privately defined method of the given name and parameter count.
*
* @param clazz - a class to start with.
* @param clazz - a class to start with.
* @param methodName - the method name, or NULL to skip.
* @param params - the expected parameters.
* @param params - the expected parameters.
* @return An object that invokes this specific method.
* @throws IllegalStateException If we cannot find this method.
*/
@@ -206,10 +146,10 @@ public final class Reflection {
/**
* Search for the first publicly and privately defined method of the given name and parameter count.
*
* @param clazz - a class to start with.
* @param clazz - a class to start with.
* @param methodName - the method name, or NULL to skip.
* @param returnType - the expected return type, or NULL to ignore.
* @param params - the expected parameters.
* @param params - the expected parameters.
* @return An object that invokes this specific method.
* @throws IllegalStateException If we cannot find this method.
*/
@@ -246,7 +186,7 @@ public final class Reflection {
* Search for the first publically and privately defined constructor of the given name and parameter count.
*
* @param className - lookup name of the class, see {@link #getClass(String)}.
* @param params - the expected parameters.
* @param params - the expected parameters.
* @return An object that invokes this constructor.
* @throws IllegalStateException If we cannot find this method.
*/
@@ -257,7 +197,7 @@ public final class Reflection {
/**
* Search for the first publically and privately defined constructor of the given name and parameter count.
*
* @param clazz - a class to start with.
* @param clazz - a class to start with.
* @param params - the expected parameters.
* @return An object that invokes this constructor.
* @throws IllegalStateException If we cannot find this method.
@@ -291,12 +231,12 @@ public final class Reflection {
* This is useful when looking up fields by a NMS or OBC type.
* <p>
*
* @see {@link #getClass()} for more information.
* @param lookupName - the class name with variables.
* @return The class.
* @see {@link #getClass()} for more information.
*/
public static Class<Object> getUntypedClass(String lookupName) {
@SuppressWarnings({ "rawtypes", "unchecked" })
@SuppressWarnings({"rawtypes", "unchecked"})
Class<Object> clazz = (Class) getClass(lookupName);
return clazz;
}
@@ -400,4 +340,62 @@ public final class Reflection {
matcher.appendTail(output);
return output.toString();
}
/**
* An interface for invoking a specific constructor.
*/
public interface ConstructorInvoker {
/**
* Invoke a constructor for a specific class.
*
* @param arguments - the arguments to pass to the constructor.
* @return The constructed object.
*/
Object invoke(Object... arguments);
}
/**
* An interface for invoking a specific method.
*/
public interface MethodInvoker {
/**
* Invoke a method on a specific target object.
*
* @param target - the target object, or NULL for a static method.
* @param arguments - the arguments to pass to the method.
* @return The return value, or NULL if is void.
*/
Object invoke(Object target, Object... arguments);
}
/**
* An interface for retrieving the field content.
*
* @param <T> - field type.
*/
public interface FieldAccessor<T> {
/**
* Retrieve the content of a field.
*
* @param target - the target object, or NULL for a static field.
* @return The value of the field.
*/
T get(Object target);
/**
* Set the content of a field.
*
* @param target - the target object, or NULL for a static field.
* @param value - the new value of the field.
*/
void set(Object target, Object value);
/**
* Determine if the given object has this field.
*
* @param target - the object to test.
* @return TRUE if it does, FALSE otherwise.
*/
boolean hasField(Object target);
}
}
@@ -76,25 +76,20 @@ public abstract class TinyProtocol7 {
// Speedup channel/protocol lookup
private final Map<String, Channel> channelLookup = new MapMaker().weakValues().makeMap();
private Listener listener;
// Channels that have already been removed
private final Set<Channel> uninjectedChannels = Collections.newSetFromMap(new MapMaker().weakKeys().<Channel, Boolean>makeMap());
private final Set<Channel> uninjectedChannels = Collections.newSetFromMap(new MapMaker().weakKeys().makeMap());
protected volatile boolean closed;
protected Plugin plugin;
private Listener listener;
// List of network markers
private List<Object> networkManagers;
// Injected channel handlers
private List<Channel> serverChannels = Lists.newArrayList();
private final List<Channel> serverChannels = Lists.newArrayList();
private ChannelInboundHandlerAdapter serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
// Current handler name
private String handlerName;
protected volatile boolean closed;
protected Plugin plugin;
private final String handlerName;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
@@ -348,6 +343,7 @@ public abstract class TinyProtocol7 {
/**
* Changed from "tiny-" to "packetevents"
*
* @return handlerName
*/
protected String getHandlerName() {
@@ -74,25 +74,20 @@ public abstract class TinyProtocol8 {
// Speedup channel/protocol lookup
private final Map<String, Channel> channelLookup = new MapMaker().weakValues().makeMap();
private Listener listener;
// Channels that have already been removed
private final Set<Channel> uninjectedChannels = Collections.newSetFromMap(new MapMaker().weakKeys().<Channel, Boolean>makeMap());
// List of network markers
private List<Object> networkManagers;
private final Set<Channel> uninjectedChannels = Collections.newSetFromMap(new MapMaker().weakKeys().makeMap());
// Injected channel handlers
private final List<Channel> serverChannels = Lists.newArrayList();
protected volatile boolean closed;
protected Plugin plugin;
private Listener listener;
// List of network markers
private List<Object> networkManagers;
private ChannelInboundHandlerAdapter serverChannelHandler;
private ChannelInitializer<Channel> beginInitProtocol;
private ChannelInitializer<Channel> endInitProtocol;
// Current handler name
private String handlerName;
protected volatile boolean closed;
protected Plugin plugin;
private final String handlerName;
/**
* Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
@@ -13,58 +13,12 @@ import java.lang.reflect.Method;
public final class EntityFinderUtils {
@Nullable
private static ServerVersion version = PacketEvents.getServerVersion();
public static Entity getEntityById(final int id) {
for (final World world : Bukkit.getWorlds()) {
final Entity entity = getEntityByIdWithWorld(world, id);
if (entity != null) {
return entity;
}
}
return null;
}
@Nullable
public static Entity getEntityByIdWithWorld(final World world, final int id) {
if(world == null) {
return null;
}
Object craftWorld = craftWorldClass.cast(world);
Object worldServer = null;
try {
worldServer = craftWorldGetHandle.invoke(craftWorld);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
Object nmsEntity = null;
try {
nmsEntity = getEntityByIdMethod.invoke(worldServer, id);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
if(nmsEntity == null) {
return null;
}
try {
return (Entity) getBukkitEntity.invoke(nmsEntity);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
private static final ServerVersion version = PacketEvents.getServerVersion();
private static Class<?> worldServerClass;
private static Class<?> craftWorldClass;
private static Class<?> entityClass;
private static Method getEntityByIdMethod;
private static Method craftWorldGetHandle;
private static Method getBukkitEntity;
static {
@@ -85,6 +39,47 @@ public final class EntityFinderUtils {
}
}
public static Entity getEntityById(final int id) {
for (final World world : Bukkit.getWorlds()) {
final Entity entity = getEntityByIdWithWorld(world, id);
if (entity != null) {
return entity;
}
}
return null;
}
@Nullable
public static Entity getEntityByIdWithWorld(final World world, final int id) {
if (world == null) {
return null;
}
Object craftWorld = craftWorldClass.cast(world);
Object worldServer = null;
try {
worldServer = craftWorldGetHandle.invoke(craftWorld);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
Object nmsEntity = null;
try {
nmsEntity = getEntityByIdMethod.invoke(worldServer, id);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
if (nmsEntity == null) {
return null;
}
try {
return (Entity) getBukkitEntity.invoke(nmsEntity);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public static String getEntityByNameMethodName() {
if (version.isHigherThan(ServerVersion.v_1_7_10) && version.isLowerThan(ServerVersion.v_1_9)) {
return "a";