diff --git a/src/main/java/net/h31ix/anticheat/Anticheat.java b/src/main/java/net/h31ix/anticheat/Anticheat.java index 8f5015c..5c3e765 100644 --- a/src/main/java/net/h31ix/anticheat/Anticheat.java +++ b/src/main/java/net/h31ix/anticheat/Anticheat.java @@ -43,272 +43,216 @@ import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; -public class Anticheat extends JavaPlugin -{ - private static AnticheatManager manager; - private static List eventList = new ArrayList(); - private static boolean update = false; - private static Configuration config; - private static boolean verbose; - private static Metrics metrics; - private static final long XRAY_TIME = 1200; - public static final String SPY_METADATA = "ac-spydata"; - - @Override - public void onEnable() - { - manager = new AnticheatManager(this, getLogger()); - eventList.add(new PlayerListener()); - eventList.add(new BlockListener()); - eventList.add(new EntityListener()); - eventList.add(new VehicleListener()); - eventList.add(new InventoryListener()); - // Order is important in some cases, don't screw with these unless needed, especially config - setupConfig(); - // Xray must come before events - setupXray(); - setupEvents(); - setupCommands(); - setupUpdater(); - setupMetrics(); - restoreLevels(); - // Test for compatibility for 1.4.5-R1.0 - try - { - Material.AIR.isSolid(); - } - catch(NoSuchMethodError error) - { - getLogger().severe("You are using an outdated version of CraftBukkit that does not contain the API required for AntiCheat to run properly."); - getLogger().severe("Please update to CraftBukkit 1.4.5-R1.0 or higher by visiting dl.bukkit.org and hitting the green download button."); - getLogger().severe("AntiCheat will now be disabled, and will not protect your server until it is updated."); - getPluginLoader().disablePlugin(this); - return; - } - // End test - if (verbose) - { - getLogger().log(Level.INFO, "Finished loading."); - } - } - - @Override - public void onDisable() - { - AnticheatManager.close(); - for(User user : manager.getUserManager().getUsers()) - { - config.saveLevel(user.getName(), user.getLevel()); - } - config.saveLevels(); - getServer().getScheduler().cancelAllTasks(); - cleanup(); - } - - private void save(InputStream in, File file) - { - if (!file.exists()) - { - file.getParentFile().mkdirs(); - try - { - OutputStream out = new FileOutputStream(file); - byte[] buf = new byte[1024]; - int len; - while((len=in.read(buf))>0) - { - out.write(buf,0,len); - } - out.close(); - in.close(); - } - catch (Exception e) - { - getLogger().severe("Unable to save files. Is the directory writeable?"); - } - if (verbose) - { - getLogger().log(Level.INFO, file.getName()+" created."); - } - } - } - - private void setupXray() - { - final XRayTracker xtracker = manager.getXRayTracker(); - if (config.logXRay()) - { - eventList.add(new XRayListener()); - if (config.alertXRay()) - { - getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Runnable() - { - @Override - public void run() - { - for (Player player : getServer().getOnlinePlayers()) - { - String name = player.getName(); - if (!xtracker.hasAlerted(name) && xtracker.sufficientData(name) && xtracker.hasAbnormal(name)) - { - List alert = new ArrayList(); - alert.add(ChatColor.YELLOW + "[ALERT] " + ChatColor.WHITE + name + ChatColor.YELLOW + " might be using xray."); - alert.add(ChatColor.YELLOW + "[ALERT] Please check their xray stats using " + ChatColor.WHITE + "/anticheat xray " + name + ChatColor.YELLOW + "."); - Utilities.alert(alert); - xtracker.logAlert(name); - } - } - } - }, XRAY_TIME, XRAY_TIME); - if (verbose) - { - getLogger().log(Level.INFO, "Scheduled the XRay checker."); - } - } - } - } - - private void setupEvents() - { - for (Listener listener : eventList) - { - getServer().getPluginManager().registerEvents(listener, this); - if (verbose) - { - getLogger().log(Level.INFO, "Registered events for ".concat(listener.toString().split("@")[0].split(".anticheat.")[1])); - } - } - } - - private void setupCommands() - { - getCommand("anticheat").setExecutor(new CommandHandler()); - if (verbose) - { - getLogger().log(Level.INFO, "Registered commands."); - } - } - - private void setupUpdater() - { - if (config.autoUpdate()) - { - if (verbose) - { - getLogger().log(Level.INFO, "Checking for a new update..."); - } - Updater updater = new Updater(this, "anticheat", this.getFile(), Updater.UpdateType.DEFAULT, false); - update = updater.getResult() != Updater.UpdateResult.NO_UPDATE; - if (verbose) - { - getLogger().log(Level.INFO, "Update avaliable: "+update); - } - } - } - - private void setupMetrics() - { - try - { - metrics = new Metrics(this); - final EventListener listener = new EventListener(); - Graph hacksGraph = metrics.createGraph("Hacks blocked"); - for (final CheckType type : CheckType.values()) - { - hacksGraph.addPlotter(new Metrics.Plotter(CheckType.getName(type)) - { - @Override - public int getValue() - { - return EventListener.getCheats(type); - } - }); - listener.resetCheck(type); - } - Graph apiGraph = metrics.createGraph("API Usage"); - apiGraph.addPlotter(new Metrics.Plotter("Checks disabled") - { - @Override - public int getValue() - { - return manager.getCheckManager().getDisabled(); - } - }); - apiGraph.addPlotter(new Metrics.Plotter("Players exempted") - { - @Override - public int getValue() - { - return manager.getCheckManager().getExempt(); - } - }); - metrics.start(); - if (verbose) - { - getLogger().log(Level.INFO, "Metrics started."); - } - } - catch (IOException ex) - { - } - } - - private void setupConfig() - { - config = manager.getConfiguration(); - checkConfigs(); - verbose = config.verboseStartup(); - if (verbose) - { - getLogger().log(Level.INFO, "Setup the config."); - } - } - - private void restoreLevels() - { - for (Player player : getServer().getOnlinePlayers()) - { - String name = player.getName(); - manager.getUserManager().addUser(new User(player.getName(), config.getLevel(name))); - if (verbose) - { - getLogger().log(Level.INFO, "Data for " + player.getName() + " re-applied from flatfile"); - } - } - } - - public void checkConfigs() - { - save(getResource("config.yml"), new File(getDataFolder() + "/config.yml")); - save(getResource("lang.yml"), new File(getDataFolder() + "/lang.yml")); - save(getResource("magic.yml"), new File(getDataFolder() + "/magic.yml")); - } - - public static Anticheat getPlugin() - { - return manager.getPlugin(); - } - - public static AnticheatManager getManager() - { - return manager; - } - - public static boolean isUpdated() - { - return !update; - } - - public static String getVersion() - { - return manager.getPlugin().getDescription().getVersion(); - } - - private void cleanup() - { - eventList = null; - manager = null; - config = null; - metrics = null; - } +public class Anticheat extends JavaPlugin { + private static AnticheatManager manager; + private static List eventList = new ArrayList(); + private static boolean update = false; + private static Configuration config; + private static boolean verbose; + private static Metrics metrics; + private static final long XRAY_TIME = 1200; + public static final String SPY_METADATA = "ac-spydata"; + + @Override + public void onEnable() { + manager = new AnticheatManager(this, getLogger()); + eventList.add(new PlayerListener()); + eventList.add(new BlockListener()); + eventList.add(new EntityListener()); + eventList.add(new VehicleListener()); + eventList.add(new InventoryListener()); + // Order is important in some cases, don't screw with these unless needed, especially config + setupConfig(); + // Xray must come before events + setupXray(); + setupEvents(); + setupCommands(); + setupUpdater(); + setupMetrics(); + restoreLevels(); + // Test for compatibility for 1.4.5-R1.0 + try { + Material.AIR.isSolid(); + } catch (NoSuchMethodError error) { + getLogger().severe("You are using an outdated version of CraftBukkit that does not contain the API required for AntiCheat to run properly."); + getLogger().severe("Please update to CraftBukkit 1.4.5-R1.0 or higher by visiting dl.bukkit.org and hitting the green download button."); + getLogger().severe("AntiCheat will now be disabled, and will not protect your server until it is updated."); + getPluginLoader().disablePlugin(this); + return; + } + // End test + if (verbose) { + getLogger().log(Level.INFO, "Finished loading."); + } + } + + @Override + public void onDisable() { + AnticheatManager.close(); + for (User user : manager.getUserManager().getUsers()) { + config.saveLevel(user.getName(), user.getLevel()); + } + config.saveLevels(); + getServer().getScheduler().cancelAllTasks(); + cleanup(); + } + + private void save(InputStream in, File file) { + if (!file.exists()) { + file.getParentFile().mkdirs(); + try { + OutputStream out = new FileOutputStream(file); + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + out.close(); + in.close(); + } catch (Exception e) { + getLogger().severe("Unable to save files. Is the directory writeable?"); + } + if (verbose) { + getLogger().log(Level.INFO, file.getName() + " created."); + } + } + } + + private void setupXray() { + final XRayTracker xtracker = manager.getXRayTracker(); + if (config.logXRay()) { + eventList.add(new XRayListener()); + if (config.alertXRay()) { + getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Runnable() { + @Override + public void run() { + for (Player player : getServer().getOnlinePlayers()) { + String name = player.getName(); + if (!xtracker.hasAlerted(name) && xtracker.sufficientData(name) && xtracker.hasAbnormal(name)) { + List alert = new ArrayList(); + alert.add(ChatColor.YELLOW + "[ALERT] " + ChatColor.WHITE + name + ChatColor.YELLOW + " might be using xray."); + alert.add(ChatColor.YELLOW + "[ALERT] Please check their xray stats using " + ChatColor.WHITE + "/anticheat xray " + name + ChatColor.YELLOW + "."); + Utilities.alert(alert); + xtracker.logAlert(name); + } + } + } + }, XRAY_TIME, XRAY_TIME); + if (verbose) { + getLogger().log(Level.INFO, "Scheduled the XRay checker."); + } + } + } + } + + private void setupEvents() { + for (Listener listener : eventList) { + getServer().getPluginManager().registerEvents(listener, this); + if (verbose) { + getLogger().log(Level.INFO, "Registered events for ".concat(listener.toString().split("@")[0].split(".anticheat.")[1])); + } + } + } + + private void setupCommands() { + getCommand("anticheat").setExecutor(new CommandHandler()); + if (verbose) { + getLogger().log(Level.INFO, "Registered commands."); + } + } + + private void setupUpdater() { + if (config.autoUpdate()) { + if (verbose) { + getLogger().log(Level.INFO, "Checking for a new update..."); + } + Updater updater = new Updater(this, "anticheat", this.getFile(), Updater.UpdateType.DEFAULT, false); + update = updater.getResult() != Updater.UpdateResult.NO_UPDATE; + if (verbose) { + getLogger().log(Level.INFO, "Update avaliable: " + update); + } + } + } + + private void setupMetrics() { + try { + metrics = new Metrics(this); + final EventListener listener = new EventListener(); + Graph hacksGraph = metrics.createGraph("Hacks blocked"); + for (final CheckType type : CheckType.values()) { + hacksGraph.addPlotter(new Metrics.Plotter(CheckType.getName(type)) { + @Override + public int getValue() { + return EventListener.getCheats(type); + } + }); + listener.resetCheck(type); + } + Graph apiGraph = metrics.createGraph("API Usage"); + apiGraph.addPlotter(new Metrics.Plotter("Checks disabled") { + @Override + public int getValue() { + return manager.getCheckManager().getDisabled(); + } + }); + apiGraph.addPlotter(new Metrics.Plotter("Players exempted") { + @Override + public int getValue() { + return manager.getCheckManager().getExempt(); + } + }); + metrics.start(); + if (verbose) { + getLogger().log(Level.INFO, "Metrics started."); + } + } catch (IOException ex) {} + } + + private void setupConfig() { + config = manager.getConfiguration(); + checkConfigs(); + verbose = config.verboseStartup(); + if (verbose) { + getLogger().log(Level.INFO, "Setup the config."); + } + } + + private void restoreLevels() { + for (Player player : getServer().getOnlinePlayers()) { + String name = player.getName(); + manager.getUserManager().addUser(new User(player.getName(), config.getLevel(name))); + if (verbose) { + getLogger().log(Level.INFO, "Data for " + player.getName() + " re-applied from flatfile"); + } + } + } + + public void checkConfigs() { + save(getResource("config.yml"), new File(getDataFolder() + "/config.yml")); + save(getResource("lang.yml"), new File(getDataFolder() + "/lang.yml")); + save(getResource("magic.yml"), new File(getDataFolder() + "/magic.yml")); + } + + public static Anticheat getPlugin() { + return manager.getPlugin(); + } + + public static AnticheatManager getManager() { + return manager; + } + + public static boolean isUpdated() { + return !update; + } + + public static String getVersion() { + return manager.getPlugin().getDescription().getVersion(); + } + + private void cleanup() { + eventList = null; + manager = null; + config = null; + metrics = null; + } } diff --git a/src/main/java/net/h31ix/anticheat/CommandHandler.java b/src/main/java/net/h31ix/anticheat/CommandHandler.java index 5876509..c107cf9 100644 --- a/src/main/java/net/h31ix/anticheat/CommandHandler.java +++ b/src/main/java/net/h31ix/anticheat/CommandHandler.java @@ -35,642 +35,437 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.metadata.FixedMetadataValue; -public class CommandHandler implements CommandExecutor -{ - private static final Configuration CONFIG = Anticheat.getManager().getConfiguration(); - private static final UserManager USER_MANAGER = Anticheat.getManager().getUserManager(); - private static final XRayTracker XRAY_TRACKER = Anticheat.getManager().getXRayTracker(); - private static final ChatColor RED = ChatColor.RED; - private static final ChatColor YELLOW = ChatColor.YELLOW; - private static final ChatColor GREEN = ChatColor.GREEN; - private static final ChatColor WHITE = ChatColor.WHITE; - private static final ChatColor GRAY = ChatColor.GRAY; - private List high = new ArrayList(); - private List med = new ArrayList(); - private List low = new ArrayList(); - private static final Server SERVER = Bukkit.getServer(); - private static final int MED_THRESHOLD = 20; - private static final int HIGH_THRESHOLD = 50; - private static final String PERMISSIONS_ERROR = RED + "Insufficient Permissions."; - private static final String MENU_END = "-----------------------------------------------------"; - - public void handleLog(CommandSender cs, String[] args) - { - if (Permission.SYSTEM_LOG.get(cs)) - { - if (args[1].equalsIgnoreCase("enable")) - { - if (!CONFIG.logConsole()) - { - CONFIG.setLog(true); - cs.sendMessage(GREEN + "Console logging enabled."); - } - else - { - cs.sendMessage(GREEN + "Console logging is already enabled!"); - } - } - else if (args[1].equalsIgnoreCase("disable")) - { - if (CONFIG.logConsole()) - { - CONFIG.setLog(false); - cs.sendMessage(GREEN + "Console logging disabled."); - } - else - { - cs.sendMessage(GREEN + "Console logging is already disabled!"); - } - } - else - { - cs.sendMessage(RED + "Usage: /anticheat log [enable/disable]"); - } - } - else - { - cs.sendMessage(PERMISSIONS_ERROR); - } - } - - public void handleDebug(CommandSender cs) - { - if (Permission.SYSTEM_REPORT.get(cs)) - { - PastebinReport report = new PastebinReport(cs); - cs.sendMessage(GREEN + "Debug information posted to: " + WHITE + report.getURL()); - cs.sendMessage(GREEN + "Please include this link when making bug reports."); - } - else - { - cs.sendMessage(PERMISSIONS_ERROR); - } - } - - public void handleXRay(CommandSender cs, String[] args) - { - if (Permission.SYSTEM_XRAY.get(cs)) - { - if (CONFIG.logXRay()) - { - List list = SERVER.matchPlayer(args[1]); - if (list.size() == 1) - { - Player player = list.get(0); - if (XRAY_TRACKER.sufficientData(player.getName())) - { - XRAY_TRACKER.sendStats(cs, player.getName()); - } - else - { - cs.sendMessage(RED + "Insufficient data collected from " + WHITE + args[1] + RED + "."); - cs.sendMessage(RED + "Please wait until more info is collected before predictions are calculated."); - } - } - else if (list.size() > 1) - { - cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + "."); - } - else if (XRAY_TRACKER.sufficientData(args[1])) - { - XRAY_TRACKER.sendStats(cs, args[1]); - } - else - { - cs.sendMessage(RED + "Insufficient data collected from " + WHITE + args[1] + RED + "."); - cs.sendMessage(RED + "Please wait until more info is collected before predictions are calculated."); - } - } - else - { - cs.sendMessage(RED + "XRay logging is off in the config."); - } - } - else - { - cs.sendMessage(PERMISSIONS_ERROR); - } - } - - public void handleReset(CommandSender cs, String[] args) - { - if (Permission.SYSTEM_RESET.get(cs)) - { - List list = SERVER.matchPlayer(args[1]); - if (list.size() == 1) - { - Player player = list.get(0); - if (USER_MANAGER.safeGetLevel(player.getName()) == 0) - { - cs.sendMessage(player.getName() + RED + " is already in Low Level!"); - } - else - { - USER_MANAGER.safeReset(player.getName()); - cs.sendMessage(player.getName() + GREEN + " has been reset to Low Level."); - } - XRAY_TRACKER.reset(player.getName()); - cs.sendMessage(player.getName() + GREEN + "'s XRay stats have been reset."); - } - else if (list.size() > 1) - { - cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + "."); - } - else - { - cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found."); - } - } - else - { - cs.sendMessage(PERMISSIONS_ERROR); - } - } - - public void handleSpy(CommandSender cs, String[] args) - { - if (cs instanceof Player) - { - if (Permission.SYSTEM_SPY.get(cs)) - { - Player sender = (Player) cs; - if (!args[1].equalsIgnoreCase("off")) - { - List list = SERVER.matchPlayer(args[1]); - if (list.size() == 1) - { - Player player = list.get(0); - for (Player p : cs.getServer().getOnlinePlayers()) - { - if (!Permission.SYSTEM_SPY.get(p)) - { - p.hidePlayer(sender); - } - } - if(!sender.hasMetadata(Anticheat.SPY_METADATA)) // Maintain ORIGINAL location and other data - { - SpyState state = new SpyState(sender.getAllowFlight(), sender.isFlying(), sender.getLocation()); - sender.setMetadata(Anticheat.SPY_METADATA, new FixedMetadataValue(Anticheat.getPlugin(), state)); - } - sender.setAllowFlight(true); - sender.setFlying(true); - sender.teleport(player); - sender.sendMessage(GREEN + "You have been teleported to " + player.getName() + " and made invisible."); - sender.sendMessage(GREEN + "To stop spying, type " + WHITE + " /AntiCheat spy off"); - } - else if (list.size() > 1) - { - cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + "."); - } - else - { - cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found."); - } - } - else - { - if (sender.hasMetadata(Anticheat.SPY_METADATA)) - { - SpyState state = ((SpyState) sender.getMetadata(Anticheat.SPY_METADATA).get(0).value()); - sender.setAllowFlight(state.getAllowFlight()); - sender.setFlying(state.getFlying()); - sender.teleport(state.getLocation()); - sender.removeMetadata(Anticheat.SPY_METADATA, Anticheat.getPlugin()); - for (Player p : cs.getServer().getOnlinePlayers()) - { - p.showPlayer(sender); - } - sender.sendMessage(GREEN + "Done spying! Brought you back to where you started!"); - } - else - { - sender.sendMessage(RED + "You were not spying."); - } - } - } - else - { - cs.sendMessage(PERMISSIONS_ERROR); - } - } - else - { - cs.sendMessage(RED + "Sorry, but you can't spy on a player from the console."); - } - } - - public void handleHelp(CommandSender cs) - { - if (Permission.SYSTEM_HELP.get(cs)) - { - String base = "/AntiCheat "; - cs.sendMessage("----------------------[" + GREEN + "AntiCheat" + WHITE + "]----------------------"); - cs.sendMessage(base + GREEN + "log [Enable/Disable]" + WHITE + " - toggle logging"); - cs.sendMessage(base + GREEN + "report [low/medium/high]" + WHITE + " - show users in groups"); - cs.sendMessage(base + GREEN + "report [user]" + WHITE + " - get a player's cheat report"); - cs.sendMessage(base + GREEN + "reload" + WHITE + " - reload AntiCheat configuration"); - cs.sendMessage(base + GREEN + "reset [user]" + WHITE + " - reset user's hack level"); - cs.sendMessage(base + GREEN + "xray [user]" + WHITE + " - check user's xray levels"); - cs.sendMessage(base + GREEN + "spy [user]" + WHITE + " - spy on a user in secret"); - cs.sendMessage(base + GREEN + "help" + WHITE + " - access this page"); - cs.sendMessage(base + GREEN + "debug" + WHITE + " - post debug information"); - cs.sendMessage(base + GREEN + "update" + WHITE + " - check update status"); - cs.sendMessage(MENU_END); - } - else - { - cs.sendMessage(PERMISSIONS_ERROR); - } - } - - public void handleUpdate(CommandSender cs) - { - if (Permission.SYSTEM_UPDATE.get(cs)) - { - cs.sendMessage("Running " + GREEN + "AntiCheat " + WHITE + "v" + GREEN + Anticheat.getVersion()); - cs.sendMessage(MENU_END); - if (!Anticheat.isUpdated()) - { - cs.sendMessage(GRAY + "There " + GREEN + "IS" + GRAY + " a newer version avaliable."); - if (CONFIG.autoUpdate()) - { - cs.sendMessage(GRAY + "It will be installed automatically for you on next launch."); - } - else - { - cs.sendMessage(GRAY + "Due to your config settings, we " + RED + "can not" + GRAY + " auto update."); - cs.sendMessage(GRAY + "Please visit http://dev.bukkit.org/server-mods/anticheat/"); - } - } - else - { - cs.sendMessage(GRAY + "AntiCheat is " + GREEN + "UP TO DATE!"); - } - } - else - { - cs.sendMessage(PERMISSIONS_ERROR); - } - } - - public void handleCalibrate(CommandSender cs) - { - if(cs instanceof Player) - { - if (Permission.SYSTEM_CALIBRATE.get(cs)) - { - Calibrator c = new Calibrator((Player)cs); - SERVER.getPluginManager().registerEvents(c, Anticheat.getPlugin()); - c.calibrate(); - } - else - { - cs.sendMessage(PERMISSIONS_ERROR); - } - } - else - { - cs.sendMessage(RED + "Sorry, but you cannot calibrate from console."); - } - } - - public void handleReport(CommandSender cs, String[] args) - { - if (Permission.SYSTEM_REPORT.get(cs)) - { - getPlayers(); - if(args.length > 1) - { - String group = args[1]; - if(group.equalsIgnoreCase("low")) - { - int num = getReportPageNum(args); - if (num > 0) - { - sendReport(cs, low, "Low", GREEN, num); - } - else - { - cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); - } - } - else if(group.equalsIgnoreCase("medium")) - { - int num = getReportPageNum(args); - if (num > 0) - { - sendReport(cs, med, "Medium", YELLOW, num); - } - else - { - cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); - } - } - if(group.equalsIgnoreCase("high")) - { - int num = getReportPageNum(args); - if (num > 0) - { - sendReport(cs, high, "High", RED, num); - } - else - { - cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); - } - } - } - } - else - { - cs.sendMessage(PERMISSIONS_ERROR); - } - } - - public int getReportPageNum(String [] args) - { - if (args.length == 2) - { - return 1; - } - else if (Utilities.isInt(args[2])) - { - return Integer.parseInt(args[2]); - } - else - { - return -1; - } - } - - public void sendReport(CommandSender cs, List players, String group, ChatColor color, int page) - { - int pages = (int)Math.ceil(((float)players.size())/7); - if(page <= pages && page > 0) - { - cs.sendMessage("--------------------[" + GREEN + "REPORT[" + page + "/"+pages+"]" + WHITE + "]---------------------"); - cs.sendMessage(GRAY + "Group: " + color + group); - for (int x = 0; x < 7; x++) - { - int index = ((page-1)*6)+(x+((page-1)*1)); - if(index < players.size()) - { - String player = players.get(index); - cs.sendMessage(GRAY + player); - } - } - cs.sendMessage(MENU_END); - } - else - { - if(pages == 0) - { - cs.sendMessage("--------------------[" + GREEN + "REPORT[1/1]" + WHITE + "]---------------------"); - cs.sendMessage(GRAY + "Group: " + color + group); - cs.sendMessage(GRAY + "There are no users in this group."); - cs.sendMessage(MENU_END); - } - else - { - cs.sendMessage(RED+"Page not found. Requested "+WHITE+page+RED+", Max "+WHITE+pages); - } - } - } - - public void handlePlayerReport(CommandSender cs, String[] args) - { - if (Permission.SYSTEM_REPORT.get(cs)) - { - User user = Anticheat.getManager().getUserManager().getUser(args[1]); - boolean cont = false; - if (user == null) - { - if((user = Anticheat.getManager().getUserManager().loadUserFromFile(args[1])) == null) - { - cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found."); - } - else - { - cont = true; - } - } - else - { - cont = true; - } - if (cont) - { - List l = new ArrayList(); - for(CheckType type : CheckType.values()) - { - if(type.getUses(user.getName()) > 0) - { - l.add(type); - } - } - if (args.length == 2) - { - sendPlayerReport(cs, l, user, 1); - } - else if (Utilities.isInt(args[2])) - { - int num = Integer.parseInt(args[2]); - sendPlayerReport(cs, l, user, num); - } - else - { - cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); - } - } - } - else - { - cs.sendMessage(PERMISSIONS_ERROR); - } - } - - public void sendPlayerReport(CommandSender cs, List types, User user, int page) - { - String name = user.getName(); - int pages = (int)Math.ceil(((float)types.size())/6); - int level = user.getLevel(); - String levelString = GREEN + "Low"; - if (level >= CONFIG.highThreshold()) - { - levelString = RED + "High"; - } - else if (level >= CONFIG.medThreshold()) - { - levelString = YELLOW + "Medium"; - } - if(page <= pages && page > 0) - { - cs.sendMessage("--------------------[" + GREEN + "REPORT[" + page + "/"+pages+"]" + WHITE + "]---------------------"); - cs.sendMessage(GRAY + "Player: " + WHITE + name); - cs.sendMessage(GRAY + "Level: " + levelString); - for (int x = 0; x < 6; x++) - { - int index = ((page-1)*5)+(x+((page-1)*1)); - if(index < types.size()) - { - int use = types.get(index).getUses(name); - ChatColor color = WHITE; - if (use >= 20) - { - color = YELLOW; - } - else if (use > 50) - { - color = RED; - } - cs.sendMessage(GRAY + CheckType.getName(types.get(index)) + ": " + color + use); - } - } - cs.sendMessage(MENU_END); - } - else - { - if(pages == 0) - { - cs.sendMessage("--------------------[" + GREEN + "REPORT[1/1]" + WHITE + "]---------------------"); - cs.sendMessage(GRAY + "Player: " + WHITE + name); - cs.sendMessage(GRAY + "Level: " + levelString); - cs.sendMessage(GRAY + "This user has not failed any checks."); - cs.sendMessage(MENU_END); - } - else - { - cs.sendMessage(RED+"Page not found. Requested "+WHITE+page+RED+", Max "+WHITE+pages); - } - } - } - - public void handleReload(CommandSender cs) - { - if (Permission.SYSTEM_RELOAD.get(cs)) - { - CONFIG.load(); - cs.sendMessage(GREEN + "AntiCheat configuration reloaded."); - } - else - { - cs.sendMessage(PERMISSIONS_ERROR); - } - } - - @Override - public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) - { - if (args.length == 3) - { - if (args[0].equalsIgnoreCase("report")) - { - if(args[1].equalsIgnoreCase("low") || args[1].equalsIgnoreCase("medium") || args[1].equalsIgnoreCase("high")) - { - handleReport(cs, args); - } - else - { - handlePlayerReport(cs, args); - } - } - } - else if (args.length == 2) - { - if (args[0].equalsIgnoreCase("log")) - { - handleLog(cs, args); - } - else if (args[0].equalsIgnoreCase("xray")) - { - handleXRay(cs, args); - } - else if (args[0].equalsIgnoreCase("reset")) - { - handleReset(cs, args); - } - else if (args[0].equalsIgnoreCase("spy")) - { - handleSpy(cs, args); - } - else if (args[0].equalsIgnoreCase("report")) - { - if(args[1].equalsIgnoreCase("low") || args[1].equalsIgnoreCase("medium") || args[1].equalsIgnoreCase("high")) - { - handleReport(cs, args); - } - else - { - handlePlayerReport(cs, args); - } - } - else - { - cs.sendMessage(RED + "Unrecognized command."); - } - } - else if (args.length == 1) - { - if (args[0].equalsIgnoreCase("help")) - { - handleHelp(cs); - } - else if (args[0].equalsIgnoreCase("debug")) - { - handleDebug(cs); - } - else if (args[0].equalsIgnoreCase("report")) - { - cs.sendMessage(ChatColor.GREEN+"To see the report of a specific user, type their name, like so:"); - cs.sendMessage(ChatColor.WHITE+"/anticheat report [user]"); - cs.sendMessage(ChatColor.GRAY+" - This will allow you to see the checks that user has failed."); - cs.sendMessage(ChatColor.GREEN+"To see the report of an AntiCheat group, type it's name, like so:"); - cs.sendMessage(ChatColor.WHITE+"/anticheat report [low/medium/high]"); - cs.sendMessage(ChatColor.GRAY+" - This will allow you to see which players are good, and which could be hacking."); - } - else if (args[0].equalsIgnoreCase("reload")) - { - handleReload(cs); - } - else if (args[0].equalsIgnoreCase("update")) - { - handleUpdate(cs); - } - /**else if (args[0].equalsIgnoreCase("calibrate")) - { - handleCalibrate(cs); - }*/ - else - { - cs.sendMessage(RED + "Unrecognized command."); - } - } - else - { - cs.sendMessage(RED + "Unrecognized command. Try " + ChatColor.WHITE + "/anticheat help"); - } - return true; - } - - public void getPlayers() - { - high.clear(); - med.clear(); - low.clear(); - for (Player player : SERVER.getOnlinePlayers()) - { - int level = USER_MANAGER.safeGetLevel(player.getName()); - if (level <= MED_THRESHOLD) - { - low.add(player.getName()); - } - else if (level <= HIGH_THRESHOLD) - { - med.add(player.getName()); - } - else - { - high.add(player.getName()); - } - } - } +public class CommandHandler implements CommandExecutor { + private static final Configuration CONFIG = Anticheat.getManager().getConfiguration(); + private static final UserManager USER_MANAGER = Anticheat.getManager().getUserManager(); + private static final XRayTracker XRAY_TRACKER = Anticheat.getManager().getXRayTracker(); + private static final ChatColor RED = ChatColor.RED; + private static final ChatColor YELLOW = ChatColor.YELLOW; + private static final ChatColor GREEN = ChatColor.GREEN; + private static final ChatColor WHITE = ChatColor.WHITE; + private static final ChatColor GRAY = ChatColor.GRAY; + private List high = new ArrayList(); + private List med = new ArrayList(); + private List low = new ArrayList(); + private static final Server SERVER = Bukkit.getServer(); + private static final int MED_THRESHOLD = 20; + private static final int HIGH_THRESHOLD = 50; + private static final String PERMISSIONS_ERROR = RED + "Insufficient Permissions."; + private static final String MENU_END = "-----------------------------------------------------"; + + public void handleLog(CommandSender cs, String[] args) { + if (Permission.SYSTEM_LOG.get(cs)) { + if (args[1].equalsIgnoreCase("enable")) { + if (!CONFIG.logConsole()) { + CONFIG.setLog(true); + cs.sendMessage(GREEN + "Console logging enabled."); + } else { + cs.sendMessage(GREEN + "Console logging is already enabled!"); + } + } else if (args[1].equalsIgnoreCase("disable")) { + if (CONFIG.logConsole()) { + CONFIG.setLog(false); + cs.sendMessage(GREEN + "Console logging disabled."); + } else { + cs.sendMessage(GREEN + "Console logging is already disabled!"); + } + } else { + cs.sendMessage(RED + "Usage: /anticheat log [enable/disable]"); + } + } else { + cs.sendMessage(PERMISSIONS_ERROR); + } + } + + public void handleDebug(CommandSender cs) { + if (Permission.SYSTEM_REPORT.get(cs)) { + PastebinReport report = new PastebinReport(cs); + cs.sendMessage(GREEN + "Debug information posted to: " + WHITE + report.getURL()); + cs.sendMessage(GREEN + "Please include this link when making bug reports."); + } else { + cs.sendMessage(PERMISSIONS_ERROR); + } + } + + public void handleXRay(CommandSender cs, String[] args) { + if (Permission.SYSTEM_XRAY.get(cs)) { + if (CONFIG.logXRay()) { + List list = SERVER.matchPlayer(args[1]); + if (list.size() == 1) { + Player player = list.get(0); + if (XRAY_TRACKER.sufficientData(player.getName())) { + XRAY_TRACKER.sendStats(cs, player.getName()); + } else { + cs.sendMessage(RED + "Insufficient data collected from " + WHITE + args[1] + RED + "."); + cs.sendMessage(RED + "Please wait until more info is collected before predictions are calculated."); + } + } else if (list.size() > 1) { + cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + "."); + } else if (XRAY_TRACKER.sufficientData(args[1])) { + XRAY_TRACKER.sendStats(cs, args[1]); + } else { + cs.sendMessage(RED + "Insufficient data collected from " + WHITE + args[1] + RED + "."); + cs.sendMessage(RED + "Please wait until more info is collected before predictions are calculated."); + } + } else { + cs.sendMessage(RED + "XRay logging is off in the config."); + } + } else { + cs.sendMessage(PERMISSIONS_ERROR); + } + } + + public void handleReset(CommandSender cs, String[] args) { + if (Permission.SYSTEM_RESET.get(cs)) { + List list = SERVER.matchPlayer(args[1]); + if (list.size() == 1) { + Player player = list.get(0); + if (USER_MANAGER.safeGetLevel(player.getName()) == 0) { + cs.sendMessage(player.getName() + RED + " is already in Low Level!"); + } else { + USER_MANAGER.safeReset(player.getName()); + cs.sendMessage(player.getName() + GREEN + " has been reset to Low Level."); + } + XRAY_TRACKER.reset(player.getName()); + cs.sendMessage(player.getName() + GREEN + "'s XRay stats have been reset."); + } else if (list.size() > 1) { + cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + "."); + } else { + cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found."); + } + } else { + cs.sendMessage(PERMISSIONS_ERROR); + } + } + + public void handleSpy(CommandSender cs, String[] args) { + if (cs instanceof Player) { + if (Permission.SYSTEM_SPY.get(cs)) { + Player sender = (Player) cs; + if (!args[1].equalsIgnoreCase("off")) { + List list = SERVER.matchPlayer(args[1]); + if (list.size() == 1) { + Player player = list.get(0); + for (Player p : cs.getServer().getOnlinePlayers()) { + if (!Permission.SYSTEM_SPY.get(p)) { + p.hidePlayer(sender); + } + } + if (!sender.hasMetadata(Anticheat.SPY_METADATA)) // Maintain ORIGINAL location and other data + { + SpyState state = new SpyState(sender.getAllowFlight(), sender.isFlying(), sender.getLocation()); + sender.setMetadata(Anticheat.SPY_METADATA, new FixedMetadataValue(Anticheat.getPlugin(), state)); + } + sender.setAllowFlight(true); + sender.setFlying(true); + sender.teleport(player); + sender.sendMessage(GREEN + "You have been teleported to " + player.getName() + " and made invisible."); + sender.sendMessage(GREEN + "To stop spying, type " + WHITE + " /AntiCheat spy off"); + } else if (list.size() > 1) { + cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + "."); + } else { + cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found."); + } + } else { + if (sender.hasMetadata(Anticheat.SPY_METADATA)) { + SpyState state = ((SpyState) sender.getMetadata(Anticheat.SPY_METADATA).get(0).value()); + sender.setAllowFlight(state.getAllowFlight()); + sender.setFlying(state.getFlying()); + sender.teleport(state.getLocation()); + sender.removeMetadata(Anticheat.SPY_METADATA, Anticheat.getPlugin()); + for (Player p : cs.getServer().getOnlinePlayers()) { + p.showPlayer(sender); + } + sender.sendMessage(GREEN + "Done spying! Brought you back to where you started!"); + } else { + sender.sendMessage(RED + "You were not spying."); + } + } + } else { + cs.sendMessage(PERMISSIONS_ERROR); + } + } else { + cs.sendMessage(RED + "Sorry, but you can't spy on a player from the console."); + } + } + + public void handleHelp(CommandSender cs) { + if (Permission.SYSTEM_HELP.get(cs)) { + String base = "/AntiCheat "; + cs.sendMessage("----------------------[" + GREEN + "AntiCheat" + WHITE + "]----------------------"); + cs.sendMessage(base + GREEN + "log [Enable/Disable]" + WHITE + " - toggle logging"); + cs.sendMessage(base + GREEN + "report [low/medium/high]" + WHITE + " - show users in groups"); + cs.sendMessage(base + GREEN + "report [user]" + WHITE + " - get a player's cheat report"); + cs.sendMessage(base + GREEN + "reload" + WHITE + " - reload AntiCheat configuration"); + cs.sendMessage(base + GREEN + "reset [user]" + WHITE + " - reset user's hack level"); + cs.sendMessage(base + GREEN + "xray [user]" + WHITE + " - check user's xray levels"); + cs.sendMessage(base + GREEN + "spy [user]" + WHITE + " - spy on a user in secret"); + cs.sendMessage(base + GREEN + "help" + WHITE + " - access this page"); + cs.sendMessage(base + GREEN + "debug" + WHITE + " - post debug information"); + cs.sendMessage(base + GREEN + "update" + WHITE + " - check update status"); + cs.sendMessage(MENU_END); + } else { + cs.sendMessage(PERMISSIONS_ERROR); + } + } + + public void handleUpdate(CommandSender cs) { + if (Permission.SYSTEM_UPDATE.get(cs)) { + cs.sendMessage("Running " + GREEN + "AntiCheat " + WHITE + "v" + GREEN + Anticheat.getVersion()); + cs.sendMessage(MENU_END); + if (!Anticheat.isUpdated()) { + cs.sendMessage(GRAY + "There " + GREEN + "IS" + GRAY + " a newer version avaliable."); + if (CONFIG.autoUpdate()) { + cs.sendMessage(GRAY + "It will be installed automatically for you on next launch."); + } else { + cs.sendMessage(GRAY + "Due to your config settings, we " + RED + "can not" + GRAY + " auto update."); + cs.sendMessage(GRAY + "Please visit http://dev.bukkit.org/server-mods/anticheat/"); + } + } else { + cs.sendMessage(GRAY + "AntiCheat is " + GREEN + "UP TO DATE!"); + } + } else { + cs.sendMessage(PERMISSIONS_ERROR); + } + } + + public void handleCalibrate(CommandSender cs) { + if (cs instanceof Player) { + if (Permission.SYSTEM_CALIBRATE.get(cs)) { + Calibrator c = new Calibrator((Player) cs); + SERVER.getPluginManager().registerEvents(c, Anticheat.getPlugin()); + c.calibrate(); + } else { + cs.sendMessage(PERMISSIONS_ERROR); + } + } else { + cs.sendMessage(RED + "Sorry, but you cannot calibrate from console."); + } + } + + public void handleReport(CommandSender cs, String[] args) { + if (Permission.SYSTEM_REPORT.get(cs)) { + getPlayers(); + if (args.length > 1) { + String group = args[1]; + if (group.equalsIgnoreCase("low")) { + int num = getReportPageNum(args); + if (num > 0) { + sendReport(cs, low, "Low", GREEN, num); + } else { + cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); + } + } else if (group.equalsIgnoreCase("medium")) { + int num = getReportPageNum(args); + if (num > 0) { + sendReport(cs, med, "Medium", YELLOW, num); + } else { + cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); + } + } + if (group.equalsIgnoreCase("high")) { + int num = getReportPageNum(args); + if (num > 0) { + sendReport(cs, high, "High", RED, num); + } else { + cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); + } + } + } + } else { + cs.sendMessage(PERMISSIONS_ERROR); + } + } + + public int getReportPageNum(String[] args) { + if (args.length == 2) { + return 1; + } else if (Utilities.isInt(args[2])) { + return Integer.parseInt(args[2]); + } else { + return -1; + } + } + + public void sendReport(CommandSender cs, List players, String group, ChatColor color, int page) { + int pages = (int) Math.ceil(((float) players.size()) / 7); + if (page <= pages && page > 0) { + cs.sendMessage("--------------------[" + GREEN + "REPORT[" + page + "/" + pages + "]" + WHITE + "]---------------------"); + cs.sendMessage(GRAY + "Group: " + color + group); + for (int x = 0; x < 7; x++) { + int index = ((page - 1) * 6) + (x + ((page - 1) * 1)); + if (index < players.size()) { + String player = players.get(index); + cs.sendMessage(GRAY + player); + } + } + cs.sendMessage(MENU_END); + } else { + if (pages == 0) { + cs.sendMessage("--------------------[" + GREEN + "REPORT[1/1]" + WHITE + "]---------------------"); + cs.sendMessage(GRAY + "Group: " + color + group); + cs.sendMessage(GRAY + "There are no users in this group."); + cs.sendMessage(MENU_END); + } else { + cs.sendMessage(RED + "Page not found. Requested " + WHITE + page + RED + ", Max " + WHITE + pages); + } + } + } + + public void handlePlayerReport(CommandSender cs, String[] args) { + if (Permission.SYSTEM_REPORT.get(cs)) { + User user = Anticheat.getManager().getUserManager().getUser(args[1]); + boolean cont = false; + if (user == null) { + if ((user = Anticheat.getManager().getUserManager().loadUserFromFile(args[1])) == null) { + cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found."); + } else { + cont = true; + } + } else { + cont = true; + } + if (cont) { + List l = new ArrayList(); + for (CheckType type : CheckType.values()) { + if (type.getUses(user.getName()) > 0) { + l.add(type); + } + } + if (args.length == 2) { + sendPlayerReport(cs, l, user, 1); + } else if (Utilities.isInt(args[2])) { + int num = Integer.parseInt(args[2]); + sendPlayerReport(cs, l, user, num); + } else { + cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); + } + } + } else { + cs.sendMessage(PERMISSIONS_ERROR); + } + } + + public void sendPlayerReport(CommandSender cs, List types, User user, int page) { + String name = user.getName(); + int pages = (int) Math.ceil(((float) types.size()) / 6); + int level = user.getLevel(); + String levelString = GREEN + "Low"; + if (level >= CONFIG.highThreshold()) { + levelString = RED + "High"; + } else if (level >= CONFIG.medThreshold()) { + levelString = YELLOW + "Medium"; + } + if (page <= pages && page > 0) { + cs.sendMessage("--------------------[" + GREEN + "REPORT[" + page + "/" + pages + "]" + WHITE + "]---------------------"); + cs.sendMessage(GRAY + "Player: " + WHITE + name); + cs.sendMessage(GRAY + "Level: " + levelString); + for (int x = 0; x < 6; x++) { + int index = ((page - 1) * 5) + (x + ((page - 1) * 1)); + if (index < types.size()) { + int use = types.get(index).getUses(name); + ChatColor color = WHITE; + if (use >= 20) { + color = YELLOW; + } else if (use > 50) { + color = RED; + } + cs.sendMessage(GRAY + CheckType.getName(types.get(index)) + ": " + color + use); + } + } + cs.sendMessage(MENU_END); + } else { + if (pages == 0) { + cs.sendMessage("--------------------[" + GREEN + "REPORT[1/1]" + WHITE + "]---------------------"); + cs.sendMessage(GRAY + "Player: " + WHITE + name); + cs.sendMessage(GRAY + "Level: " + levelString); + cs.sendMessage(GRAY + "This user has not failed any checks."); + cs.sendMessage(MENU_END); + } else { + cs.sendMessage(RED + "Page not found. Requested " + WHITE + page + RED + ", Max " + WHITE + pages); + } + } + } + + public void handleReload(CommandSender cs) { + if (Permission.SYSTEM_RELOAD.get(cs)) { + CONFIG.load(); + cs.sendMessage(GREEN + "AntiCheat configuration reloaded."); + } else { + cs.sendMessage(PERMISSIONS_ERROR); + } + } + + @Override + public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) { + if (args.length == 3) { + if (args[0].equalsIgnoreCase("report")) { + if (args[1].equalsIgnoreCase("low") || args[1].equalsIgnoreCase("medium") || args[1].equalsIgnoreCase("high")) { + handleReport(cs, args); + } else { + handlePlayerReport(cs, args); + } + } + } else if (args.length == 2) { + if (args[0].equalsIgnoreCase("log")) { + handleLog(cs, args); + } else if (args[0].equalsIgnoreCase("xray")) { + handleXRay(cs, args); + } else if (args[0].equalsIgnoreCase("reset")) { + handleReset(cs, args); + } else if (args[0].equalsIgnoreCase("spy")) { + handleSpy(cs, args); + } else if (args[0].equalsIgnoreCase("report")) { + if (args[1].equalsIgnoreCase("low") || args[1].equalsIgnoreCase("medium") || args[1].equalsIgnoreCase("high")) { + handleReport(cs, args); + } else { + handlePlayerReport(cs, args); + } + } else { + cs.sendMessage(RED + "Unrecognized command."); + } + } else if (args.length == 1) { + if (args[0].equalsIgnoreCase("help")) { + handleHelp(cs); + } else if (args[0].equalsIgnoreCase("debug")) { + handleDebug(cs); + } else if (args[0].equalsIgnoreCase("report")) { + cs.sendMessage(ChatColor.GREEN + "To see the report of a specific user, type their name, like so:"); + cs.sendMessage(ChatColor.WHITE + "/anticheat report [user]"); + cs.sendMessage(ChatColor.GRAY + " - This will allow you to see the checks that user has failed."); + cs.sendMessage(ChatColor.GREEN + "To see the report of an AntiCheat group, type it's name, like so:"); + cs.sendMessage(ChatColor.WHITE + "/anticheat report [low/medium/high]"); + cs.sendMessage(ChatColor.GRAY + " - This will allow you to see which players are good, and which could be hacking."); + } else if (args[0].equalsIgnoreCase("reload")) { + handleReload(cs); + } else if (args[0].equalsIgnoreCase("update")) { + handleUpdate(cs); + } + /** + * else if (args[0].equalsIgnoreCase("calibrate")) { handleCalibrate(cs); } + */ + else { + cs.sendMessage(RED + "Unrecognized command."); + } + } else { + cs.sendMessage(RED + "Unrecognized command. Try " + ChatColor.WHITE + "/anticheat help"); + } + return true; + } + + public void getPlayers() { + high.clear(); + med.clear(); + low.clear(); + for (Player player : SERVER.getOnlinePlayers()) { + int level = USER_MANAGER.safeGetLevel(player.getName()); + if (level <= MED_THRESHOLD) { + low.add(player.getName()); + } else if (level <= HIGH_THRESHOLD) { + med.add(player.getName()); + } else { + high.add(player.getName()); + } + } + } } diff --git a/src/main/java/net/h31ix/anticheat/api/AnticheatAPI.java b/src/main/java/net/h31ix/anticheat/api/AnticheatAPI.java index ce07fb9..472fad7 100644 --- a/src/main/java/net/h31ix/anticheat/api/AnticheatAPI.java +++ b/src/main/java/net/h31ix/anticheat/api/AnticheatAPI.java @@ -28,161 +28,128 @@ import org.bukkit.entity.Player; * Developer's interface for all things AntiCheat. */ -public class AnticheatAPI -{ - private static CheckManager chk = Anticheat.getManager().getCheckManager(); - private static UserManager umr = Anticheat.getManager().getUserManager(); - private static XRayTracker xtracker = Anticheat.getManager().getXRayTracker(); - - //CheckManager API - - /** - * Start running a certain check - * - * @param type - * Check to start watching for - */ - public static void activateCheck(CheckType type) - { - chk.activateCheck(type); - } - - /** - * Stop running a certain check - * - * @param type - * Check to stop watching for - */ - public static void deactivateCheck(CheckType type) - { - chk.deactivateCheck(type); - } - - /** - * Find out if a check is currently being watched for - * - * @param type - * Type to check - * @return true if plugin is watching for this check - */ - public static boolean isActive(CheckType type) - { - return chk.isActive(type); - } - - /** - * Allow a player to skip a certain check - * - * @param player - * Player to stop watching - * @param type - * Check to stop watching for - */ - public static void exemptPlayer(Player player, CheckType type) - { - chk.exemptPlayer(player, type); - } - - /** - * Stop allowing a player to skip a certain check - * - * @param player - * Player to start watching - * @param type - * Check to start watching for - */ - public static void unexemptPlayer(Player player, CheckType type) - { - chk.unexemptPlayer(player, type); - } - - /** - * Find out if a player is currently exempt from a certain check - * - * @param player - * Player to check - * @param type - * Type to check - * @return true if plugin is ignoring this check on this player - */ - public static boolean isExempt(Player player, CheckType type) - { - return chk.isExempt(player, type); - } - - /** - * Find out if a check will occur for a player. This checks if they are - * being tracked, the check is active, the player isn't exempt from the - * check, and the player doesn't have override permission. - * - * @param player - * Player to check - * @param type - * Type to check - * @return true if plugin will check this player, and that all things allow - * it to happen. - */ - public boolean willCheck(Player player, CheckType type) - { - return chk.willCheck(player, type); - } - - //PlayerManager API - - /** - * Get a player's integer hack level - * - * @param player - * Player to check - * @return player's hack level - */ - public static int getLevel(Player player) - { - return umr.safeGetLevel(player.getName()); - } - - - /** - * Set a player's hack level (Min = 0, Max = 50) - * - * @param player - * Player to set - * @param level - * Level to set to - */ - public static void setLevel(Player player, int level) - { - umr.safeSetLevel(player.getName(), level); - } - - //XrayTracker API - - /** - * Find out if a player is detected as using xray hacks (on any ore) - * - * @param player - * Player to check - * @return true if the player has any xray anomalies. - */ - public static boolean isXrayer(Player player) - { - String name = player.getName(); - if (xtracker.sufficientData(name) && xtracker.hasAbnormal(name)) - { - return true; - } - return false; - } - - //Advanced Users Only API. - - /** - * Get access to all the other managers, advanced users ONLY - * - * @return the AntiCheat Manager - */ - public static AnticheatManager getManager() - { - return Anticheat.getManager(); - } +public class AnticheatAPI { + private static CheckManager chk = Anticheat.getManager().getCheckManager(); + private static UserManager umr = Anticheat.getManager().getUserManager(); + private static XRayTracker xtracker = Anticheat.getManager().getXRayTracker(); + + // CheckManager API + + /** + * Start running a certain check + * + * @param type Check to start watching for + */ + public static void activateCheck(CheckType type) { + chk.activateCheck(type); + } + + /** + * Stop running a certain check + * + * @param type Check to stop watching for + */ + public static void deactivateCheck(CheckType type) { + chk.deactivateCheck(type); + } + + /** + * Find out if a check is currently being watched for + * + * @param type Type to check + * @return true if plugin is watching for this check + */ + public static boolean isActive(CheckType type) { + return chk.isActive(type); + } + + /** + * Allow a player to skip a certain check + * + * @param player Player to stop watching + * @param type Check to stop watching for + */ + public static void exemptPlayer(Player player, CheckType type) { + chk.exemptPlayer(player, type); + } + + /** + * Stop allowing a player to skip a certain check + * + * @param player Player to start watching + * @param type Check to start watching for + */ + public static void unexemptPlayer(Player player, CheckType type) { + chk.unexemptPlayer(player, type); + } + + /** + * Find out if a player is currently exempt from a certain check + * + * @param player Player to check + * @param type Type to check + * @return true if plugin is ignoring this check on this player + */ + public static boolean isExempt(Player player, CheckType type) { + return chk.isExempt(player, type); + } + + /** + * Find out if a check will occur for a player. This checks if they are being tracked, the check is active, the player isn't exempt from the check, and the player doesn't have override permission. + * + * @param player Player to check + * @param type Type to check + * @return true if plugin will check this player, and that all things allow it to happen. + */ + public boolean willCheck(Player player, CheckType type) { + return chk.willCheck(player, type); + } + + // PlayerManager API + + /** + * Get a player's integer hack level + * + * @param player Player to check + * @return player's hack level + */ + public static int getLevel(Player player) { + return umr.safeGetLevel(player.getName()); + } + + + /** + * Set a player's hack level (Min = 0, Max = 50) + * + * @param player Player to set + * @param level Level to set to + */ + public static void setLevel(Player player, int level) { + umr.safeSetLevel(player.getName(), level); + } + + // XrayTracker API + + /** + * Find out if a player is detected as using xray hacks (on any ore) + * + * @param player Player to check + * @return true if the player has any xray anomalies. + */ + public static boolean isXrayer(Player player) { + String name = player.getName(); + if (xtracker.sufficientData(name) && xtracker.hasAbnormal(name)) { return true; } + return false; + } + + // Advanced Users Only API. + + /** + * Get access to all the other managers, advanced users ONLY + * + * @return the AntiCheat Manager + */ + public static AnticheatManager getManager() { + return Anticheat.getManager(); + } } diff --git a/src/main/java/net/h31ix/anticheat/event/BlockListener.java b/src/main/java/net/h31ix/anticheat/event/BlockListener.java index 06aa932..154b495 100644 --- a/src/main/java/net/h31ix/anticheat/event/BlockListener.java +++ b/src/main/java/net/h31ix/anticheat/event/BlockListener.java @@ -25,7 +25,6 @@ import net.h31ix.anticheat.manage.CheckType; import net.h31ix.anticheat.util.Configuration; import net.h31ix.anticheat.util.Distance; import net.h31ix.anticheat.util.Utilities; - import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -34,82 +33,66 @@ import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockPlaceEvent; -public class BlockListener extends EventListener -{ - private final Backend backend = getBackend(); - private final CheckManager checkManager = getCheckManager(); - private final Configuration config = Anticheat.getManager().getConfiguration(); - - @EventHandler(priority = EventPriority.MONITOR) - public void onBlockDamage(BlockDamageEvent event) - { - Player player = event.getPlayer(); - if (event.getInstaBreak() && Utilities.isInstantBreak(event.getBlock().getType())) - { - backend.logInstantBreak(player); - } - if (checkManager.willCheck(player, CheckType.AUTOTOOL) && backend.justSwitchedTool(player)) - { - event.setCancelled(!config.silentMode()); - log("tried to switch their tool too fast.", player, CheckType.AUTOTOOL); - } - } - - @EventHandler(ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) - { - final Player player = event.getPlayer(); - Block block = event.getBlock(); - if (player != null && checkManager.willCheck(player, CheckType.FAST_PLACE)) - { - if (backend.checkFastPlace(player)) - { - event.setCancelled(!config.silentMode()); - log("tried to place a block of " + block.getType().name() + " too fast.", player, CheckType.FAST_PLACE); - } - else - { - decrease(player); - backend.logBlockPlace(player); - } - } - } - - @EventHandler(ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) - { - final Player player = event.getPlayer(); - final Block block = event.getBlock(); - boolean noHack = true; - if (player != null) - { - if (checkManager.willCheck(player, CheckType.FAST_BREAK) && !backend.isInstantBreakExempt(player) && backend.checkFastBreak(player, block)) - { - event.setCancelled(!config.silentMode()); - log("tried to break a block of " + block.getType().name() + " too fast.", player, CheckType.FAST_BREAK); - noHack = false; - } - if (checkManager.willCheck(player, CheckType.NO_SWING) && backend.checkSwing(player, block)) - { - event.setCancelled(!config.silentMode()); - log("tried to break a block of " + block.getType().name() + " without swinging their arm.", player, CheckType.NO_SWING); - noHack = false; - } - if (checkManager.willCheck(player, CheckType.LONG_REACH)) - { - Distance distance = new Distance(player.getLocation(), block.getLocation()); - if (backend.checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference())) - { - event.setCancelled(!config.silentMode()); - log("tried to break a block of " + block.getType().name() + " that was too far away.", player, CheckType.LONG_REACH); - noHack = false; - } - } - } - if (noHack) - { - decrease(player); - } - backend.logBlockBreak(player); - } +public class BlockListener extends EventListener { + private final Backend backend = getBackend(); + private final CheckManager checkManager = getCheckManager(); + private final Configuration config = Anticheat.getManager().getConfiguration(); + + @EventHandler(priority = EventPriority.MONITOR) + public void onBlockDamage(BlockDamageEvent event) { + Player player = event.getPlayer(); + if (event.getInstaBreak() && Utilities.isInstantBreak(event.getBlock().getType())) { + backend.logInstantBreak(player); + } + if (checkManager.willCheck(player, CheckType.AUTOTOOL) && backend.justSwitchedTool(player)) { + event.setCancelled(!config.silentMode()); + log("tried to switch their tool too fast.", player, CheckType.AUTOTOOL); + } + } + + @EventHandler(ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + final Player player = event.getPlayer(); + Block block = event.getBlock(); + if (player != null && checkManager.willCheck(player, CheckType.FAST_PLACE)) { + if (backend.checkFastPlace(player)) { + event.setCancelled(!config.silentMode()); + log("tried to place a block of " + block.getType().name() + " too fast.", player, CheckType.FAST_PLACE); + } else { + decrease(player); + backend.logBlockPlace(player); + } + } + } + + @EventHandler(ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + final Player player = event.getPlayer(); + final Block block = event.getBlock(); + boolean noHack = true; + if (player != null) { + if (checkManager.willCheck(player, CheckType.FAST_BREAK) && !backend.isInstantBreakExempt(player) && backend.checkFastBreak(player, block)) { + event.setCancelled(!config.silentMode()); + log("tried to break a block of " + block.getType().name() + " too fast.", player, CheckType.FAST_BREAK); + noHack = false; + } + if (checkManager.willCheck(player, CheckType.NO_SWING) && backend.checkSwing(player, block)) { + event.setCancelled(!config.silentMode()); + log("tried to break a block of " + block.getType().name() + " without swinging their arm.", player, CheckType.NO_SWING); + noHack = false; + } + if (checkManager.willCheck(player, CheckType.LONG_REACH)) { + Distance distance = new Distance(player.getLocation(), block.getLocation()); + if (backend.checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference())) { + event.setCancelled(!config.silentMode()); + log("tried to break a block of " + block.getType().name() + " that was too far away.", player, CheckType.LONG_REACH); + noHack = false; + } + } + } + if (noHack) { + decrease(player); + } + backend.logBlockBreak(player); + } } diff --git a/src/main/java/net/h31ix/anticheat/event/EntityListener.java b/src/main/java/net/h31ix/anticheat/event/EntityListener.java index e74f374..a38128e 100644 --- a/src/main/java/net/h31ix/anticheat/event/EntityListener.java +++ b/src/main/java/net/h31ix/anticheat/event/EntityListener.java @@ -33,157 +33,120 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.entity.*; import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; -public class EntityListener extends EventListener -{ - private final Backend backend = getBackend(); - private final CheckManager checkManager = getCheckManager(); - private final Configuration config = Anticheat.getManager().getConfiguration(); - - @EventHandler - public void onEntityShootBow(EntityShootBowEvent event) - { - if (event.getEntity() instanceof Player) - { - Player player = (Player) event.getEntity(); - if (checkManager.willCheck(player, CheckType.FAST_BOW)) - { - if (backend.checkFastBow(player, event.getForce())) - { - event.setCancelled(!config.silentMode()); - log("tried to fire a bow too fast.", player, CheckType.FAST_BOW); - } - else - { - decrease(player); - } - } - } - } - - @EventHandler - public void onEntityRegainHealth(EntityRegainHealthEvent event) - { - if (event.getEntity() instanceof Player && event.getRegainReason() == RegainReason.SATIATED) - { - Player player = (Player) event.getEntity(); - if (checkManager.willCheck(player, CheckType.FAST_HEAL)) - { - if (backend.justHealed(player)) - { - event.setCancelled(!config.silentMode()); - log("tried to heal too fast.", player, CheckType.FAST_HEAL); - } - else - { - decrease(player); - backend.logHeal(player); - } - } - } - } - - @EventHandler - public void onFoodLevelChange(FoodLevelChangeEvent event) - { - if (event.getEntity() instanceof Player) - { - Player player = (Player) event.getEntity(); - if(player.getFoodLevel() < event.getFoodLevel() && checkManager.willCheck(player, CheckType.FAST_EAT)) // Make sure it's them actually gaining a food level - { - if (backend.justStartedEating(player)) - { - event.setCancelled(!config.silentMode()); - log("tried to eat too fast.", player, CheckType.FAST_EAT); - } - else - { - decrease(player); - } - } - } - } - - @EventHandler(ignoreCancelled = true) - public void onEntityDamage(EntityDamageEvent event) - { - boolean noHack = true; - if (event instanceof EntityDamageByEntityEvent) - { - EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event; - if (event.getEntity() instanceof Player) - { - Player player = (Player) event.getEntity(); - // Keep players from shooting an arrow at themselves in order to fly - if(e.getDamager() instanceof Arrow) - { - Arrow arrow = (Arrow)e.getDamager(); - if(arrow.getShooter() instanceof Player && event.getEntity() == arrow.getShooter()) - { - event.setCancelled(true); - } - } - if (e.getDamager() instanceof Player) - { - Player p = (Player) e.getDamager(); - backend.logDamage(p, 1); - int value = p.getInventory().getItemInHand().containsEnchantment(Enchantment.KNOCKBACK) ? 2 : 1; - backend.logDamage(player, value); - if (checkManager.willCheck(p, CheckType.LONG_REACH)) - { - Distance distance = new Distance(player.getLocation(), p.getLocation()); - if (backend.checkLongReachDamage(distance.getXDifference(), distance.getYDifference(), distance.getZDifference())) - { - event.setCancelled(!config.silentMode()); - log("tried to damage a player too far away from them.", p, CheckType.LONG_REACH); - noHack = false; - } - } - } - else - { - if (e.getDamager() instanceof TNTPrimed || e.getDamager() instanceof Creeper) - { - backend.logDamage(player, 3); - } - else - { - backend.logDamage(player, 1); - } - } - } - if (e.getDamager() instanceof Player) - { - Player player = (Player) e.getDamager(); - backend.logDamage(player, 1); - if (checkManager.willCheck(player, CheckType.AUTOTOOL) && backend.justSwitchedTool(player)) - { - event.setCancelled(!config.silentMode()); - log("tried to switch their tool too fast.", player, CheckType.AUTOTOOL); - noHack = false; - } - if (checkManager.willCheck(player, CheckType.FORCEFIELD) && backend.justSprinted(player)) - { - event.setCancelled(!config.silentMode()); - log("tried to sprint & damage too fast.", player, CheckType.FORCEFIELD); - noHack = false; - } - if (checkManager.willCheck(player, CheckType.NO_SWING) && !backend.justAnimated(player)) - { - event.setCancelled(!config.silentMode()); - log("tried to damage an entity without swinging their arm.", player, CheckType.NO_SWING); - noHack = false; - } - if (checkManager.willCheck(player, CheckType.FORCEFIELD) && !backend.checkSight(player, e.getEntity())) - { - event.setCancelled(!config.silentMode()); - log("tried to damage an entity that they couldn't see.", player, CheckType.FORCEFIELD); - noHack = false; - } - if (noHack) - { - decrease(player); - } - } - } - } +public class EntityListener extends EventListener { + private final Backend backend = getBackend(); + private final CheckManager checkManager = getCheckManager(); + private final Configuration config = Anticheat.getManager().getConfiguration(); + + @EventHandler + public void onEntityShootBow(EntityShootBowEvent event) { + if (event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + if (checkManager.willCheck(player, CheckType.FAST_BOW)) { + if (backend.checkFastBow(player, event.getForce())) { + event.setCancelled(!config.silentMode()); + log("tried to fire a bow too fast.", player, CheckType.FAST_BOW); + } else { + decrease(player); + } + } + } + } + + @EventHandler + public void onEntityRegainHealth(EntityRegainHealthEvent event) { + if (event.getEntity() instanceof Player && event.getRegainReason() == RegainReason.SATIATED) { + Player player = (Player) event.getEntity(); + if (checkManager.willCheck(player, CheckType.FAST_HEAL)) { + if (backend.justHealed(player)) { + event.setCancelled(!config.silentMode()); + log("tried to heal too fast.", player, CheckType.FAST_HEAL); + } else { + decrease(player); + backend.logHeal(player); + } + } + } + } + + @EventHandler + public void onFoodLevelChange(FoodLevelChangeEvent event) { + if (event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + if (player.getFoodLevel() < event.getFoodLevel() && checkManager.willCheck(player, CheckType.FAST_EAT)) // Make sure it's them actually gaining a food level + { + if (backend.justStartedEating(player)) { + event.setCancelled(!config.silentMode()); + log("tried to eat too fast.", player, CheckType.FAST_EAT); + } else { + decrease(player); + } + } + } + } + + @EventHandler(ignoreCancelled = true) + public void onEntityDamage(EntityDamageEvent event) { + boolean noHack = true; + if (event instanceof EntityDamageByEntityEvent) { + EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event; + if (event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + // Keep players from shooting an arrow at themselves in order to fly + if (e.getDamager() instanceof Arrow) { + Arrow arrow = (Arrow) e.getDamager(); + if (arrow.getShooter() instanceof Player && event.getEntity() == arrow.getShooter()) { + event.setCancelled(true); + } + } + if (e.getDamager() instanceof Player) { + Player p = (Player) e.getDamager(); + backend.logDamage(p, 1); + int value = p.getInventory().getItemInHand().containsEnchantment(Enchantment.KNOCKBACK) ? 2 : 1; + backend.logDamage(player, value); + if (checkManager.willCheck(p, CheckType.LONG_REACH)) { + Distance distance = new Distance(player.getLocation(), p.getLocation()); + if (backend.checkLongReachDamage(distance.getXDifference(), distance.getYDifference(), distance.getZDifference())) { + event.setCancelled(!config.silentMode()); + log("tried to damage a player too far away from them.", p, CheckType.LONG_REACH); + noHack = false; + } + } + } else { + if (e.getDamager() instanceof TNTPrimed || e.getDamager() instanceof Creeper) { + backend.logDamage(player, 3); + } else { + backend.logDamage(player, 1); + } + } + } + if (e.getDamager() instanceof Player) { + Player player = (Player) e.getDamager(); + backend.logDamage(player, 1); + if (checkManager.willCheck(player, CheckType.AUTOTOOL) && backend.justSwitchedTool(player)) { + event.setCancelled(!config.silentMode()); + log("tried to switch their tool too fast.", player, CheckType.AUTOTOOL); + noHack = false; + } + if (checkManager.willCheck(player, CheckType.FORCEFIELD) && backend.justSprinted(player)) { + event.setCancelled(!config.silentMode()); + log("tried to sprint & damage too fast.", player, CheckType.FORCEFIELD); + noHack = false; + } + if (checkManager.willCheck(player, CheckType.NO_SWING) && !backend.justAnimated(player)) { + event.setCancelled(!config.silentMode()); + log("tried to damage an entity without swinging their arm.", player, CheckType.NO_SWING); + noHack = false; + } + if (checkManager.willCheck(player, CheckType.FORCEFIELD) && !backend.checkSight(player, e.getEntity())) { + event.setCancelled(!config.silentMode()); + log("tried to damage an entity that they couldn't see.", player, CheckType.FORCEFIELD); + noHack = false; + } + if (noHack) { + decrease(player); + } + } + } + } } diff --git a/src/main/java/net/h31ix/anticheat/event/EventListener.java b/src/main/java/net/h31ix/anticheat/event/EventListener.java index 5b1973d..9a20a91 100644 --- a/src/main/java/net/h31ix/anticheat/event/EventListener.java +++ b/src/main/java/net/h31ix/anticheat/event/EventListener.java @@ -26,117 +26,95 @@ import net.h31ix.anticheat.manage.*; import org.bukkit.entity.Player; import org.bukkit.event.Listener; -public class EventListener implements Listener -{ - private static final Map USAGE_LIST = new EnumMap(CheckType.class); - private static final Map DECREASE_LIST = new HashMap(); - private static final CheckManager CHECK_MANAGER = Anticheat.getManager().getCheckManager(); - private static final Backend BACKEND = Anticheat.getManager().getBackend(); - private static final Anticheat PLUGIN = Anticheat.getManager().getPlugin(); - private static final UserManager USER_MANAGER = Anticheat.getManager().getUserManager(); - - public static void log(String message, Player player, CheckType type) - { - User user = getUserManager().getUser(player.getName()); - if (user.increaseLevel(type)) - { - Anticheat.getManager().log(user.getName() + " " + message); - } - removeDecrease(user); - logCheat(type, user); - } - - private static void logCheat(CheckType type, User user) - { - USAGE_LIST.put(type, getCheats(type) + 1); - type.logUse(user.getName()); - // Ignore plugins that are creating NPCs with no names (why the hell) - if(user.getName() != null) - { - if (Anticheat.getManager().getConfiguration().getFileLogLevel() == 2 && type.getUses(user.getName()) % 10 == 0) - { - Anticheat.getManager().fileLog(user.getName() + " has triggered multiple " + type + " checks."); - } - } - } - - public void resetCheck(CheckType type) - { - USAGE_LIST.put(type, 0); - } - - public static int getCheats(CheckType type) - { - int x = 0; - if (USAGE_LIST.get(type) != null) - { - x = USAGE_LIST.get(type); - } - return x; - } - - private static void removeDecrease(User user) - { - int x = 0; - // Ignore plugins that are creating NPCs with no names - if(user.getName() != null) - { - if (DECREASE_LIST.get(user.getName()) != null) - { - x = DECREASE_LIST.get(user.getName()); - x -= 2; - if (x < 0) - { - x = 0; - } - } - DECREASE_LIST.put(user.getName(), x); - } - } - - public static void decrease(Player player) - { - User user = getUserManager().getUser(player.getName()); - // Ignore plugins that are creating NPCs with no names - if(user.getName() != null) - { - int x = 0; - if (DECREASE_LIST.get(user.getName()) != null) - { - x = DECREASE_LIST.get(user.getName()); - } - x += 1; - DECREASE_LIST.put(user.getName(), x); - if (x >= 10) - { - user.decreaseLevel(); - DECREASE_LIST.put(user.getName(), 0); - } - } - } - - public static CheckManager getCheckManager() - { - return CHECK_MANAGER; - } - - public static AnticheatManager getManager() - { - return Anticheat.getManager(); - } - - public static Backend getBackend() - { - return BACKEND; - } - - public static UserManager getUserManager() - { - return USER_MANAGER; - } - - public static Anticheat getPlugin() - { - return PLUGIN; - } +public class EventListener implements Listener { + private static final Map USAGE_LIST = new EnumMap(CheckType.class); + private static final Map DECREASE_LIST = new HashMap(); + private static final CheckManager CHECK_MANAGER = Anticheat.getManager().getCheckManager(); + private static final Backend BACKEND = Anticheat.getManager().getBackend(); + private static final Anticheat PLUGIN = Anticheat.getManager().getPlugin(); + private static final UserManager USER_MANAGER = Anticheat.getManager().getUserManager(); + + public static void log(String message, Player player, CheckType type) { + User user = getUserManager().getUser(player.getName()); + if (user.increaseLevel(type)) { + Anticheat.getManager().log(user.getName() + " " + message); + } + removeDecrease(user); + logCheat(type, user); + } + + private static void logCheat(CheckType type, User user) { + USAGE_LIST.put(type, getCheats(type) + 1); + type.logUse(user.getName()); + // Ignore plugins that are creating NPCs with no names (why the hell) + if (user.getName() != null) { + if (Anticheat.getManager().getConfiguration().getFileLogLevel() == 2 && type.getUses(user.getName()) % 10 == 0) { + Anticheat.getManager().fileLog(user.getName() + " has triggered multiple " + type + " checks."); + } + } + } + + public void resetCheck(CheckType type) { + USAGE_LIST.put(type, 0); + } + + public static int getCheats(CheckType type) { + int x = 0; + if (USAGE_LIST.get(type) != null) { + x = USAGE_LIST.get(type); + } + return x; + } + + private static void removeDecrease(User user) { + int x = 0; + // Ignore plugins that are creating NPCs with no names + if (user.getName() != null) { + if (DECREASE_LIST.get(user.getName()) != null) { + x = DECREASE_LIST.get(user.getName()); + x -= 2; + if (x < 0) { + x = 0; + } + } + DECREASE_LIST.put(user.getName(), x); + } + } + + public static void decrease(Player player) { + User user = getUserManager().getUser(player.getName()); + // Ignore plugins that are creating NPCs with no names + if (user.getName() != null) { + int x = 0; + if (DECREASE_LIST.get(user.getName()) != null) { + x = DECREASE_LIST.get(user.getName()); + } + x += 1; + DECREASE_LIST.put(user.getName(), x); + if (x >= 10) { + user.decreaseLevel(); + DECREASE_LIST.put(user.getName(), 0); + } + } + } + + public static CheckManager getCheckManager() { + return CHECK_MANAGER; + } + + public static AnticheatManager getManager() { + return Anticheat.getManager(); + } + + public static Backend getBackend() { + return BACKEND; + } + + public static UserManager getUserManager() { + return USER_MANAGER; + } + + public static Anticheat getPlugin() { + return PLUGIN; + } } diff --git a/src/main/java/net/h31ix/anticheat/event/InventoryListener.java b/src/main/java/net/h31ix/anticheat/event/InventoryListener.java index 8fb1951..fc9c705 100644 --- a/src/main/java/net/h31ix/anticheat/event/InventoryListener.java +++ b/src/main/java/net/h31ix/anticheat/event/InventoryListener.java @@ -27,34 +27,27 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.inventory.InventoryClickEvent; -public class InventoryListener extends EventListener{ - - private final Backend backend = getBackend(); - private final CheckManager checkManager = getCheckManager(); - private final Configuration config = Anticheat.getManager().getConfiguration(); - - @EventHandler - public void onInventoryClick(InventoryClickEvent event) - { - if (event.getWhoClicked() instanceof Player) - { - Player player = (Player) event.getWhoClicked(); - if(checkManager.willCheck(player, CheckType.FAST_INVENTORY)) - { - if(backend.checkInventoryClicks(player)) - { - if(!config.silentMode()) - { - event.setCancelled(!config.silentMode()); - player.setHealth(0); - } - log("tried to use their inventory too fast", player, CheckType.FAST_INVENTORY); - } - else - { - decrease(player); - } - } - } - } +public class InventoryListener extends EventListener { + + private final Backend backend = getBackend(); + private final CheckManager checkManager = getCheckManager(); + private final Configuration config = Anticheat.getManager().getConfiguration(); + + @EventHandler + public void onInventoryClick(InventoryClickEvent event) { + if (event.getWhoClicked() instanceof Player) { + Player player = (Player) event.getWhoClicked(); + if (checkManager.willCheck(player, CheckType.FAST_INVENTORY)) { + if (backend.checkInventoryClicks(player)) { + if (!config.silentMode()) { + event.setCancelled(!config.silentMode()); + player.setHealth(0); + } + log("tried to use their inventory too fast", player, CheckType.FAST_INVENTORY); + } else { + decrease(player); + } + } + } + } } diff --git a/src/main/java/net/h31ix/anticheat/event/PlayerListener.java b/src/main/java/net/h31ix/anticheat/event/PlayerListener.java index af85547..5b3ee61 100644 --- a/src/main/java/net/h31ix/anticheat/event/PlayerListener.java +++ b/src/main/java/net/h31ix/anticheat/event/PlayerListener.java @@ -42,400 +42,314 @@ import org.bukkit.event.player.*; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.inventory.PlayerInventory; -public class PlayerListener extends EventListener -{ - private final Backend backend = getBackend(); - private final CheckManager checkManager = getCheckManager(); - private final Configuration config = Anticheat.getManager().getConfiguration(); - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) - { - Player player = event.getPlayer(); - if (checkManager.willCheck(player, CheckType.SPAM) && config.commandSpam()) - { - backend.logChat(player); - if (backend.checkSpam(player, event.getMessage())) - { - event.setCancelled(!config.silentMode()); - player.sendMessage(ChatColor.RED + "Please do not spam."); - } - } - } - - @EventHandler - public void onPlayerToggleFlight(PlayerToggleFlightEvent event) - { - if (!event.isFlying()) - { - backend.logEnterExit(event.getPlayer()); - } - } - - @EventHandler - public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) - { - if (event.getNewGameMode() != GameMode.CREATIVE) - { - backend.logEnterExit(event.getPlayer()); - } - } - - @EventHandler - public void onProjectileLaunch(ProjectileLaunchEvent event) - { - if (event.getEntity().getShooter() instanceof Player) - { - Player player = (Player) event.getEntity().getShooter(); - - if (event.getEntity() instanceof Arrow) - { - return; - } - - if (checkManager.willCheck(player, CheckType.FAST_PROJECTILE) && backend.checkProjectile(player)) - { - event.setCancelled(!config.silentMode()); - log("tried to fire projectiles too fast.", player, CheckType.FAST_PROJECTILE); - } - } - } - - @EventHandler - public void onPlayerTeleport(PlayerTeleportEvent event) - { - if (event.getCause() == TeleportCause.ENDER_PEARL || event.getCause() == TeleportCause.PLUGIN) - { - backend.logTeleport(event.getPlayer()); - } - } - - @EventHandler - public void onPlayerChangeWorlds(PlayerChangedWorldEvent event) - { - backend.logTeleport(event.getPlayer()); - } - - @EventHandler - public void onPlayerToggleSneak(PlayerToggleSneakEvent event) - { - if (event.isSneaking()) - { - backend.logToggleSneak(event.getPlayer()); - } - } - - @EventHandler - public void onPlayerVelocity(PlayerVelocityEvent event) - { - Player player = event.getPlayer(); - if (checkManager.willCheck(player, CheckType.FLY) && checkManager.willCheck(player, CheckType.ZOMBE_FLY)) //@h31ix: Change if necessary. I'm not sure what perms should go here :3 - { - if (backend.justVelocity(player) && backend.extendVelocityTime(player)) - { - event.setCancelled(!config.silentMode()); - return; // don't log it lol. - } - backend.logVelocity(player); - } - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerChat(AsyncPlayerChatEvent event) - { - Player player = event.getPlayer(); - if (checkManager.willCheck(player, CheckType.SPAM) && config.chatSpam()) - { - backend.logChat(player); - if (backend.checkSpam(player, event.getMessage())) - { - boolean b = !config.silentMode(); - event.setCancelled(b); - if (b) - { - player.sendMessage(ChatColor.RED + config.getLang().getChatWarning()); - } - } - } - } - - @EventHandler - public void onPlayerKick(PlayerKickEvent event) - { - backend.clearChatLevel(event.getPlayer()); - backend.garbageClean(event.getPlayer()); - } - - @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) - { - backend.garbageClean(event.getPlayer()); - } - - @EventHandler - public void onPlayerToggleSprint(PlayerToggleSprintEvent event) - { - Player player = event.getPlayer(); - if (checkManager.willCheck(player, CheckType.SPRINT)) - { - if (backend.checkSprintHungry(event)) - { - event.setCancelled(!config.silentMode()); - log("tried to sprint while hungry.", player, CheckType.SPRINT); - } - else - { - decrease(player); - } - } - } - - @EventHandler - public void onPlayerInteract(PlayerInteractEvent event) - { - Player player = event.getPlayer(); - PlayerInventory inv = player.getInventory(); - if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) - { - Material m = inv.getItemInHand().getType(); - if (m == Material.BOW) - { - backend.logBowWindUp(player); - } - else if (Utilities.isFood(m)) - { - backend.logEatingStart(player); - } - } - Block block = event.getClickedBlock(); - - if (block != null) - { - Distance distance = new Distance(player.getLocation(), block.getLocation()); - backend.checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference()); - } - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerDropItem(PlayerDropItemEvent event) - { - Player player = event.getPlayer(); - if (checkManager.willCheck(player, CheckType.ITEM_SPAM) && backend.checkFastDrop(player)) - { - event.setCancelled(!config.silentMode()); - } - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerEnterBed(PlayerBedEnterEvent event) - { - backend.logEnterExit(event.getPlayer()); - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerExitBed(PlayerBedLeaveEvent event) - { - backend.logEnterExit(event.getPlayer()); - } - - @EventHandler - public void onPlayerAnimation(PlayerAnimationEvent event) - { - Player player = event.getPlayer(); - backend.logAnimation(player); - } - - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) - { - Player player = event.getPlayer(); - String section = "\u00a7"; - if (checkManager.willCheck(player, CheckType.ZOMBE_FLY)) - { - player.sendMessage(section + "f " + section + "f " + section + "1 " + section + "0 " + section + "2 " + section + "4"); - } - if (checkManager.willCheck(player, CheckType.ZOMBE_CHEAT)) - { - player.sendMessage(section + "f " + section + "f " + section + "2 " + section + "0 " + section + "4 " + section + "8"); - } - if (checkManager.willCheck(player, CheckType.ZOMBE_NOCLIP)) - { - player.sendMessage(section + "f " + section + "f " + section + "4 " + section + "0 " + section + "9 " + section + "6"); - } - backend.logJoin(player); - if (getUserManager().getUser(player.getName()) == null) - { - getUserManager().addUser(new User(player.getName())); - } - else - { - getUserManager().addUserFromFile(player.getName()); - } - if (player.hasMetadata(Anticheat.SPY_METADATA)) - { - for (Player p : player.getServer().getOnlinePlayers()) - { - if (!Permission.SYSTEM_SPY.get(p)) - { - p.hidePlayer(player); - } - } - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void checkExploit(PlayerMoveEvent event) - { - Player player = event.getPlayer(); - Location from = event.getFrom(); - Location to = event.getTo(); - Distance distance = new Distance(from, to); - double y = distance.getYDifference(); - backend.logAscension(player, from.getY(), to.getY()); - if (checkManager.willCheck(player, CheckType.SPEED) && backend.checkFreeze(player, from.getY(), to.getY())) - { - log("tried to freeze in mid-air.", player, CheckType.SPEED); - player.kickPlayer("Freezing client"); - } - if (checkManager.willCheck(player, CheckType.SPRINT)) - { - if (backend.checkSprintStill(player, from, to)) - { - event.setCancelled(!config.silentMode()); - log("tried to sprint while standing still.", player, CheckType.SPRINT); - } - } - if (checkManager.willCheck(player, CheckType.FLY) && !player.isFlying() && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && backend.checkFlight(player, distance)) - { - if (!config.silentMode()) - { - event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); - } - log("tried to fly.", player, CheckType.FLY); - } - if (checkManager.willCheck(player, CheckType.FLY) && !player.isFlying() && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && (backend.checkYAxis(player, distance) || backend.checkAscension(player, from.getY(), to.getY()))) - { - if (!config.silentMode()) - { - event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); - } - log("tried to fly on y-axis", player, CheckType.FLY); - } - if (checkManager.willCheck(player, CheckType.VCLIP) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY) && event.getFrom().getY() > event.getTo().getY()) - { - int result = backend.checkVClip(player, new Distance(event.getFrom(), event.getTo())); - - if (result > 0) - { - if (!config.silentMode()) - { - // You come back up, and you suddenly feel sick from trying to stick yourself through the blocks.. - Location newloc = new Location(player.getWorld(), event.getFrom().getX(), event.getFrom().getY() + result, event.getFrom().getZ()); - if (result > 3) - { - result = 3; // prevents players from using AC as a way to teleport to sky islands. - } - if (newloc.getBlock().getTypeId() == 0) - { - event.setTo(newloc); - } - else - { - event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); - } - player.damage(3); - } - log("tried to move down through a block.", player, CheckType.VCLIP); - } - } - if (checkManager.willCheck(player, CheckType.NOFALL) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && event.getFrom().getY() > event.getTo().getY() && backend.checkNoFall(player, y)) - { - if (!config.silentMode()) - { - event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); - player.damage(2); // I added this in here so the player(s) would still receive damage. - } - log("tried to avoid fall damage.", player, CheckType.NOFALL); - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void checkSpeed(PlayerMoveEvent event) - { - Player player = event.getPlayer(); - Location from = event.getFrom(); - Location to = event.getTo(); - boolean changed = false; - - if (event.getTo() != event.getFrom()) - { - Distance distance = new Distance(from, to); - double x = distance.getXDifference(); - double y = distance.getYDifference(); - double z = distance.getZDifference(); - if (checkManager.willCheck(player, CheckType.SPEED) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY)) - { - if (event.getFrom().getY() < event.getTo().getY() && backend.checkYSpeed(player, y)) - { - if (!config.silentMode()) - { - event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); - } - log("tried to ascend too fast.", player, CheckType.SPEED); - changed = true; - } - if (backend.checkXZSpeed(player, x, z)) - { - if (!config.silentMode()) - { - event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); - } - log("tried to move too fast.", player, CheckType.SPEED); - changed = true; - } - if ((event.getFrom().getX() != event.getTo().getX() || event.getFrom().getZ() != event.getTo().getZ()) && backend.checkTimer(player)) - { - if (!config.silentMode()) - { - event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); - } - log("tried to alter their timer.", player, CheckType.SPEED); - changed = true; - } - } - if (checkManager.willCheck(player, CheckType.WATER_WALK) && backend.checkWaterWalk(player, x, y, z)) - { - if (!config.silentMode()) - { - player.teleport(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(player.getLocation().add(0, -1, 0))); - } - log("tried to walk on water.", player, CheckType.WATER_WALK); - changed = true; - } - if (checkManager.willCheck(player, CheckType.SNEAK) && backend.checkSneak(player, x, z)) - { - if (!config.silentMode()) - { - event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); - player.setSneaking(false); - } - log("tried to sneak too fast.", player, CheckType.SNEAK); - changed = true; - } - if (checkManager.willCheck(player, CheckType.SPIDER) && backend.checkSpider(player, y)) - { - if (!config.silentMode()) - { - event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); - } - log("tried to climb a wall.", player, CheckType.SPIDER); - changed = true; - } - - if (!changed) - { - Anticheat.getManager().getUserManager().getUser(player.getName()).setGoodLocation(event.getFrom()); - } - } - } +public class PlayerListener extends EventListener { + private final Backend backend = getBackend(); + private final CheckManager checkManager = getCheckManager(); + private final Configuration config = Anticheat.getManager().getConfiguration(); + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { + Player player = event.getPlayer(); + if (checkManager.willCheck(player, CheckType.SPAM) && config.commandSpam()) { + backend.logChat(player); + if (backend.checkSpam(player, event.getMessage())) { + event.setCancelled(!config.silentMode()); + player.sendMessage(ChatColor.RED + "Please do not spam."); + } + } + } + + @EventHandler + public void onPlayerToggleFlight(PlayerToggleFlightEvent event) { + if (!event.isFlying()) { + backend.logEnterExit(event.getPlayer()); + } + } + + @EventHandler + public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) { + if (event.getNewGameMode() != GameMode.CREATIVE) { + backend.logEnterExit(event.getPlayer()); + } + } + + @EventHandler + public void onProjectileLaunch(ProjectileLaunchEvent event) { + if (event.getEntity().getShooter() instanceof Player) { + Player player = (Player) event.getEntity().getShooter(); + + if (event.getEntity() instanceof Arrow) { return; } + + if (checkManager.willCheck(player, CheckType.FAST_PROJECTILE) && backend.checkProjectile(player)) { + event.setCancelled(!config.silentMode()); + log("tried to fire projectiles too fast.", player, CheckType.FAST_PROJECTILE); + } + } + } + + @EventHandler + public void onPlayerTeleport(PlayerTeleportEvent event) { + if (event.getCause() == TeleportCause.ENDER_PEARL || event.getCause() == TeleportCause.PLUGIN) { + backend.logTeleport(event.getPlayer()); + } + } + + @EventHandler + public void onPlayerChangeWorlds(PlayerChangedWorldEvent event) { + backend.logTeleport(event.getPlayer()); + } + + @EventHandler + public void onPlayerToggleSneak(PlayerToggleSneakEvent event) { + if (event.isSneaking()) { + backend.logToggleSneak(event.getPlayer()); + } + } + + @EventHandler + public void onPlayerVelocity(PlayerVelocityEvent event) { + Player player = event.getPlayer(); + if (checkManager.willCheck(player, CheckType.FLY) && checkManager.willCheck(player, CheckType.ZOMBE_FLY)) // @h31ix: Change if necessary. I'm not sure what perms should go here :3 + { + if (backend.justVelocity(player) && backend.extendVelocityTime(player)) { + event.setCancelled(!config.silentMode()); + return; // don't log it lol. + } + backend.logVelocity(player); + } + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerChat(AsyncPlayerChatEvent event) { + Player player = event.getPlayer(); + if (checkManager.willCheck(player, CheckType.SPAM) && config.chatSpam()) { + backend.logChat(player); + if (backend.checkSpam(player, event.getMessage())) { + boolean b = !config.silentMode(); + event.setCancelled(b); + if (b) { + player.sendMessage(ChatColor.RED + config.getLang().getChatWarning()); + } + } + } + } + + @EventHandler + public void onPlayerKick(PlayerKickEvent event) { + backend.clearChatLevel(event.getPlayer()); + backend.garbageClean(event.getPlayer()); + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent event) { + backend.garbageClean(event.getPlayer()); + } + + @EventHandler + public void onPlayerToggleSprint(PlayerToggleSprintEvent event) { + Player player = event.getPlayer(); + if (checkManager.willCheck(player, CheckType.SPRINT)) { + if (backend.checkSprintHungry(event)) { + event.setCancelled(!config.silentMode()); + log("tried to sprint while hungry.", player, CheckType.SPRINT); + } else { + decrease(player); + } + } + } + + @EventHandler + public void onPlayerInteract(PlayerInteractEvent event) { + Player player = event.getPlayer(); + PlayerInventory inv = player.getInventory(); + if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { + Material m = inv.getItemInHand().getType(); + if (m == Material.BOW) { + backend.logBowWindUp(player); + } else if (Utilities.isFood(m)) { + backend.logEatingStart(player); + } + } + Block block = event.getClickedBlock(); + + if (block != null) { + Distance distance = new Distance(player.getLocation(), block.getLocation()); + backend.checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference()); + } + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerDropItem(PlayerDropItemEvent event) { + Player player = event.getPlayer(); + if (checkManager.willCheck(player, CheckType.ITEM_SPAM) && backend.checkFastDrop(player)) { + event.setCancelled(!config.silentMode()); + } + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerEnterBed(PlayerBedEnterEvent event) { + backend.logEnterExit(event.getPlayer()); + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerExitBed(PlayerBedLeaveEvent event) { + backend.logEnterExit(event.getPlayer()); + } + + @EventHandler + public void onPlayerAnimation(PlayerAnimationEvent event) { + Player player = event.getPlayer(); + backend.logAnimation(player); + } + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + String section = "\u00a7"; + if (checkManager.willCheck(player, CheckType.ZOMBE_FLY)) { + player.sendMessage(section + "f " + section + "f " + section + "1 " + section + "0 " + section + "2 " + section + "4"); + } + if (checkManager.willCheck(player, CheckType.ZOMBE_CHEAT)) { + player.sendMessage(section + "f " + section + "f " + section + "2 " + section + "0 " + section + "4 " + section + "8"); + } + if (checkManager.willCheck(player, CheckType.ZOMBE_NOCLIP)) { + player.sendMessage(section + "f " + section + "f " + section + "4 " + section + "0 " + section + "9 " + section + "6"); + } + backend.logJoin(player); + if (getUserManager().getUser(player.getName()) == null) { + getUserManager().addUser(new User(player.getName())); + } else { + getUserManager().addUserFromFile(player.getName()); + } + if (player.hasMetadata(Anticheat.SPY_METADATA)) { + for (Player p : player.getServer().getOnlinePlayers()) { + if (!Permission.SYSTEM_SPY.get(p)) { + p.hidePlayer(player); + } + } + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void checkExploit(PlayerMoveEvent event) { + Player player = event.getPlayer(); + Location from = event.getFrom(); + Location to = event.getTo(); + Distance distance = new Distance(from, to); + double y = distance.getYDifference(); + backend.logAscension(player, from.getY(), to.getY()); + if (checkManager.willCheck(player, CheckType.SPEED) && backend.checkFreeze(player, from.getY(), to.getY())) { + log("tried to freeze in mid-air.", player, CheckType.SPEED); + player.kickPlayer("Freezing client"); + } + if (checkManager.willCheck(player, CheckType.SPRINT)) { + if (backend.checkSprintStill(player, from, to)) { + event.setCancelled(!config.silentMode()); + log("tried to sprint while standing still.", player, CheckType.SPRINT); + } + } + if (checkManager.willCheck(player, CheckType.FLY) && !player.isFlying() && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && backend.checkFlight(player, distance)) { + if (!config.silentMode()) { + event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); + } + log("tried to fly.", player, CheckType.FLY); + } + if (checkManager.willCheck(player, CheckType.FLY) && !player.isFlying() && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && (backend.checkYAxis(player, distance) || backend.checkAscension(player, from.getY(), to.getY()))) { + if (!config.silentMode()) { + event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); + } + log("tried to fly on y-axis", player, CheckType.FLY); + } + if (checkManager.willCheck(player, CheckType.VCLIP) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY) && event.getFrom().getY() > event.getTo().getY()) { + int result = backend.checkVClip(player, new Distance(event.getFrom(), event.getTo())); + + if (result > 0) { + if (!config.silentMode()) { + // You come back up, and you suddenly feel sick from trying to stick yourself through the blocks.. + Location newloc = new Location(player.getWorld(), event.getFrom().getX(), event.getFrom().getY() + result, event.getFrom().getZ()); + if (result > 3) { + result = 3; // prevents players from using AC as a way to teleport to sky islands. + } + if (newloc.getBlock().getTypeId() == 0) { + event.setTo(newloc); + } else { + event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); + } + player.damage(3); + } + log("tried to move down through a block.", player, CheckType.VCLIP); + } + } + if (checkManager.willCheck(player, CheckType.NOFALL) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && event.getFrom().getY() > event.getTo().getY() && backend.checkNoFall(player, y)) { + if (!config.silentMode()) { + event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); + player.damage(2); // I added this in here so the player(s) would still receive damage. + } + log("tried to avoid fall damage.", player, CheckType.NOFALL); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void checkSpeed(PlayerMoveEvent event) { + Player player = event.getPlayer(); + Location from = event.getFrom(); + Location to = event.getTo(); + boolean changed = false; + + if (event.getTo() != event.getFrom()) { + Distance distance = new Distance(from, to); + double x = distance.getXDifference(); + double y = distance.getYDifference(); + double z = distance.getZDifference(); + if (checkManager.willCheck(player, CheckType.SPEED) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY)) { + if (event.getFrom().getY() < event.getTo().getY() && backend.checkYSpeed(player, y)) { + if (!config.silentMode()) { + event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); + } + log("tried to ascend too fast.", player, CheckType.SPEED); + changed = true; + } + if (backend.checkXZSpeed(player, x, z)) { + if (!config.silentMode()) { + event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); + } + log("tried to move too fast.", player, CheckType.SPEED); + changed = true; + } + if ((event.getFrom().getX() != event.getTo().getX() || event.getFrom().getZ() != event.getTo().getZ()) && backend.checkTimer(player)) { + if (!config.silentMode()) { + event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); + } + log("tried to alter their timer.", player, CheckType.SPEED); + changed = true; + } + } + if (checkManager.willCheck(player, CheckType.WATER_WALK) && backend.checkWaterWalk(player, x, y, z)) { + if (!config.silentMode()) { + player.teleport(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(player.getLocation().add(0, -1, 0))); + } + log("tried to walk on water.", player, CheckType.WATER_WALK); + changed = true; + } + if (checkManager.willCheck(player, CheckType.SNEAK) && backend.checkSneak(player, x, z)) { + if (!config.silentMode()) { + event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); + player.setSneaking(false); + } + log("tried to sneak too fast.", player, CheckType.SNEAK); + changed = true; + } + if (checkManager.willCheck(player, CheckType.SPIDER) && backend.checkSpider(player, y)) { + if (!config.silentMode()) { + event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); + } + log("tried to climb a wall.", player, CheckType.SPIDER); + changed = true; + } + + if (!changed) { + Anticheat.getManager().getUserManager().getUser(player.getName()).setGoodLocation(event.getFrom()); + } + } + } } diff --git a/src/main/java/net/h31ix/anticheat/event/VehicleListener.java b/src/main/java/net/h31ix/anticheat/event/VehicleListener.java index 6d7461b..cb37c82 100644 --- a/src/main/java/net/h31ix/anticheat/event/VehicleListener.java +++ b/src/main/java/net/h31ix/anticheat/event/VehicleListener.java @@ -24,25 +24,20 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.vehicle.VehicleExitEvent; -public class VehicleListener extends EventListener -{ - private final Backend backend = getBackend(); - - @EventHandler(ignoreCancelled = true) - public void onVehicleEnter(VehicleEnterEvent event) - { - if (event.getEntered() instanceof Player) - { - backend.logEnterExit((Player) event.getEntered()); - } - } - - @EventHandler(ignoreCancelled = true) - public void onVehicleExit(VehicleExitEvent event) - { - if (event.getExited() instanceof Player) - { - backend.logEnterExit((Player) event.getExited()); - } - } +public class VehicleListener extends EventListener { + private final Backend backend = getBackend(); + + @EventHandler(ignoreCancelled = true) + public void onVehicleEnter(VehicleEnterEvent event) { + if (event.getEntered() instanceof Player) { + backend.logEnterExit((Player) event.getEntered()); + } + } + + @EventHandler(ignoreCancelled = true) + public void onVehicleExit(VehicleExitEvent event) { + if (event.getExited() instanceof Player) { + backend.logEnterExit((Player) event.getExited()); + } + } } diff --git a/src/main/java/net/h31ix/anticheat/manage/AnticheatManager.java b/src/main/java/net/h31ix/anticheat/manage/AnticheatManager.java index 3336852..69b8852 100644 --- a/src/main/java/net/h31ix/anticheat/manage/AnticheatManager.java +++ b/src/main/java/net/h31ix/anticheat/manage/AnticheatManager.java @@ -37,121 +37,98 @@ import org.bukkit.ChatColor; * The internal hub for all managers. */ -public class AnticheatManager -{ - private Anticheat plugin = null; - private Configuration configuration; - private XRayTracker xrayTracker = null; - private UserManager userManager = null; - private CheckManager checkManager = null; - private Backend backend = null; - private final Logger fileLogger; - private static List logs = new CopyOnWriteArrayList(); - private static Handler fileHandler; - private static final int LOG_LEVEL_HIGH = 3; - - public AnticheatManager(Anticheat instance, Logger logger) - { - plugin = instance; - // now load all the others!!!!! - fileLogger = Logger.getLogger("net.h31ix.anticheat.Anticheat"); - configuration = new Configuration(this); - xrayTracker = new XRayTracker(); - userManager = new UserManager(configuration); - checkManager = new CheckManager(this); - backend = new Backend(this); - try - { - File file = new File(plugin.getDataFolder() + "/log"); - if (!file.exists()) - { - file.mkdir(); - } - fileHandler = new FileHandler(plugin.getDataFolder() + "/log/anticheat.log", true); - fileHandler.setFormatter(new FileFormatter()); - } - catch (Exception ex) - { - logger.log(Level.SEVERE, null, ex); - } - fileLogger.setUseParentHandlers(false); - fileLogger.addHandler(fileHandler); - } - - public void log(String message) - { - log(message, 0); - } - - public void log(String message, int i) - { - if (getConfiguration().logConsole()) - { - Bukkit.getConsoleSender().sendMessage(ChatColor.RED+message); - } - if(i == 0 && getConfiguration().getFileLogLevel() == LOG_LEVEL_HIGH) // Not an alert, normal log message - { - fileLog(message); - } - else if(getConfiguration().getFileLogLevel() != 0)// alert - { - fileLog(message); - } - logs.add(ChatColor.stripColor(message)); - } - - public void fileLog(String message) - { - fileLogger.info(message); - } - - public List getLastLogs() - { - List log = new CopyOnWriteArrayList(); - if (logs.size() < 30) - { - return logs; - } - for(int i = logs.size()-1; i >= 0; i--) - { - log.add(logs.get(i)); - } - logs.clear(); - return log; - } - - public Anticheat getPlugin() - { - return plugin; - } - - public Configuration getConfiguration() - { - return configuration; - } - - public XRayTracker getXRayTracker() - { - return xrayTracker; - } - - public UserManager getUserManager() - { - return userManager; - } - - public CheckManager getCheckManager() - { - return checkManager; - } - - public Backend getBackend() - { - return backend; - } - - public static void close() - { - fileHandler.close(); - } +public class AnticheatManager { + private Anticheat plugin = null; + private Configuration configuration; + private XRayTracker xrayTracker = null; + private UserManager userManager = null; + private CheckManager checkManager = null; + private Backend backend = null; + private final Logger fileLogger; + private static List logs = new CopyOnWriteArrayList(); + private static Handler fileHandler; + private static final int LOG_LEVEL_HIGH = 3; + + public AnticheatManager(Anticheat instance, Logger logger) { + plugin = instance; + // now load all the others!!!!! + fileLogger = Logger.getLogger("net.h31ix.anticheat.Anticheat"); + configuration = new Configuration(this); + xrayTracker = new XRayTracker(); + userManager = new UserManager(configuration); + checkManager = new CheckManager(this); + backend = new Backend(this); + try { + File file = new File(plugin.getDataFolder() + "/log"); + if (!file.exists()) { + file.mkdir(); + } + fileHandler = new FileHandler(plugin.getDataFolder() + "/log/anticheat.log", true); + fileHandler.setFormatter(new FileFormatter()); + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + } + fileLogger.setUseParentHandlers(false); + fileLogger.addHandler(fileHandler); + } + + public void log(String message) { + log(message, 0); + } + + public void log(String message, int i) { + if (getConfiguration().logConsole()) { + Bukkit.getConsoleSender().sendMessage(ChatColor.RED + message); + } + if (i == 0 && getConfiguration().getFileLogLevel() == LOG_LEVEL_HIGH) // Not an alert, normal log message + { + fileLog(message); + } else if (getConfiguration().getFileLogLevel() != 0)// alert + { + fileLog(message); + } + logs.add(ChatColor.stripColor(message)); + } + + public void fileLog(String message) { + fileLogger.info(message); + } + + public List getLastLogs() { + List log = new CopyOnWriteArrayList(); + if (logs.size() < 30) { return logs; } + for (int i = logs.size() - 1; i >= 0; i--) { + log.add(logs.get(i)); + } + logs.clear(); + return log; + } + + public Anticheat getPlugin() { + return plugin; + } + + public Configuration getConfiguration() { + return configuration; + } + + public XRayTracker getXRayTracker() { + return xrayTracker; + } + + public UserManager getUserManager() { + return userManager; + } + + public CheckManager getCheckManager() { + return checkManager; + } + + public Backend getBackend() { + return backend; + } + + public static void close() { + fileHandler.close(); + } } diff --git a/src/main/java/net/h31ix/anticheat/manage/Backend.java b/src/main/java/net/h31ix/anticheat/manage/Backend.java index a6c900c..fd437bd 100644 --- a/src/main/java/net/h31ix/anticheat/manage/Backend.java +++ b/src/main/java/net/h31ix/anticheat/manage/Backend.java @@ -42,1351 +42,997 @@ import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerToggleSprintEvent; import org.bukkit.potion.PotionEffectType; -public class Backend -{ - private List isInWater = new ArrayList(); - private List isInWaterCache = new ArrayList(); - private List isAscending = new ArrayList(); - private Map ascensionCount = new HashMap(); - private Map oldMessage = new HashMap(); - private Map lastMessage = new HashMap(); - private Map blocksOverFlight = new HashMap(); - private Map chatLevel = new HashMap(); - private Map chatKicks = new HashMap(); - private Map nofallViolation = new HashMap(); - private Map speedViolation = new HashMap(); - private Map fastBreakViolation = new HashMap(); - private Map yAxisViolations = new HashMap(); - private Map yAxisLastViolation = new HashMap(); - private Map lastYcoord = new HashMap(); - private Map lastYtime = new HashMap(); - private Map fastBreaks = new HashMap(); - private Map blockBreakHolder = new HashMap(); - private Map lastBlockBroken = new HashMap(); - private Map fastPlaceViolation = new HashMap(); - private Map lastZeroHitPlace = new HashMap(); - private Map lastBlockPlaced = new HashMap(); - private Map lastBlockPlaceTime = new HashMap(); - private Map blockPunches = new HashMap(); - private Map waterAscensionViolation = new HashMap(); - private Map waterSpeedViolation = new HashMap(); - private Map projectilesShot = new HashMap(); - private Map velocitized = new HashMap(); - private Map velocitytrack = new HashMap(); - private Map animated = new HashMap(); - private Map startEat = new HashMap(); - private Map lastHeal = new HashMap(); - private Map projectileTime = new HashMap(); - private Map bowWindUp = new HashMap(); - private Map instantBreakExempt = new HashMap(); - private Map sprinted = new HashMap(); - private Map brokenBlock = new HashMap(); - private Map placedBlock = new HashMap(); - private Map movingExempt = new HashMap(); - private Map blockTime = new HashMap(); - private Map blocksDropped = new HashMap(); - private Map lastInventoryTime = new HashMap(); - private Map inventoryTime = new HashMap(); - private Map inventoryClicks = new HashMap(); - private Map itemInHand = new HashMap(); - private Map steps = new HashMap(); - private Map stepTime = new HashMap(); - private HashSet transparent = new HashSet(); - private Map lastFallPacket = new HashMap(); - - private Magic magic; - private AnticheatManager micromanage = null; - private Language lang = null; - - public Backend(AnticheatManager instance) - { - magic = new Magic(instance.getConfiguration().getMagic(), instance.getConfiguration(), CommentedConfiguration.loadConfiguration(instance.getPlugin().getResource("magic.yml"))); - micromanage = instance; - lang = micromanage.getConfiguration().getLang(); - transparent.add((byte) -1); - } - - public void garbageClean(Player player) - { - String pN = player.getName(); - User user = micromanage.getUserManager().getUser(pN); - if (user != null) - { - micromanage.getUserManager().remove(user); - } - blocksDropped.remove(pN); - blockTime.remove(pN); - movingExempt.remove(pN); - brokenBlock.remove(pN); - placedBlock.remove(pN); - bowWindUp.remove(pN); - startEat.remove(pN); - lastHeal.remove(pN); - sprinted.remove(pN); - isInWater.remove(pN); - isInWaterCache.remove(pN); - instantBreakExempt.remove(pN); - isAscending.remove(pN); - ascensionCount.remove(pN); - oldMessage.remove(pN); - lastMessage.remove(pN); - blocksOverFlight.remove(pN); - chatLevel.remove(pN); - nofallViolation.remove(pN); - fastBreakViolation.remove(pN); - yAxisViolations.remove(pN); - yAxisLastViolation.remove(pN); - lastYcoord.remove(pN); - lastYtime.remove(pN); - fastBreaks.remove(pN); - blockBreakHolder.remove(pN); - lastBlockBroken.remove(pN); - fastPlaceViolation.remove(pN); - lastZeroHitPlace.remove(pN); - lastBlockPlaced.remove(pN); - lastBlockPlaceTime.remove(pN); - blockPunches.remove(pN); - waterAscensionViolation.remove(pN); - waterSpeedViolation.remove(pN); - projectilesShot.remove(pN); - velocitized.remove(pN); - velocitytrack.remove(pN); - animated.remove(pN); - startEat.remove(pN); - lastHeal.remove(pN); - projectileTime.remove(pN); - bowWindUp.remove(pN); - instantBreakExempt.remove(pN); - sprinted.remove(pN); - brokenBlock.remove(pN); - placedBlock.remove(pN); - movingExempt.remove(pN); - blockTime.remove(pN); - blocksDropped.remove(pN); - lastInventoryTime.remove(pN); - inventoryTime.remove(pN); - inventoryClicks.remove(pN); - lastFallPacket.remove(pN); - } - - public boolean checkFreeze(Player player, double from, double to) - { - // TODO: Fix! This is causing false-positives - /*if((from-to) > 0) - { - boolean flag = false; - if(lastFallPacket.containsKey(player.getName()) && lastFallPacket.get(player.getName()) > 0) - { - flag = (System.currentTimeMillis()-lastFallPacket.get(player.getName())) > 1000; - } - lastFallPacket.put(player.getName(), System.currentTimeMillis()); - return flag; - } - else - { - lastFallPacket.put(player.getName(), -1L); - }*/ - return false; - } - - public boolean checkFastBow(Player player, float force) - { - // Ignore magic numbers here, they are minecrafty vanilla stuff. - int ticks = (int) ((((System.currentTimeMillis() - bowWindUp.get(player.getName())) * 20) / 1000) + 3); - bowWindUp.remove(player.getName()); - float f = (float) ticks / 20.0F; - f = (f * f + f * 2.0F) / 3.0F; - f = f > 1.0F ? 1.0F : f; - return Math.abs(force - f) > magic.BOW_ERROR; - } - - public boolean checkProjectile(Player player) - { - increment(player, projectilesShot, 10); - if (!projectileTime.containsKey(player.getName())) - { - projectileTime.put(player.getName(), System.currentTimeMillis()); - return false; - } - else if (projectilesShot.get(player.getName()) == magic.PROJECTILE_CHECK) - { - long time = System.currentTimeMillis() - projectileTime.get(player.getName()); - projectileTime.remove(player.getName()); - projectilesShot.remove(player.getName()); - return time < magic.PROJECTILE_TIME_MIN; - } - return false; - } - - public boolean checkFastDrop(Player player) - { - increment(player, blocksDropped, 10); - if (!blockTime.containsKey(player.getName())) - { - blockTime.put(player.getName(), System.currentTimeMillis()); - return false; - } - else if (blocksDropped.get(player.getName()) == magic.DROP_CHECK) - { - long time = System.currentTimeMillis() - blockTime.get(player.getName()); - blockTime.remove(player.getName()); - blocksDropped.remove(player.getName()); - return time < magic.DROP_TIME_MIN; - } - return false; - } - - public boolean checkLongReachBlock(Player player, double x, double y, double z) - { - if (isInstantBreakExempt(player)) - { - return false; - } - else - { - return (x >= magic.BLOCK_MAX_DISTANCE || y > magic.BLOCK_MAX_DISTANCE || z > magic.BLOCK_MAX_DISTANCE); - } - } - - public boolean checkLongReachDamage(double x, double y, double z) - { - return x >= magic.ENTITY_MAX_DISTANCE || y > magic.ENTITY_MAX_DISTANCE || z > magic.ENTITY_MAX_DISTANCE; - } - - public boolean checkSpider(Player player, double y) - { - if (y <= magic.LADDER_Y_MAX && y >= magic.LADDER_Y_MIN && !Utilities.isClimbableBlock(player.getLocation().getBlock())) - { - return true; - } - return false; - } - - public boolean checkYSpeed(Player player, double y) - { - if (!player.isInsideVehicle() && !player.isSleeping() && y > magic.Y_SPEED_MAX && !isDoing(player, velocitized, magic.VELOCITY_TIME) && !player.hasPotionEffect(PotionEffectType.JUMP)) - { - return true; - } - return false; - } - - public boolean checkNoFall(Player player, double y) - { - String name = player.getName(); - if (player.getGameMode() != GameMode.CREATIVE && !player.isInsideVehicle() && !player.isSleeping() && !isMovingExempt(player) && !justPlaced(player) && !Utilities.isInWater(player)) - { - if (player.getFallDistance() == 0) - { - if (nofallViolation.get(name) == null) - { - nofallViolation.put(name, 1); - } - else - { - nofallViolation.put(name, nofallViolation.get(player.getName()) + 1); - } - - if (nofallViolation.get(name) >= magic.NOFALL_LIMIT) - { - nofallViolation.put(player.getName(), 1); - return true; - } - else - { - return false; - } - } - else - { - nofallViolation.put(name, 0); - return false; - } - } - return false; - } - - public boolean checkXZSpeed(Player player, double x, double z) - { - if (!isSpeedExempt(player) && player.getVehicle() == null) - { - boolean speed = false; - if (player.getLocation().getBlock().getType() == Material.SOUL_SAND) - { - if (player.isSprinting()) - { - speed = x > magic.XZ_SPEED_MAX_SOULSAND_SPRINT || z > magic.XZ_SPEED_MAX_SOULSAND_SPRINT; - } - else - { - speed = x > magic.XZ_SPEED_MAX_SOULSAND || z > magic.XZ_SPEED_MAX_SOULSAND; - } - } - else if (player.isFlying()) - { - speed = x > magic.XZ_SPEED_MAX_FLY || z > magic.XZ_SPEED_MAX_FLY; - } - else if (player.hasPotionEffect(PotionEffectType.SPEED)) - { - speed = x > magic.XZ_SPEED_MAX_POTION || z > magic.XZ_SPEED_MAX_POTION; - } - else if (player.isSprinting()) - { - speed = x > magic.XZ_SPEED_MAX_SPRINT || z > magic.XZ_SPEED_MAX_SPRINT; - } - else - { - speed = x > magic.XZ_SPEED_MAX || z > magic.XZ_SPEED_MAX; - } - if (speed) - { - int num = this.increment(player, speedViolation, magic.SPEED_MAX); - return num >= magic.SPEED_MAX; - } - else - { - speedViolation.put(player.getName(), 0); - return false; - } - } - else - { - return false; - } - } - - public boolean checkSneak(Player player, double x, double z) - { - if (player.isSneaking() && !player.isFlying() && !isMovingExempt(player)) - { - return x > magic.XZ_SPEED_MAX_SNEAK || z > magic.XZ_SPEED_MAX_SNEAK; - } - else - { - return false; - } - } - - public boolean checkSprintHungry(PlayerToggleSprintEvent event) - { - Player player = event.getPlayer(); - if (event.isSprinting()) - { - return player.getFoodLevel() <= magic.SPRINT_FOOD_MIN && player.getGameMode() != GameMode.CREATIVE; - } - else - { - return false; - } - } - - public boolean checkSprintStill(Player player, Location from, Location to) - { - return !isMovingExempt(player) && player.isSprinting() && from.getX() == to.getX() && from.getZ() == to.getZ(); - } - - public boolean checkWaterWalk(Player player, double x, double y, double z) - { - Block block = player.getLocation().getBlock(); - - if (player.getVehicle() == null && !player.isFlying()) - { - if (block.isLiquid()) - { - if (isInWater.contains(player.getName())) - { - if (isInWaterCache.contains(player.getName())) - { - if (player.getNearbyEntities(1, 1, 1).isEmpty()) - { - boolean b = false; - if (!Utilities.sprintFly(player) && x > magic.XZ_SPEED_MAX_WATER || z > magic.XZ_SPEED_MAX_WATER) - { - b = true; - } - else if (x > magic.XZ_SPEED_MAX_WATER_SPRINT || z > magic.XZ_SPEED_MAX_WATER_SPRINT) - { - b = true; - } - else if (!Utilities.isFullyInWater(player.getLocation()) && Utilities.isHoveringOverWater(player.getLocation(), 1) && y == 0D && !block.getType().equals(Material.WATER_LILY)) - { - b = true; - } - if (b) - { - if (waterSpeedViolation.containsKey(player.getName())) - { - int v = waterSpeedViolation.get(player.getName()); - if (v >= magic.WATER_SPEED_VIOLATION_MAX) - { - waterSpeedViolation.put(player.getName(), 0); - return true; - } - else - { - waterSpeedViolation.put(player.getName(), v + 1); - } - } - else - { - waterSpeedViolation.put(player.getName(), 1); - } - } - } - } - else - { - isInWaterCache.add(player.getName()); - return false; - } - } - else - { - isInWater.add(player.getName()); - return false; - } - } - else if (block.getRelative(BlockFace.DOWN).isLiquid() && isAscending(player) && Utilities.cantStandAt(block) && Utilities.cantStandAt(block.getRelative(BlockFace.DOWN))) - { - if (waterAscensionViolation.containsKey(player.getName())) - { - int v = waterAscensionViolation.get(player.getName()); - if (v >= magic.WATER_ASCENSION_VIOLATION_MAX) - { - waterAscensionViolation.put(player.getName(), 0); - return true; - } - else - { - waterAscensionViolation.put(player.getName(), v + 1); - return true; - } - } - else - { - waterAscensionViolation.put(player.getName(), 1); - } - } - else - { - isInWater.remove(player.getName()); - isInWaterCache.remove(player.getName()); - } - } - return false; - } - - // The first check in Anticheat with a integer as a result :O! - - public int checkVClip(Player player, Distance distance) - { - double from = Math.round(distance.fromY()); - double to = Math.round(distance.toY()); - - boolean bs = false; - - if (player.isInsideVehicle()) - { - return 0; - } - if (from == to || from < to) - { - return 0; - } - if (Math.round(distance.getYDifference()) < 2) - { - return 0; - } - - for (int i = 0; i < (Math.round(distance.getYDifference())) + 1; i++) - { - Block block = new Location(player.getWorld(), player.getLocation().getX(), to + i, player.getLocation().getZ()).getBlock(); - if (block.getTypeId() != 0 && block.getType().isSolid()) - { - bs = true; - } - if (bs) - { - return (int) from + 3; - } - } - - return 0; - } - - public boolean checkYAxis(Player player, Distance distance) - { - if (distance.getYDifference() > 400 || distance.getYDifference() < 0) - { - return false; - } - if (!isMovingExempt(player) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && !Utilities.isClimbableBlock(player.getLocation().add(0, -1, 0).getBlock()) && !player.isInsideVehicle() && !Utilities.isInWater(player)) - { - double y1 = player.getLocation().getY(); - String name = player.getName(); - //Fix Y axis spam. - if (!lastYcoord.containsKey(name) || !lastYtime.containsKey(name) || !yAxisLastViolation.containsKey(name) || !yAxisLastViolation.containsKey(name)) - { - lastYcoord.put(name, y1); - yAxisViolations.put(name, 0); - yAxisLastViolation.put(name, 0L); - lastYtime.put(name, System.currentTimeMillis()); - } - else - { - if (y1 > lastYcoord.get(name) && yAxisViolations.get(name) > magic.Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) < magic.Y_MAXVIOTIME) - { - Location g = player.getLocation(); - g.setY(lastYcoord.get(name)); - player.sendMessage(ChatColor.RED + "[AntiCheat] Fly hacking on the y-axis detected. Please wait 5 seconds to prevent getting damage."); - yAxisViolations.put(name, yAxisViolations.get(name) + 1); - yAxisLastViolation.put(name, System.currentTimeMillis()); - if (g.getBlock().getTypeId() == 0) - { - player.teleport(g); - } - return true; - } - else - { - if (yAxisViolations.get(name) > magic.Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) > magic.Y_MAXVIOTIME) - { - yAxisViolations.put(name, 0); - yAxisLastViolation.put(name, 0L); - } - } - if ((y1 - lastYcoord.get(name)) > magic.Y_MAXDIFF && (System.currentTimeMillis() - lastYtime.get(name)) < magic.Y_TIME) - { - Location g = player.getLocation(); - g.setY(lastYcoord.get(name)); - yAxisViolations.put(name, yAxisViolations.get(name) + 1); - yAxisLastViolation.put(name, System.currentTimeMillis()); - if (g.getBlock().getTypeId() == 0) - { - player.teleport(g); - } - return true; - } - else - { - if ((y1 - lastYcoord.get(name)) > magic.Y_MAXDIFF + 1 || (System.currentTimeMillis() - lastYtime.get(name)) > magic.Y_TIME) - { - lastYtime.put(name, System.currentTimeMillis()); - lastYcoord.put(name, y1); - } - } - } - } - //Fix Y axis spam - return false; - } - - public boolean checkTimer(Player player) - { - String name = player.getName(); - int step = 1; - if (steps.containsKey(name)) - { - step = steps.get(name) + 1; - } - if (step == 1) - { - stepTime.put(name, System.currentTimeMillis()); - } - increment(player, steps, step); - if (step == magic.TIMER_STEP_CHECK) - { - long time = System.currentTimeMillis() - stepTime.get(name); - steps.put(name, 0); - return time < magic.TIMER_TIMEMIN; - } - return false; - } - - public boolean checkSight(Player player, Entity entity) - { - if (entity instanceof LivingEntity) - { - LivingEntity le = (LivingEntity) entity; - // Check to make sure the entity's head is not surrounded - Block head = le.getWorld().getBlockAt((int) le.getLocation().getX(), (int) (le.getLocation().getY() + le.getEyeHeight()), (int) le.getLocation().getZ()); - boolean solid = false; - //TODO: This sucks. See if it's possible to not have as many false-positives while still retaining most of the check. - for (int x = -2; x <= 2; x++) - { - for (int z = -2; z <= 2; z++) - { - for (int y = -1; y < 2; y++) - { - if (head.getRelative(x, y, z).getTypeId() != 0) - { - if (head.getRelative(x, y, z).getType().isSolid()) - { - solid = true; - break; - } - - } - } - } - - } - if (solid) - { - return true; - } - // TODO: Needs proper testing - Location mobLocation = le.getEyeLocation(); - for (Block block : player.getLineOfSight(transparent, 5)) - { - if (Math.abs(block.getLocation().getX() - mobLocation.getX()) < 2.3 || Math.abs(block.getLocation().getZ() - mobLocation.getZ()) < 2.3) - { - - return true; - } - } - return false; - } - return true; - } - - public boolean checkFlight(Player player, Distance distance) - { - if (distance.getYDifference() > 400) - { - //This was a teleport, so we don't care about it. - return false; - } - String name = player.getName(); - double y1 = distance.fromY(); - double y2 = distance.toY(); - //Check if the player is climbing up water. - /* if (block.getRelative(BlockFace.NORTH).isLiquid() || block.getRelative(BlockFace.SOUTH).isLiquid() || block.getRelative(BlockFace.EAST).isLiquid() || block.getRelative(BlockFace.WEST).isLiquid()) - { - if (y1 < y2) - { - //Even if they are using a hacked client and flying next to water to abuse this, they can't be go past the speed limit so they might as well swim - return distance.getYDifference() > magic.WATER_CLIMB_MAX; - } - } */ - - if (!isMovingExempt(player) && !Utilities.isHoveringOverWater(player.getLocation(), 1) && Utilities.cantStandAtExp(player.getLocation())) - { - /* if (y1 == y2 || y1 < y2) - { - - if (y1 == y2) - { - //Check if the player is on slabs or crouching on stairs - if (Utilities.isSlab(block.getRelative(BlockFace.NORTH)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH)) || Utilities.isSlab(block.getRelative(BlockFace.EAST)) || Utilities.isSlab(block.getRelative(BlockFace.WEST)) || Utilities.isSlab(block.getRelative(BlockFace.NORTH_EAST)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH_EAST)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH_WEST)) || Utilities.isSlab(block.getRelative(BlockFace.NORTH_WEST))) - { - return false; - } - else if (player.isSneaking() && (Utilities.isStair(block.getRelative(BlockFace.NORTH)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH)) || Utilities.isStair(block.getRelative(BlockFace.EAST)) || Utilities.isStair(block.getRelative(BlockFace.WEST)) || Utilities.isStair(block.getRelative(BlockFace.NORTH_EAST)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH_EAST)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH_WEST)) || Utilities.isStair(block.getRelative(BlockFace.NORTH_WEST)))) - { - return false; - } - - - int violation = flightViolation.containsKey(name) ? flightViolation.get(name) + 1 : 1; - increment(player, flightViolation, violation); - return violation > magic.FLIGHT_LIMIT; - } */ - - if (!blocksOverFlight.containsKey(name)) - { - blocksOverFlight.put(name, 0D); - } - - blocksOverFlight.put(name, (blocksOverFlight.get(name) + distance.getXDifference() + distance.getYDifference() + distance.getZDifference())); - - if (y1 > y2) - { - blocksOverFlight.put(name, (blocksOverFlight.get(name) - distance.getYDifference())); - } - - if (blocksOverFlight.get(name) > magic.FLIGHT_BLOCK_LIMIT && (y1 <= y2)) - { - return true; - } - } - else - { - blocksOverFlight.put(name, 0D); - } - - return false; - } - - public void logAscension(Player player, double y1, double y2) - { - String name = player.getName(); - if (y1 < y2 && !isAscending.contains(name)) - { - isAscending.add(name); - } - else - { - isAscending.remove(name); - } - } - - public boolean checkAscension(Player player, double y1, double y2) - { - int max = magic.ASCENSION_COUNT_MAX; - if (player.hasPotionEffect(PotionEffectType.JUMP)) - { - max += 12; - } - Block block = player.getLocation().getBlock(); - if (!isMovingExempt(player) && !Utilities.isInWater(player) && !justBroke(player) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && !player.isInsideVehicle()) - { - String name = player.getName(); - if (y1 < y2) - { - if (!block.getRelative(BlockFace.NORTH).isLiquid() && !block.getRelative(BlockFace.SOUTH).isLiquid() && !block.getRelative(BlockFace.EAST).isLiquid() && !block.getRelative(BlockFace.WEST).isLiquid()) - { - increment(player, ascensionCount, max); - if (ascensionCount.get(name) >= max) - { - return true; - } - } - } - else - { - ascensionCount.put(name, 0); - } - } - return false; - } - - public boolean checkSwing(Player player, Block block) - { - String name = player.getName(); - if (!isInstantBreakExempt(player)) - { - if (!player.getInventory().getItemInHand().containsEnchantment(Enchantment.DIG_SPEED) && !(player.getInventory().getItemInHand().getType() == Material.SHEARS && block.getType() == Material.LEAVES)) - { - if (blockPunches.get(name) != null && player.getGameMode() != GameMode.CREATIVE) - { - int i = blockPunches.get(name); - if (i < magic.BLOCK_PUNCH_MIN) - { - return true; - } - else - { - blockPunches.put(name, 0); // it should reset after EACH block break. - } - } - } - } - return !justAnimated(player); //TODO: best way to implement other option? - } - - public boolean checkFastBreak(Player player, Block block) - { - int violations = magic.FASTBREAK_MAXVIOLATIONS; - long timemax = Utilities.calcSurvivalFastBreak(player.getInventory().getItemInHand(), block.getType()); - if (player.getGameMode() == GameMode.CREATIVE) - { - violations = magic.FASTBREAK_MAXVIOLATIONS_CREATIVE; - timemax = magic.FASTBREAK_TIMEMAX_CREATIVE; - } - String name = player.getName(); - if (!fastBreakViolation.containsKey(name)) - { - fastBreakViolation.put(name, 0); - } - else - { - Long math = System.currentTimeMillis() - lastBlockBroken.get(name); - if (fastBreakViolation.get(name) > violations && math < magic.FASTBREAK_MAXVIOLATIONTIME) - { - lastBlockBroken.put(name, System.currentTimeMillis()); - player.sendMessage(ChatColor.RED + "[AntiCheat] Fastbreaking detected. Please wait 10 seconds before breaking blocks."); - return true; - } - else if (fastBreakViolation.get(name) > 0 && math > magic.FASTBREAK_MAXVIOLATIONTIME) - { - fastBreakViolation.put(name, 0); - } - } - if (!fastBreaks.containsKey(name) || !lastBlockBroken.containsKey(name)) - { - if (!lastBlockBroken.containsKey(name)) - { - lastBlockBroken.put(name, System.currentTimeMillis()); - } - if (!fastBreaks.containsKey(name)) - { - fastBreaks.put(name, 0); - } - } - else - { - Long math = System.currentTimeMillis() - lastBlockBroken.get(name); - if (math < timemax && (math != 0L)) - { - if (fastBreakViolation.containsKey(name) && fastBreakViolation.get(name) > 0) - { - fastBreakViolation.put(name, fastBreakViolation.get(name) + 1); - } - else - { - fastBreaks.put(name, fastBreaks.get(name) + 1); - } - blockBreakHolder.put(name, false); - } - if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT && math < timemax) - { - fastBreaks.put(name, 0); - fastBreakViolation.put(name, fastBreakViolation.get(name) + 1); - return true; - } - else if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT || fastBreakViolation.get(name) > 0) - { - if (!blockBreakHolder.containsKey(name) || !blockBreakHolder.get(name)) - { - blockBreakHolder.put(name, true); - } - else - { - fastBreaks.put(name, fastBreaks.get(name) - 1); - if (fastBreakViolation.get(name) > 0) - { - fastBreakViolation.put(name, fastBreakViolation.get(name) - 1); - } - blockBreakHolder.put(name, false); - } - } - } - - lastBlockBroken.put(name, System.currentTimeMillis()); // always keep a log going. - return false; - } - - public boolean checkFastPlace(Player player) - { - int violations = magic.FASTPLACE_MAXVIOLATIONS; - if (player.getGameMode() == GameMode.CREATIVE) - { - violations = magic.FASTPLACE_MAXVIOLATIONS_CREATIVE; - } - long time = System.currentTimeMillis(); - String name = player.getName(); - if (!lastBlockPlaceTime.containsKey(name) || !fastPlaceViolation.containsKey(name)) - { - lastBlockPlaceTime.put(name, Long.parseLong("0")); - if (!fastPlaceViolation.containsKey(name)) - { - fastPlaceViolation.put(name, 0); - } - } - else if (fastPlaceViolation.containsKey(name) && fastPlaceViolation.get(name) > violations) - { - Long math = System.currentTimeMillis() - lastBlockPlaced.get(name); - if (lastBlockPlaced.get(name) > 0 && math < magic.FASTPLACE_MAXVIOLATIONTIME) - { - lastBlockPlaced.put(name, time); - player.sendMessage(ChatColor.RED + "[AntiCheat] Fastplacing detected. Please wait 10 seconds before placing blocks."); - return true; - } - else if (lastBlockPlaced.get(name) > 0 && math > magic.FASTPLACE_MAXVIOLATIONTIME) - { - fastPlaceViolation.put(name, 0); - } - } - else if (lastBlockPlaced.containsKey(name)) - { - long last = lastBlockPlaced.get(name); - long lastTime = lastBlockPlaceTime.get(name); - long thisTime = time - last; - boolean nocheck = thisTime < 1 || lastTime < 1; - if (!lastZeroHitPlace.containsKey(name)) - { - lastZeroHitPlace.put(name, 0); - } - if (nocheck) - { - if (!lastZeroHitPlace.containsKey(name)) - { - lastZeroHitPlace.put(name, 1); - } - else - { - lastZeroHitPlace.put(name, lastZeroHitPlace.get(name) + 1); - } - } - if (thisTime < magic.FASTPLACE_TIMEMAX && lastTime < magic.FASTPLACE_TIMEMAX && nocheck && lastZeroHitPlace.get(name) > magic.FASTPLACE_ZEROLIMIT) - { - lastBlockPlaceTime.put(name, (time - last)); - lastBlockPlaced.put(name, time); - fastPlaceViolation.put(name, fastPlaceViolation.get(name) + 1); - return true; - } - lastBlockPlaceTime.put(name, (time - last)); - } - lastBlockPlaced.put(name, time); - return false; - } - - public void logBowWindUp(Player player) - { - bowWindUp.put(player.getName(), System.currentTimeMillis()); - } - - public void logEatingStart(Player player) - { - startEat.put(player.getName(), System.currentTimeMillis()); - } - - public boolean justStartedEating(Player player) - { - if (startEat.containsKey(player.getName())) // Otherwise it was modified by a plugin, don't worry about it. - { - long l = startEat.get(player.getName()); - startEat.remove(player.getName()); - return (System.currentTimeMillis() - l) < magic.EAT_TIME_MIN; - } - return false; - } - - public void logHeal(Player player) - { - lastHeal.put(player.getName(), System.currentTimeMillis()); - } - - public boolean justHealed(Player player) - { - if (lastHeal.containsKey(player.getName())) // Otherwise it was modified by a plugin, don't worry about it. - { - long l = lastHeal.get(player.getName()); - lastHeal.remove(player.getName()); - return (System.currentTimeMillis() - l) < magic.HEAL_TIME_MIN; - } - return false; - } - - public void logChat(final Player player) - { - String name = player.getName(); - if (chatLevel.get(name) == null) - { - logEvent(chatLevel, player, 1, magic.CHAT_MIN); - } - else - { - int amount = chatLevel.get(name) + 1; - logEvent(chatLevel, player, amount, magic.CHAT_MIN); - if (checkChatLevel(player, amount)) - { - micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable() - { - @Override - public void run() - { - processChatSpammer(player); - } - }); - } - } - } - - public boolean checkSpam(Player player, String msg) - { - String name = player.getName(); - if (lastMessage.get(name) == null) - { - logEvent(lastMessage, player, msg, magic.CHAT_REPEAT_MIN); - } - else - { - if (oldMessage.get(name) != null && lastMessage.get(name).equals(msg) && oldMessage.get(name).equals(msg)) - { - return true; - } - else - { - logEvent(oldMessage, player, lastMessage.get(name), magic.CHAT_REPEAT_MIN); - logEvent(lastMessage, player, msg, magic.CHAT_REPEAT_MIN); - return false; - } - } - return false; - } - - public boolean checkInventoryClicks(Player player) - { - if (player.getGameMode() == GameMode.CREATIVE) - { - return false; - } - String name = player.getName(); - int clicks = 1; - if (inventoryClicks.containsKey(name)) - { - clicks = inventoryClicks.get(name) + 1; - } - inventoryClicks.put(name, clicks); - if (clicks == 1) - { - inventoryTime.put(name, System.currentTimeMillis()); - } - else if (clicks == magic.INVENTORY_CHECK) - { - long time = System.currentTimeMillis() - inventoryTime.get(name); - inventoryClicks.put(name, 0); - return time < magic.INVENTORY_TIMEMIN; - } - return false; - } - - public void clearChatLevel(Player player) - { - chatLevel.remove(player.getName()); - } - - public void logInstantBreak(final Player player) - { - instantBreakExempt.put(player.getName(), System.currentTimeMillis()); - } - - public boolean isInstantBreakExempt(Player player) - { - return isDoing(player, instantBreakExempt, magic.INSTANT_BREAK_TIME); - } - - public void logSprint(final Player player) - { - sprinted.put(player.getName(), System.currentTimeMillis()); - } - - public boolean justSprinted(Player player) - { - return isDoing(player, sprinted, magic.SPRINT_MIN); - } - - public boolean isHoveringOverWaterAfterViolation(Player player) - { - if (waterSpeedViolation.containsKey(player.getName())) - { - if (waterSpeedViolation.get(player.getName()) >= magic.WATER_SPEED_VIOLATION_MAX && Utilities.isHoveringOverWater(player.getLocation())) - { - return true; - } - } - return false; - } - - public void logBlockBreak(final Player player) - { - brokenBlock.put(player.getName(), System.currentTimeMillis()); - resetAnimation(player); - } - - public boolean justBroke(Player player) - { - return isDoing(player, brokenBlock, magic.BLOCK_BREAK_MIN); - } - - public void logVelocity(final Player player) - { - velocitized.put(player.getName(), System.currentTimeMillis()); - } - - public boolean justVelocity(Player player) - { - return (velocitized.containsKey(player.getName()) ? (System.currentTimeMillis() - velocitized.get(player.getName())) < magic.VELOCITY_CHECKTIME : false); - } - - public boolean justSwitchedTool(Player player) - { - if (itemInHand.containsKey(player.getName())) - { - return itemInHand.get(player.getName()) != player.getItemInHand().getType(); - } - else - { - return false; - } - } - - public boolean extendVelocityTime(final Player player) - { - if (velocitytrack.containsKey(player.getName())) - { - velocitytrack.put(player.getName(), velocitytrack.get(player.getName()) + 1); - if (velocitytrack.get(player.getName()) > magic.VELOCITY_MAXTIMES) - { - velocitized.put(player.getName(), System.currentTimeMillis() + magic.VELOCITY_PREVENT); - micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable() - { - @Override - public void run() - { - velocitytrack.put(player.getName(), 0); - } - }, magic.VELOCITY_SCHETIME * 20L); - return true; - } - } - else - { - velocitytrack.put(player.getName(), 0); - } - - return false; - } - - public void logBlockPlace(final Player player) - { - placedBlock.put(player.getName(), System.currentTimeMillis()); - } - - public boolean justPlaced(Player player) - { - return isDoing(player, placedBlock, magic.BLOCK_PLACE_MIN); - } - - public void logAnimation(final Player player) - { - animated.put(player.getName(), System.currentTimeMillis()); - increment(player, blockPunches, magic.BLOCK_PUNCH_MIN); - itemInHand.put(player.getName(), player.getItemInHand().getType()); - } - - public void resetAnimation(final Player player) - { - animated.remove(player.getName()); - blockPunches.put(player.getName(), 0); - } - - public boolean justAnimated(Player player) - { - if (player.getItemInHand().containsEnchantment(Enchantment.DIG_SPEED)) - { - return true; - } - String name = player.getName(); - if (animated.containsKey(name)) - { - long time = System.currentTimeMillis() - animated.get(name); - animated.remove(player.getName()); - return time < magic.ANIMATION_MIN; - } - else - { - return false; - } - } - - public void logDamage(final Player player, int type) - { - long time; - switch (type) - { - case 1: - time = magic.DAMAGE_TIME; - break; - case 2: - time = magic.KNOCKBACK_DAMAGE_TIME; - break; - case 3: - time = magic.EXPLOSION_DAMAGE_TIME; - break; - default: - time = magic.DAMAGE_TIME; - break; - - } - movingExempt.put(player.getName(), System.currentTimeMillis() + time); - // Only map in which termination time is calculated beforehand. - } - - public void logEnterExit(final Player player) - { - movingExempt.put(player.getName(), System.currentTimeMillis() + magic.ENTERED_EXITED_TIME); - } - - public void logToggleSneak(final Player player) - { - movingExempt.put(player.getName(), System.currentTimeMillis() + magic.SNEAK_TIME); - } - - public void logTeleport(final Player player) - { - movingExempt.put(player.getName(), System.currentTimeMillis() + magic.TELEPORT_TIME); - - /* Data for fly/speed should be reset */ - nofallViolation.remove(player.getName()); - blocksOverFlight.remove(player.getName()); - yAxisViolations.remove(player.getName()); - yAxisLastViolation.remove(player.getName()); - lastYcoord.remove(player.getName()); - lastYtime.remove(player.getName()); - } - - public void logExitFly(final Player player) - { - movingExempt.put(player.getName(), System.currentTimeMillis() + magic.EXIT_FLY_TIME); - } - - public void logJoin(final Player player) - { - movingExempt.put(player.getName(), System.currentTimeMillis() + magic.JOIN_TIME); - } - - public boolean isMovingExempt(Player player) - { - return isDoing(player, movingExempt, -1); - } - - public boolean isAscending(Player player) - { - return isAscending.contains(player.getName()); - } - - public boolean isSpeedExempt(Player player) - { - return isMovingExempt(player) || justVelocity(player); - } - - private void logEvent(final Map map, final Player player, final E obj, long time) - { - - map.put(player.getName(), obj); - micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable() - { - @Override - public void run() - { - if (map.get(player.getName()) == obj) - { - map.remove(player.getName()); - } - else - { - //Don't remove this, for some reason it's fixing chat bugs. - } - } - }, time); - } - - private boolean isDoing(Player player, Map map, double max) - { - if (map.containsKey(player.getName())) - { - if (max != -1) - { - if (((System.currentTimeMillis() - map.get(player.getName())) / 1000) > max) - { - map.remove(player.getName()); - return false; - } - else - { - return true; - } - } - else - { - // Termination time has already been calculated - if (map.get(player.getName()) < System.currentTimeMillis()) - { - map.remove(player.getName()); - return false; - } - else - { - return true; - } - } - } - else - { - return false; - } - } - - private boolean checkChatLevel(Player player, int amount) - { - return amount >= magic.CHAT_KICK_LEVEL; - } - - private void processChatSpammer(Player player) - { - if (player != null && player.isOnline()) - { - String name = player.getName(); - int kick; - if (chatKicks.get(name) == null || chatKicks.get(name) == 0) - { - kick = 1; - chatKicks.put(name, kick); - } - else - { - kick = chatKicks.get(name) + 1; - chatKicks.put(name, kick); - } - - String event = kick <= magic.CHAT_BAN_LEVEL ? micromanage.getConfiguration().chatActionKick() : micromanage.getConfiguration().chatActionBan(); - // Set string variables - event = event.replaceAll("&player", name).replaceAll("&world", player.getWorld().getName()); - - if (event.startsWith("COMMAND[")) - { - String command = event.replaceAll("COMMAND\\[", "").replaceAll("]", ""); - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command); - } - else if (event.equalsIgnoreCase("KICK")) - { - String msg = kick <= magic.CHAT_BAN_LEVEL ? ChatColor.RED + lang.getChatKickReason() + " (" + kick + "/" + magic.CHAT_BAN_LEVEL + ")" : ChatColor.RED + lang.getChatBanReason(); - player.kickPlayer(msg); - msg = kick <= magic.CHAT_BAN_LEVEL ? ChatColor.RED + lang.getChatKickBroadcast() + " (" + kick + "/" + magic.CHAT_BAN_LEVEL + ")" : ChatColor.RED + lang.getChatBanBroadcast(); - msg = msg.replaceAll("&player", name); - if (!msg.equals("")) - { - Bukkit.broadcastMessage(msg); - } - } - else if (event.equalsIgnoreCase("BAN")) - { - player.setBanned(true); - player.kickPlayer(ChatColor.RED + lang.getChatBanReason()); - String msg = ChatColor.RED + lang.getChatBanBroadcast(); - msg = msg.replaceAll("&player", name); - if (!msg.equals("")) - { - Bukkit.broadcastMessage(msg); - } - } - } - } - - public int increment(Player player, Map map, int num) - { - String name = player.getName(); - if (map.get(name) == null) - { - map.put(name, 1); - return 1; - } - else - { - int amount = map.get(name) + 1; - if (amount < num + 1) - { - map.put(name, amount); - return amount; - } - else - { - map.put(name, num); - return num; - } - } - } +public class Backend { + private List isInWater = new ArrayList(); + private List isInWaterCache = new ArrayList(); + private List isAscending = new ArrayList(); + private Map ascensionCount = new HashMap(); + private Map oldMessage = new HashMap(); + private Map lastMessage = new HashMap(); + private Map blocksOverFlight = new HashMap(); + private Map chatLevel = new HashMap(); + private Map chatKicks = new HashMap(); + private Map nofallViolation = new HashMap(); + private Map speedViolation = new HashMap(); + private Map fastBreakViolation = new HashMap(); + private Map yAxisViolations = new HashMap(); + private Map yAxisLastViolation = new HashMap(); + private Map lastYcoord = new HashMap(); + private Map lastYtime = new HashMap(); + private Map fastBreaks = new HashMap(); + private Map blockBreakHolder = new HashMap(); + private Map lastBlockBroken = new HashMap(); + private Map fastPlaceViolation = new HashMap(); + private Map lastZeroHitPlace = new HashMap(); + private Map lastBlockPlaced = new HashMap(); + private Map lastBlockPlaceTime = new HashMap(); + private Map blockPunches = new HashMap(); + private Map waterAscensionViolation = new HashMap(); + private Map waterSpeedViolation = new HashMap(); + private Map projectilesShot = new HashMap(); + private Map velocitized = new HashMap(); + private Map velocitytrack = new HashMap(); + private Map animated = new HashMap(); + private Map startEat = new HashMap(); + private Map lastHeal = new HashMap(); + private Map projectileTime = new HashMap(); + private Map bowWindUp = new HashMap(); + private Map instantBreakExempt = new HashMap(); + private Map sprinted = new HashMap(); + private Map brokenBlock = new HashMap(); + private Map placedBlock = new HashMap(); + private Map movingExempt = new HashMap(); + private Map blockTime = new HashMap(); + private Map blocksDropped = new HashMap(); + private Map lastInventoryTime = new HashMap(); + private Map inventoryTime = new HashMap(); + private Map inventoryClicks = new HashMap(); + private Map itemInHand = new HashMap(); + private Map steps = new HashMap(); + private Map stepTime = new HashMap(); + private HashSet transparent = new HashSet(); + private Map lastFallPacket = new HashMap(); + + private Magic magic; + private AnticheatManager micromanage = null; + private Language lang = null; + + public Backend(AnticheatManager instance) { + magic = new Magic(instance.getConfiguration().getMagic(), instance.getConfiguration(), CommentedConfiguration.loadConfiguration(instance.getPlugin().getResource("magic.yml"))); + micromanage = instance; + lang = micromanage.getConfiguration().getLang(); + transparent.add((byte) -1); + } + + public void garbageClean(Player player) { + String pN = player.getName(); + User user = micromanage.getUserManager().getUser(pN); + if (user != null) { + micromanage.getUserManager().remove(user); + } + blocksDropped.remove(pN); + blockTime.remove(pN); + movingExempt.remove(pN); + brokenBlock.remove(pN); + placedBlock.remove(pN); + bowWindUp.remove(pN); + startEat.remove(pN); + lastHeal.remove(pN); + sprinted.remove(pN); + isInWater.remove(pN); + isInWaterCache.remove(pN); + instantBreakExempt.remove(pN); + isAscending.remove(pN); + ascensionCount.remove(pN); + oldMessage.remove(pN); + lastMessage.remove(pN); + blocksOverFlight.remove(pN); + chatLevel.remove(pN); + nofallViolation.remove(pN); + fastBreakViolation.remove(pN); + yAxisViolations.remove(pN); + yAxisLastViolation.remove(pN); + lastYcoord.remove(pN); + lastYtime.remove(pN); + fastBreaks.remove(pN); + blockBreakHolder.remove(pN); + lastBlockBroken.remove(pN); + fastPlaceViolation.remove(pN); + lastZeroHitPlace.remove(pN); + lastBlockPlaced.remove(pN); + lastBlockPlaceTime.remove(pN); + blockPunches.remove(pN); + waterAscensionViolation.remove(pN); + waterSpeedViolation.remove(pN); + projectilesShot.remove(pN); + velocitized.remove(pN); + velocitytrack.remove(pN); + animated.remove(pN); + startEat.remove(pN); + lastHeal.remove(pN); + projectileTime.remove(pN); + bowWindUp.remove(pN); + instantBreakExempt.remove(pN); + sprinted.remove(pN); + brokenBlock.remove(pN); + placedBlock.remove(pN); + movingExempt.remove(pN); + blockTime.remove(pN); + blocksDropped.remove(pN); + lastInventoryTime.remove(pN); + inventoryTime.remove(pN); + inventoryClicks.remove(pN); + lastFallPacket.remove(pN); + } + + public boolean checkFreeze(Player player, double from, double to) { + // TODO: Fix! This is causing false-positives + /* + * if((from-to) > 0) { boolean flag = false; if(lastFallPacket.containsKey(player.getName()) && lastFallPacket.get(player.getName()) > 0) { flag = (System.currentTimeMillis()-lastFallPacket.get(player.getName())) > 1000; } lastFallPacket.put(player.getName(), System.currentTimeMillis()); + * return flag; } else { lastFallPacket.put(player.getName(), -1L); } + */ + return false; + } + + public boolean checkFastBow(Player player, float force) { + // Ignore magic numbers here, they are minecrafty vanilla stuff. + int ticks = (int) ((((System.currentTimeMillis() - bowWindUp.get(player.getName())) * 20) / 1000) + 3); + bowWindUp.remove(player.getName()); + float f = (float) ticks / 20.0F; + f = (f * f + f * 2.0F) / 3.0F; + f = f > 1.0F ? 1.0F : f; + return Math.abs(force - f) > magic.BOW_ERROR; + } + + public boolean checkProjectile(Player player) { + increment(player, projectilesShot, 10); + if (!projectileTime.containsKey(player.getName())) { + projectileTime.put(player.getName(), System.currentTimeMillis()); + return false; + } else if (projectilesShot.get(player.getName()) == magic.PROJECTILE_CHECK) { + long time = System.currentTimeMillis() - projectileTime.get(player.getName()); + projectileTime.remove(player.getName()); + projectilesShot.remove(player.getName()); + return time < magic.PROJECTILE_TIME_MIN; + } + return false; + } + + public boolean checkFastDrop(Player player) { + increment(player, blocksDropped, 10); + if (!blockTime.containsKey(player.getName())) { + blockTime.put(player.getName(), System.currentTimeMillis()); + return false; + } else if (blocksDropped.get(player.getName()) == magic.DROP_CHECK) { + long time = System.currentTimeMillis() - blockTime.get(player.getName()); + blockTime.remove(player.getName()); + blocksDropped.remove(player.getName()); + return time < magic.DROP_TIME_MIN; + } + return false; + } + + public boolean checkLongReachBlock(Player player, double x, double y, double z) { + if (isInstantBreakExempt(player)) { + return false; + } else { + return (x >= magic.BLOCK_MAX_DISTANCE || y > magic.BLOCK_MAX_DISTANCE || z > magic.BLOCK_MAX_DISTANCE); + } + } + + public boolean checkLongReachDamage(double x, double y, double z) { + return x >= magic.ENTITY_MAX_DISTANCE || y > magic.ENTITY_MAX_DISTANCE || z > magic.ENTITY_MAX_DISTANCE; + } + + public boolean checkSpider(Player player, double y) { + if (y <= magic.LADDER_Y_MAX && y >= magic.LADDER_Y_MIN && !Utilities.isClimbableBlock(player.getLocation().getBlock())) { return true; } + return false; + } + + public boolean checkYSpeed(Player player, double y) { + if (!player.isInsideVehicle() && !player.isSleeping() && y > magic.Y_SPEED_MAX && !isDoing(player, velocitized, magic.VELOCITY_TIME) && !player.hasPotionEffect(PotionEffectType.JUMP)) { return true; } + return false; + } + + public boolean checkNoFall(Player player, double y) { + String name = player.getName(); + if (player.getGameMode() != GameMode.CREATIVE && !player.isInsideVehicle() && !player.isSleeping() && !isMovingExempt(player) && !justPlaced(player) && !Utilities.isInWater(player)) { + if (player.getFallDistance() == 0) { + if (nofallViolation.get(name) == null) { + nofallViolation.put(name, 1); + } else { + nofallViolation.put(name, nofallViolation.get(player.getName()) + 1); + } + + if (nofallViolation.get(name) >= magic.NOFALL_LIMIT) { + nofallViolation.put(player.getName(), 1); + return true; + } else { + return false; + } + } else { + nofallViolation.put(name, 0); + return false; + } + } + return false; + } + + public boolean checkXZSpeed(Player player, double x, double z) { + if (!isSpeedExempt(player) && player.getVehicle() == null) { + boolean speed = false; + if (player.getLocation().getBlock().getType() == Material.SOUL_SAND) { + if (player.isSprinting()) { + speed = x > magic.XZ_SPEED_MAX_SOULSAND_SPRINT || z > magic.XZ_SPEED_MAX_SOULSAND_SPRINT; + } else { + speed = x > magic.XZ_SPEED_MAX_SOULSAND || z > magic.XZ_SPEED_MAX_SOULSAND; + } + } else if (player.isFlying()) { + speed = x > magic.XZ_SPEED_MAX_FLY || z > magic.XZ_SPEED_MAX_FLY; + } else if (player.hasPotionEffect(PotionEffectType.SPEED)) { + speed = x > magic.XZ_SPEED_MAX_POTION || z > magic.XZ_SPEED_MAX_POTION; + } else if (player.isSprinting()) { + speed = x > magic.XZ_SPEED_MAX_SPRINT || z > magic.XZ_SPEED_MAX_SPRINT; + } else { + speed = x > magic.XZ_SPEED_MAX || z > magic.XZ_SPEED_MAX; + } + if (speed) { + int num = this.increment(player, speedViolation, magic.SPEED_MAX); + return num >= magic.SPEED_MAX; + } else { + speedViolation.put(player.getName(), 0); + return false; + } + } else { + return false; + } + } + + public boolean checkSneak(Player player, double x, double z) { + if (player.isSneaking() && !player.isFlying() && !isMovingExempt(player)) { + return x > magic.XZ_SPEED_MAX_SNEAK || z > magic.XZ_SPEED_MAX_SNEAK; + } else { + return false; + } + } + + public boolean checkSprintHungry(PlayerToggleSprintEvent event) { + Player player = event.getPlayer(); + if (event.isSprinting()) { + return player.getFoodLevel() <= magic.SPRINT_FOOD_MIN && player.getGameMode() != GameMode.CREATIVE; + } else { + return false; + } + } + + public boolean checkSprintStill(Player player, Location from, Location to) { + return !isMovingExempt(player) && player.isSprinting() && from.getX() == to.getX() && from.getZ() == to.getZ(); + } + + public boolean checkWaterWalk(Player player, double x, double y, double z) { + Block block = player.getLocation().getBlock(); + + if (player.getVehicle() == null && !player.isFlying()) { + if (block.isLiquid()) { + if (isInWater.contains(player.getName())) { + if (isInWaterCache.contains(player.getName())) { + if (player.getNearbyEntities(1, 1, 1).isEmpty()) { + boolean b = false; + if (!Utilities.sprintFly(player) && x > magic.XZ_SPEED_MAX_WATER || z > magic.XZ_SPEED_MAX_WATER) { + b = true; + } else if (x > magic.XZ_SPEED_MAX_WATER_SPRINT || z > magic.XZ_SPEED_MAX_WATER_SPRINT) { + b = true; + } else if (!Utilities.isFullyInWater(player.getLocation()) && Utilities.isHoveringOverWater(player.getLocation(), 1) && y == 0D && !block.getType().equals(Material.WATER_LILY)) { + b = true; + } + if (b) { + if (waterSpeedViolation.containsKey(player.getName())) { + int v = waterSpeedViolation.get(player.getName()); + if (v >= magic.WATER_SPEED_VIOLATION_MAX) { + waterSpeedViolation.put(player.getName(), 0); + return true; + } else { + waterSpeedViolation.put(player.getName(), v + 1); + } + } else { + waterSpeedViolation.put(player.getName(), 1); + } + } + } + } else { + isInWaterCache.add(player.getName()); + return false; + } + } else { + isInWater.add(player.getName()); + return false; + } + } else if (block.getRelative(BlockFace.DOWN).isLiquid() && isAscending(player) && Utilities.cantStandAt(block) && Utilities.cantStandAt(block.getRelative(BlockFace.DOWN))) { + if (waterAscensionViolation.containsKey(player.getName())) { + int v = waterAscensionViolation.get(player.getName()); + if (v >= magic.WATER_ASCENSION_VIOLATION_MAX) { + waterAscensionViolation.put(player.getName(), 0); + return true; + } else { + waterAscensionViolation.put(player.getName(), v + 1); + return true; + } + } else { + waterAscensionViolation.put(player.getName(), 1); + } + } else { + isInWater.remove(player.getName()); + isInWaterCache.remove(player.getName()); + } + } + return false; + } + + // The first check in Anticheat with a integer as a result :O! + + public int checkVClip(Player player, Distance distance) { + double from = Math.round(distance.fromY()); + double to = Math.round(distance.toY()); + + boolean bs = false; + + if (player.isInsideVehicle()) { return 0; } + if (from == to || from < to) { return 0; } + if (Math.round(distance.getYDifference()) < 2) { return 0; } + + for (int i = 0; i < (Math.round(distance.getYDifference())) + 1; i++) { + Block block = new Location(player.getWorld(), player.getLocation().getX(), to + i, player.getLocation().getZ()).getBlock(); + if (block.getTypeId() != 0 && block.getType().isSolid()) { + bs = true; + } + if (bs) { return (int) from + 3; } + } + + return 0; + } + + public boolean checkYAxis(Player player, Distance distance) { + if (distance.getYDifference() > 400 || distance.getYDifference() < 0) { return false; } + if (!isMovingExempt(player) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && !Utilities.isClimbableBlock(player.getLocation().add(0, -1, 0).getBlock()) && !player.isInsideVehicle() && !Utilities.isInWater(player)) { + double y1 = player.getLocation().getY(); + String name = player.getName(); + // Fix Y axis spam. + if (!lastYcoord.containsKey(name) || !lastYtime.containsKey(name) || !yAxisLastViolation.containsKey(name) || !yAxisLastViolation.containsKey(name)) { + lastYcoord.put(name, y1); + yAxisViolations.put(name, 0); + yAxisLastViolation.put(name, 0L); + lastYtime.put(name, System.currentTimeMillis()); + } else { + if (y1 > lastYcoord.get(name) && yAxisViolations.get(name) > magic.Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) < magic.Y_MAXVIOTIME) { + Location g = player.getLocation(); + g.setY(lastYcoord.get(name)); + player.sendMessage(ChatColor.RED + "[AntiCheat] Fly hacking on the y-axis detected. Please wait 5 seconds to prevent getting damage."); + yAxisViolations.put(name, yAxisViolations.get(name) + 1); + yAxisLastViolation.put(name, System.currentTimeMillis()); + if (g.getBlock().getTypeId() == 0) { + player.teleport(g); + } + return true; + } else { + if (yAxisViolations.get(name) > magic.Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) > magic.Y_MAXVIOTIME) { + yAxisViolations.put(name, 0); + yAxisLastViolation.put(name, 0L); + } + } + if ((y1 - lastYcoord.get(name)) > magic.Y_MAXDIFF && (System.currentTimeMillis() - lastYtime.get(name)) < magic.Y_TIME) { + Location g = player.getLocation(); + g.setY(lastYcoord.get(name)); + yAxisViolations.put(name, yAxisViolations.get(name) + 1); + yAxisLastViolation.put(name, System.currentTimeMillis()); + if (g.getBlock().getTypeId() == 0) { + player.teleport(g); + } + return true; + } else { + if ((y1 - lastYcoord.get(name)) > magic.Y_MAXDIFF + 1 || (System.currentTimeMillis() - lastYtime.get(name)) > magic.Y_TIME) { + lastYtime.put(name, System.currentTimeMillis()); + lastYcoord.put(name, y1); + } + } + } + } + // Fix Y axis spam + return false; + } + + public boolean checkTimer(Player player) { + String name = player.getName(); + int step = 1; + if (steps.containsKey(name)) { + step = steps.get(name) + 1; + } + if (step == 1) { + stepTime.put(name, System.currentTimeMillis()); + } + increment(player, steps, step); + if (step == magic.TIMER_STEP_CHECK) { + long time = System.currentTimeMillis() - stepTime.get(name); + steps.put(name, 0); + return time < magic.TIMER_TIMEMIN; + } + return false; + } + + public boolean checkSight(Player player, Entity entity) { + if (entity instanceof LivingEntity) { + LivingEntity le = (LivingEntity) entity; + // Check to make sure the entity's head is not surrounded + Block head = le.getWorld().getBlockAt((int) le.getLocation().getX(), (int) (le.getLocation().getY() + le.getEyeHeight()), (int) le.getLocation().getZ()); + boolean solid = false; + // TODO: This sucks. See if it's possible to not have as many false-positives while still retaining most of the check. + for (int x = -2; x <= 2; x++) { + for (int z = -2; z <= 2; z++) { + for (int y = -1; y < 2; y++) { + if (head.getRelative(x, y, z).getTypeId() != 0) { + if (head.getRelative(x, y, z).getType().isSolid()) { + solid = true; + break; + } + + } + } + } + + } + if (solid) { return true; } + // TODO: Needs proper testing + Location mobLocation = le.getEyeLocation(); + for (Block block : player.getLineOfSight(transparent, 5)) { + if (Math.abs(block.getLocation().getX() - mobLocation.getX()) < 2.3 || Math.abs(block.getLocation().getZ() - mobLocation.getZ()) < 2.3) { + + return true; } + } + return false; + } + return true; + } + + public boolean checkFlight(Player player, Distance distance) { + if (distance.getYDifference() > 400) { + // This was a teleport, so we don't care about it. + return false; + } + String name = player.getName(); + double y1 = distance.fromY(); + double y2 = distance.toY(); + // Check if the player is climbing up water. + /* + * if (block.getRelative(BlockFace.NORTH).isLiquid() || block.getRelative(BlockFace.SOUTH).isLiquid() || block.getRelative(BlockFace.EAST).isLiquid() || block.getRelative(BlockFace.WEST).isLiquid()) { if (y1 < y2) { //Even if they are using a hacked client and flying next to water to abuse + * this, they can't be go past the speed limit so they might as well swim return distance.getYDifference() > magic.WATER_CLIMB_MAX; } } + */ + + if (!isMovingExempt(player) && !Utilities.isHoveringOverWater(player.getLocation(), 1) && Utilities.cantStandAtExp(player.getLocation())) { + /* + * if (y1 == y2 || y1 < y2) { + * + * if (y1 == y2) { //Check if the player is on slabs or crouching on stairs if (Utilities.isSlab(block.getRelative(BlockFace.NORTH)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH)) || Utilities.isSlab(block.getRelative(BlockFace.EAST)) || + * Utilities.isSlab(block.getRelative(BlockFace.WEST)) || Utilities.isSlab(block.getRelative(BlockFace.NORTH_EAST)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH_EAST)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH_WEST)) || + * Utilities.isSlab(block.getRelative(BlockFace.NORTH_WEST))) { return false; } else if (player.isSneaking() && (Utilities.isStair(block.getRelative(BlockFace.NORTH)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH)) || Utilities.isStair(block.getRelative(BlockFace.EAST)) || + * Utilities.isStair(block.getRelative(BlockFace.WEST)) || Utilities.isStair(block.getRelative(BlockFace.NORTH_EAST)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH_EAST)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH_WEST)) || + * Utilities.isStair(block.getRelative(BlockFace.NORTH_WEST)))) { return false; } + * + * + * int violation = flightViolation.containsKey(name) ? flightViolation.get(name) + 1 : 1; increment(player, flightViolation, violation); return violation > magic.FLIGHT_LIMIT; } + */ + + if (!blocksOverFlight.containsKey(name)) { + blocksOverFlight.put(name, 0D); + } + + blocksOverFlight.put(name, (blocksOverFlight.get(name) + distance.getXDifference() + distance.getYDifference() + distance.getZDifference())); + + if (y1 > y2) { + blocksOverFlight.put(name, (blocksOverFlight.get(name) - distance.getYDifference())); + } + + if (blocksOverFlight.get(name) > magic.FLIGHT_BLOCK_LIMIT && (y1 <= y2)) { return true; } + } else { + blocksOverFlight.put(name, 0D); + } + + return false; + } + + public void logAscension(Player player, double y1, double y2) { + String name = player.getName(); + if (y1 < y2 && !isAscending.contains(name)) { + isAscending.add(name); + } else { + isAscending.remove(name); + } + } + + public boolean checkAscension(Player player, double y1, double y2) { + int max = magic.ASCENSION_COUNT_MAX; + if (player.hasPotionEffect(PotionEffectType.JUMP)) { + max += 12; + } + Block block = player.getLocation().getBlock(); + if (!isMovingExempt(player) && !Utilities.isInWater(player) && !justBroke(player) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && !player.isInsideVehicle()) { + String name = player.getName(); + if (y1 < y2) { + if (!block.getRelative(BlockFace.NORTH).isLiquid() && !block.getRelative(BlockFace.SOUTH).isLiquid() && !block.getRelative(BlockFace.EAST).isLiquid() && !block.getRelative(BlockFace.WEST).isLiquid()) { + increment(player, ascensionCount, max); + if (ascensionCount.get(name) >= max) { return true; } + } + } else { + ascensionCount.put(name, 0); + } + } + return false; + } + + public boolean checkSwing(Player player, Block block) { + String name = player.getName(); + if (!isInstantBreakExempt(player)) { + if (!player.getInventory().getItemInHand().containsEnchantment(Enchantment.DIG_SPEED) && !(player.getInventory().getItemInHand().getType() == Material.SHEARS && block.getType() == Material.LEAVES)) { + if (blockPunches.get(name) != null && player.getGameMode() != GameMode.CREATIVE) { + int i = blockPunches.get(name); + if (i < magic.BLOCK_PUNCH_MIN) { + return true; + } else { + blockPunches.put(name, 0); // it should reset after EACH block break. + } + } + } + } + return !justAnimated(player); // TODO: best way to implement other option? + } + + public boolean checkFastBreak(Player player, Block block) { + int violations = magic.FASTBREAK_MAXVIOLATIONS; + long timemax = Utilities.calcSurvivalFastBreak(player.getInventory().getItemInHand(), block.getType()); + if (player.getGameMode() == GameMode.CREATIVE) { + violations = magic.FASTBREAK_MAXVIOLATIONS_CREATIVE; + timemax = magic.FASTBREAK_TIMEMAX_CREATIVE; + } + String name = player.getName(); + if (!fastBreakViolation.containsKey(name)) { + fastBreakViolation.put(name, 0); + } else { + Long math = System.currentTimeMillis() - lastBlockBroken.get(name); + if (fastBreakViolation.get(name) > violations && math < magic.FASTBREAK_MAXVIOLATIONTIME) { + lastBlockBroken.put(name, System.currentTimeMillis()); + player.sendMessage(ChatColor.RED + "[AntiCheat] Fastbreaking detected. Please wait 10 seconds before breaking blocks."); + return true; + } else if (fastBreakViolation.get(name) > 0 && math > magic.FASTBREAK_MAXVIOLATIONTIME) { + fastBreakViolation.put(name, 0); + } + } + if (!fastBreaks.containsKey(name) || !lastBlockBroken.containsKey(name)) { + if (!lastBlockBroken.containsKey(name)) { + lastBlockBroken.put(name, System.currentTimeMillis()); + } + if (!fastBreaks.containsKey(name)) { + fastBreaks.put(name, 0); + } + } else { + Long math = System.currentTimeMillis() - lastBlockBroken.get(name); + if (math < timemax && (math != 0L)) { + if (fastBreakViolation.containsKey(name) && fastBreakViolation.get(name) > 0) { + fastBreakViolation.put(name, fastBreakViolation.get(name) + 1); + } else { + fastBreaks.put(name, fastBreaks.get(name) + 1); + } + blockBreakHolder.put(name, false); + } + if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT && math < timemax) { + fastBreaks.put(name, 0); + fastBreakViolation.put(name, fastBreakViolation.get(name) + 1); + return true; + } else if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT || fastBreakViolation.get(name) > 0) { + if (!blockBreakHolder.containsKey(name) || !blockBreakHolder.get(name)) { + blockBreakHolder.put(name, true); + } else { + fastBreaks.put(name, fastBreaks.get(name) - 1); + if (fastBreakViolation.get(name) > 0) { + fastBreakViolation.put(name, fastBreakViolation.get(name) - 1); + } + blockBreakHolder.put(name, false); + } + } + } + + lastBlockBroken.put(name, System.currentTimeMillis()); // always keep a log going. + return false; + } + + public boolean checkFastPlace(Player player) { + int violations = magic.FASTPLACE_MAXVIOLATIONS; + if (player.getGameMode() == GameMode.CREATIVE) { + violations = magic.FASTPLACE_MAXVIOLATIONS_CREATIVE; + } + long time = System.currentTimeMillis(); + String name = player.getName(); + if (!lastBlockPlaceTime.containsKey(name) || !fastPlaceViolation.containsKey(name)) { + lastBlockPlaceTime.put(name, Long.parseLong("0")); + if (!fastPlaceViolation.containsKey(name)) { + fastPlaceViolation.put(name, 0); + } + } else if (fastPlaceViolation.containsKey(name) && fastPlaceViolation.get(name) > violations) { + Long math = System.currentTimeMillis() - lastBlockPlaced.get(name); + if (lastBlockPlaced.get(name) > 0 && math < magic.FASTPLACE_MAXVIOLATIONTIME) { + lastBlockPlaced.put(name, time); + player.sendMessage(ChatColor.RED + "[AntiCheat] Fastplacing detected. Please wait 10 seconds before placing blocks."); + return true; + } else if (lastBlockPlaced.get(name) > 0 && math > magic.FASTPLACE_MAXVIOLATIONTIME) { + fastPlaceViolation.put(name, 0); + } + } else if (lastBlockPlaced.containsKey(name)) { + long last = lastBlockPlaced.get(name); + long lastTime = lastBlockPlaceTime.get(name); + long thisTime = time - last; + boolean nocheck = thisTime < 1 || lastTime < 1; + if (!lastZeroHitPlace.containsKey(name)) { + lastZeroHitPlace.put(name, 0); + } + if (nocheck) { + if (!lastZeroHitPlace.containsKey(name)) { + lastZeroHitPlace.put(name, 1); + } else { + lastZeroHitPlace.put(name, lastZeroHitPlace.get(name) + 1); + } + } + if (thisTime < magic.FASTPLACE_TIMEMAX && lastTime < magic.FASTPLACE_TIMEMAX && nocheck && lastZeroHitPlace.get(name) > magic.FASTPLACE_ZEROLIMIT) { + lastBlockPlaceTime.put(name, (time - last)); + lastBlockPlaced.put(name, time); + fastPlaceViolation.put(name, fastPlaceViolation.get(name) + 1); + return true; + } + lastBlockPlaceTime.put(name, (time - last)); + } + lastBlockPlaced.put(name, time); + return false; + } + + public void logBowWindUp(Player player) { + bowWindUp.put(player.getName(), System.currentTimeMillis()); + } + + public void logEatingStart(Player player) { + startEat.put(player.getName(), System.currentTimeMillis()); + } + + public boolean justStartedEating(Player player) { + if (startEat.containsKey(player.getName())) // Otherwise it was modified by a plugin, don't worry about it. + { + long l = startEat.get(player.getName()); + startEat.remove(player.getName()); + return (System.currentTimeMillis() - l) < magic.EAT_TIME_MIN; + } + return false; + } + + public void logHeal(Player player) { + lastHeal.put(player.getName(), System.currentTimeMillis()); + } + + public boolean justHealed(Player player) { + if (lastHeal.containsKey(player.getName())) // Otherwise it was modified by a plugin, don't worry about it. + { + long l = lastHeal.get(player.getName()); + lastHeal.remove(player.getName()); + return (System.currentTimeMillis() - l) < magic.HEAL_TIME_MIN; + } + return false; + } + + public void logChat(final Player player) { + String name = player.getName(); + if (chatLevel.get(name) == null) { + logEvent(chatLevel, player, 1, magic.CHAT_MIN); + } else { + int amount = chatLevel.get(name) + 1; + logEvent(chatLevel, player, amount, magic.CHAT_MIN); + if (checkChatLevel(player, amount)) { + micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable() { + @Override + public void run() { + processChatSpammer(player); + } + }); + } + } + } + + public boolean checkSpam(Player player, String msg) { + String name = player.getName(); + if (lastMessage.get(name) == null) { + logEvent(lastMessage, player, msg, magic.CHAT_REPEAT_MIN); + } else { + if (oldMessage.get(name) != null && lastMessage.get(name).equals(msg) && oldMessage.get(name).equals(msg)) { + return true; + } else { + logEvent(oldMessage, player, lastMessage.get(name), magic.CHAT_REPEAT_MIN); + logEvent(lastMessage, player, msg, magic.CHAT_REPEAT_MIN); + return false; + } + } + return false; + } + + public boolean checkInventoryClicks(Player player) { + if (player.getGameMode() == GameMode.CREATIVE) { return false; } + String name = player.getName(); + int clicks = 1; + if (inventoryClicks.containsKey(name)) { + clicks = inventoryClicks.get(name) + 1; + } + inventoryClicks.put(name, clicks); + if (clicks == 1) { + inventoryTime.put(name, System.currentTimeMillis()); + } else if (clicks == magic.INVENTORY_CHECK) { + long time = System.currentTimeMillis() - inventoryTime.get(name); + inventoryClicks.put(name, 0); + return time < magic.INVENTORY_TIMEMIN; + } + return false; + } + + public void clearChatLevel(Player player) { + chatLevel.remove(player.getName()); + } + + public void logInstantBreak(final Player player) { + instantBreakExempt.put(player.getName(), System.currentTimeMillis()); + } + + public boolean isInstantBreakExempt(Player player) { + return isDoing(player, instantBreakExempt, magic.INSTANT_BREAK_TIME); + } + + public void logSprint(final Player player) { + sprinted.put(player.getName(), System.currentTimeMillis()); + } + + public boolean justSprinted(Player player) { + return isDoing(player, sprinted, magic.SPRINT_MIN); + } + + public boolean isHoveringOverWaterAfterViolation(Player player) { + if (waterSpeedViolation.containsKey(player.getName())) { + if (waterSpeedViolation.get(player.getName()) >= magic.WATER_SPEED_VIOLATION_MAX && Utilities.isHoveringOverWater(player.getLocation())) { return true; } + } + return false; + } + + public void logBlockBreak(final Player player) { + brokenBlock.put(player.getName(), System.currentTimeMillis()); + resetAnimation(player); + } + + public boolean justBroke(Player player) { + return isDoing(player, brokenBlock, magic.BLOCK_BREAK_MIN); + } + + public void logVelocity(final Player player) { + velocitized.put(player.getName(), System.currentTimeMillis()); + } + + public boolean justVelocity(Player player) { + return (velocitized.containsKey(player.getName()) ? (System.currentTimeMillis() - velocitized.get(player.getName())) < magic.VELOCITY_CHECKTIME : false); + } + + public boolean justSwitchedTool(Player player) { + if (itemInHand.containsKey(player.getName())) { + return itemInHand.get(player.getName()) != player.getItemInHand().getType(); + } else { + return false; + } + } + + public boolean extendVelocityTime(final Player player) { + if (velocitytrack.containsKey(player.getName())) { + velocitytrack.put(player.getName(), velocitytrack.get(player.getName()) + 1); + if (velocitytrack.get(player.getName()) > magic.VELOCITY_MAXTIMES) { + velocitized.put(player.getName(), System.currentTimeMillis() + magic.VELOCITY_PREVENT); + micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable() { + @Override + public void run() { + velocitytrack.put(player.getName(), 0); + } + }, magic.VELOCITY_SCHETIME * 20L); + return true; + } + } else { + velocitytrack.put(player.getName(), 0); + } + + return false; + } + + public void logBlockPlace(final Player player) { + placedBlock.put(player.getName(), System.currentTimeMillis()); + } + + public boolean justPlaced(Player player) { + return isDoing(player, placedBlock, magic.BLOCK_PLACE_MIN); + } + + public void logAnimation(final Player player) { + animated.put(player.getName(), System.currentTimeMillis()); + increment(player, blockPunches, magic.BLOCK_PUNCH_MIN); + itemInHand.put(player.getName(), player.getItemInHand().getType()); + } + + public void resetAnimation(final Player player) { + animated.remove(player.getName()); + blockPunches.put(player.getName(), 0); + } + + public boolean justAnimated(Player player) { + if (player.getItemInHand().containsEnchantment(Enchantment.DIG_SPEED)) { return true; } + String name = player.getName(); + if (animated.containsKey(name)) { + long time = System.currentTimeMillis() - animated.get(name); + animated.remove(player.getName()); + return time < magic.ANIMATION_MIN; + } else { + return false; + } + } + + public void logDamage(final Player player, int type) { + long time; + switch (type) { + case 1: + time = magic.DAMAGE_TIME; + break; + case 2: + time = magic.KNOCKBACK_DAMAGE_TIME; + break; + case 3: + time = magic.EXPLOSION_DAMAGE_TIME; + break; + default: + time = magic.DAMAGE_TIME; + break; + + } + movingExempt.put(player.getName(), System.currentTimeMillis() + time); + // Only map in which termination time is calculated beforehand. + } + + public void logEnterExit(final Player player) { + movingExempt.put(player.getName(), System.currentTimeMillis() + magic.ENTERED_EXITED_TIME); + } + + public void logToggleSneak(final Player player) { + movingExempt.put(player.getName(), System.currentTimeMillis() + magic.SNEAK_TIME); + } + + public void logTeleport(final Player player) { + movingExempt.put(player.getName(), System.currentTimeMillis() + magic.TELEPORT_TIME); + + /* Data for fly/speed should be reset */ + nofallViolation.remove(player.getName()); + blocksOverFlight.remove(player.getName()); + yAxisViolations.remove(player.getName()); + yAxisLastViolation.remove(player.getName()); + lastYcoord.remove(player.getName()); + lastYtime.remove(player.getName()); + } + + public void logExitFly(final Player player) { + movingExempt.put(player.getName(), System.currentTimeMillis() + magic.EXIT_FLY_TIME); + } + + public void logJoin(final Player player) { + movingExempt.put(player.getName(), System.currentTimeMillis() + magic.JOIN_TIME); + } + + public boolean isMovingExempt(Player player) { + return isDoing(player, movingExempt, -1); + } + + public boolean isAscending(Player player) { + return isAscending.contains(player.getName()); + } + + public boolean isSpeedExempt(Player player) { + return isMovingExempt(player) || justVelocity(player); + } + + private void logEvent(final Map map, final Player player, final E obj, long time) { + + map.put(player.getName(), obj); + micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable() { + @Override + public void run() { + if (map.get(player.getName()) == obj) { + map.remove(player.getName()); + } else { + // Don't remove this, for some reason it's fixing chat bugs. + } + } + }, time); + } + + private boolean isDoing(Player player, Map map, double max) { + if (map.containsKey(player.getName())) { + if (max != -1) { + if (((System.currentTimeMillis() - map.get(player.getName())) / 1000) > max) { + map.remove(player.getName()); + return false; + } else { + return true; + } + } else { + // Termination time has already been calculated + if (map.get(player.getName()) < System.currentTimeMillis()) { + map.remove(player.getName()); + return false; + } else { + return true; + } + } + } else { + return false; + } + } + + private boolean checkChatLevel(Player player, int amount) { + return amount >= magic.CHAT_KICK_LEVEL; + } + + private void processChatSpammer(Player player) { + if (player != null && player.isOnline()) { + String name = player.getName(); + int kick; + if (chatKicks.get(name) == null || chatKicks.get(name) == 0) { + kick = 1; + chatKicks.put(name, kick); + } else { + kick = chatKicks.get(name) + 1; + chatKicks.put(name, kick); + } + + String event = kick <= magic.CHAT_BAN_LEVEL ? micromanage.getConfiguration().chatActionKick() : micromanage.getConfiguration().chatActionBan(); + // Set string variables + event = event.replaceAll("&player", name).replaceAll("&world", player.getWorld().getName()); + + if (event.startsWith("COMMAND[")) { + String command = event.replaceAll("COMMAND\\[", "").replaceAll("]", ""); + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command); + } else if (event.equalsIgnoreCase("KICK")) { + String msg = kick <= magic.CHAT_BAN_LEVEL ? ChatColor.RED + lang.getChatKickReason() + " (" + kick + "/" + magic.CHAT_BAN_LEVEL + ")" : ChatColor.RED + lang.getChatBanReason(); + player.kickPlayer(msg); + msg = kick <= magic.CHAT_BAN_LEVEL ? ChatColor.RED + lang.getChatKickBroadcast() + " (" + kick + "/" + magic.CHAT_BAN_LEVEL + ")" : ChatColor.RED + lang.getChatBanBroadcast(); + msg = msg.replaceAll("&player", name); + if (!msg.equals("")) { + Bukkit.broadcastMessage(msg); + } + } else if (event.equalsIgnoreCase("BAN")) { + player.setBanned(true); + player.kickPlayer(ChatColor.RED + lang.getChatBanReason()); + String msg = ChatColor.RED + lang.getChatBanBroadcast(); + msg = msg.replaceAll("&player", name); + if (!msg.equals("")) { + Bukkit.broadcastMessage(msg); + } + } + } + } + + public int increment(Player player, Map map, int num) { + String name = player.getName(); + if (map.get(name) == null) { + map.put(name, 1); + return 1; + } else { + int amount = map.get(name) + 1; + if (amount < num + 1) { + map.put(name, amount); + return amount; + } else { + map.put(name, num); + return num; + } + } + } } diff --git a/src/main/java/net/h31ix/anticheat/manage/CheckManager.java b/src/main/java/net/h31ix/anticheat/manage/CheckManager.java index cf785e2..4824129 100644 --- a/src/main/java/net/h31ix/anticheat/manage/CheckManager.java +++ b/src/main/java/net/h31ix/anticheat/manage/CheckManager.java @@ -27,109 +27,86 @@ import org.bukkit.entity.Player; /** *

- * The manager that AntiCheat will check with to see if it should watch certain - * checks and certain players. + * The manager that AntiCheat will check with to see if it should watch certain checks and certain players. */ -public class CheckManager -{ - private AnticheatManager manager = null; - private static List checkIgnoreList = new ArrayList(); - private static Map> exemptList = new HashMap>(); - private static int disabled = 0; - private static int exempt = 0; - - public CheckManager(AnticheatManager instance) - { - manager = instance; - } - - public void activateCheck(CheckType type) - { - if (isActive(type)) - { - manager.log("The " + type.toString() + " check was activated."); - checkIgnoreList.remove(type); - } - } - - public void deactivateCheck(CheckType type) - { - if (!isActive(type)) - { - manager.log("The " + type.toString() + " check was deactivated."); - checkIgnoreList.add(type); - disabled++; - } - } - - public boolean isActive(CheckType type) - { - return !checkIgnoreList.contains(type); - } - - public void exemptPlayer(Player player, CheckType type) - { - if (!isExempt(player, type)) - { - if(!exemptList.containsKey(player.getName())) - { - exemptList.put(player.getName(), new ArrayList()); - } - manager.log(player.getName() + " was exempted from the " + type.toString() + " check."); - exemptList.get(player.getName()).add(type); - exempt++; - } - } - - public void unexemptPlayer(Player player, CheckType type) - { - if (isExempt(player, type)) - { - manager.log(player.getName() + " was re-added to the " + type.toString() + " check."); - exemptList.get(player.getName()).remove(type); - } - } - - public boolean isExempt(Player player, CheckType type) - { - return exemptList.containsKey(player.getName()) ? exemptList.get(player.getName()).contains(type) : false; - } - - public boolean isOpExempt(Player player) - { - return (this.manager.getConfiguration().opExempt() && player.isOp()); - } - - public boolean willCheck(Player player, CheckType type) - { - return isActive(type) && manager.getConfiguration().checkInWorld(player.getWorld()) && !isExempt(player, type) && !type.checkPermission(player) && isOnline(player) && !isOpExempt(player); - } - - public boolean isOnline(Player player) - { - // Check if the player is on the user list, e.g. is not an NPC - for(Player p : Bukkit.getOnlinePlayers()) - { - if(p.getName().equals(player.getName())) - { - return true; - } - } - return false; - } - - public int getExempt() - { - int x = exempt; - exempt = 0; - return x; - } - - public int getDisabled() - { - int x = disabled; - disabled = 0; - return x; - } +public class CheckManager { + private AnticheatManager manager = null; + private static List checkIgnoreList = new ArrayList(); + private static Map> exemptList = new HashMap>(); + private static int disabled = 0; + private static int exempt = 0; + + public CheckManager(AnticheatManager instance) { + manager = instance; + } + + public void activateCheck(CheckType type) { + if (isActive(type)) { + manager.log("The " + type.toString() + " check was activated."); + checkIgnoreList.remove(type); + } + } + + public void deactivateCheck(CheckType type) { + if (!isActive(type)) { + manager.log("The " + type.toString() + " check was deactivated."); + checkIgnoreList.add(type); + disabled++; + } + } + + public boolean isActive(CheckType type) { + return !checkIgnoreList.contains(type); + } + + public void exemptPlayer(Player player, CheckType type) { + if (!isExempt(player, type)) { + if (!exemptList.containsKey(player.getName())) { + exemptList.put(player.getName(), new ArrayList()); + } + manager.log(player.getName() + " was exempted from the " + type.toString() + " check."); + exemptList.get(player.getName()).add(type); + exempt++; + } + } + + public void unexemptPlayer(Player player, CheckType type) { + if (isExempt(player, type)) { + manager.log(player.getName() + " was re-added to the " + type.toString() + " check."); + exemptList.get(player.getName()).remove(type); + } + } + + public boolean isExempt(Player player, CheckType type) { + return exemptList.containsKey(player.getName()) ? exemptList.get(player.getName()).contains(type) : false; + } + + public boolean isOpExempt(Player player) { + return (this.manager.getConfiguration().opExempt() && player.isOp()); + } + + public boolean willCheck(Player player, CheckType type) { + return isActive(type) && manager.getConfiguration().checkInWorld(player.getWorld()) && !isExempt(player, type) && !type.checkPermission(player) && isOnline(player) && !isOpExempt(player); + } + + public boolean isOnline(Player player) { + // Check if the player is on the user list, e.g. is not an NPC + for (Player p : Bukkit.getOnlinePlayers()) { + if (p.getName().equals(player.getName())) { return true; } + } + return false; + } + + public int getExempt() { + int x = exempt; + exempt = 0; + return x; + } + + public int getDisabled() { + int x = disabled; + disabled = 0; + return x; + } } diff --git a/src/main/java/net/h31ix/anticheat/manage/CheckType.java b/src/main/java/net/h31ix/anticheat/manage/CheckType.java index 8ae3d2c..d909fca 100644 --- a/src/main/java/net/h31ix/anticheat/manage/CheckType.java +++ b/src/main/java/net/h31ix/anticheat/manage/CheckType.java @@ -28,67 +28,60 @@ import org.bukkit.entity.Player; * All the types of checks and their corresponding permission nodes. */ -public enum CheckType -{ - ZOMBE_FLY(Permission.CHECK_ZOMBE_FLY), - ZOMBE_NOCLIP(Permission.CHECK_ZOMBE_NOCLIP), - ZOMBE_CHEAT(Permission.CHECK_ZOMBE_CHEAT), - FLY(Permission.CHECK_FLY), - WATER_WALK(Permission.CHECK_WATERWALK), - NO_SWING(Permission.CHECK_NOSWING), - FAST_BREAK(Permission.CHECK_FASTBREAK), - FAST_PLACE(Permission.CHECK_FASTPLACE), - SPAM(Permission.CHECK_SPAM), - SPRINT(Permission.CHECK_SPRINT), - SNEAK(Permission.CHECK_SNEAK), - SPEED(Permission.CHECK_SPEED), - VCLIP(Permission.CHECK_VCLIP), - SPIDER(Permission.CHECK_SPIDER), - NOFALL(Permission.CHECK_NOFALL), - FAST_BOW(Permission.CHECK_FASTBOW), - FAST_EAT(Permission.CHECK_FASTEAT), - FAST_HEAL(Permission.CHECK_FASTHEAL), - FORCEFIELD(Permission.CHECK_FORCEFIELD), - XRAY(Permission.CHECK_XRAY), - LONG_REACH(Permission.CHECK_LONGREACH), - FAST_PROJECTILE(Permission.CHECK_FASTPROJECTILE), - ITEM_SPAM(Permission.CHECK_ITEMSPAM), - FAST_INVENTORY(Permission.CHECK_FASTINVENTORY), - AUTOTOOL(Permission.CHECK_AUTOTOOL); - - private final Permission permission; - private final Map level = new HashMap(); - - private CheckType(Permission perm) - { - this.permission = perm; - } - - public boolean checkPermission(Player player) - { - return permission.get(player); - } - - public void logUse(String name) - { - int amount = level.get(name) == null ? 1 : level.get(name) + 1; - level.put(name, amount); - } - - public void clearUse(String name) - { - level.put(name, 0); - } - - public int getUses(String name) - { - return level.get(name) != null ? level.get(name) : 0; - } - - public static String getName(CheckType type) - { - char[] chars = type.toString().replaceAll("_", " ").toLowerCase().toCharArray(); - chars[0] = Character.toUpperCase(chars[0]); - return new String(chars); - } +public enum CheckType { + ZOMBE_FLY(Permission.CHECK_ZOMBE_FLY), + ZOMBE_NOCLIP(Permission.CHECK_ZOMBE_NOCLIP), + ZOMBE_CHEAT(Permission.CHECK_ZOMBE_CHEAT), + FLY(Permission.CHECK_FLY), + WATER_WALK(Permission.CHECK_WATERWALK), + NO_SWING(Permission.CHECK_NOSWING), + FAST_BREAK(Permission.CHECK_FASTBREAK), + FAST_PLACE(Permission.CHECK_FASTPLACE), + SPAM(Permission.CHECK_SPAM), + SPRINT(Permission.CHECK_SPRINT), + SNEAK(Permission.CHECK_SNEAK), + SPEED(Permission.CHECK_SPEED), + VCLIP(Permission.CHECK_VCLIP), + SPIDER(Permission.CHECK_SPIDER), + NOFALL(Permission.CHECK_NOFALL), + FAST_BOW(Permission.CHECK_FASTBOW), + FAST_EAT(Permission.CHECK_FASTEAT), + FAST_HEAL(Permission.CHECK_FASTHEAL), + FORCEFIELD(Permission.CHECK_FORCEFIELD), + XRAY(Permission.CHECK_XRAY), + LONG_REACH(Permission.CHECK_LONGREACH), + FAST_PROJECTILE(Permission.CHECK_FASTPROJECTILE), + ITEM_SPAM(Permission.CHECK_ITEMSPAM), + FAST_INVENTORY(Permission.CHECK_FASTINVENTORY), + AUTOTOOL(Permission.CHECK_AUTOTOOL); + + private final Permission permission; + private final Map level = new HashMap(); + + private CheckType(Permission perm) { + this.permission = perm; + } + + public boolean checkPermission(Player player) { + return permission.get(player); + } + + public void logUse(String name) { + int amount = level.get(name) == null ? 1 : level.get(name) + 1; + level.put(name, amount); + } + + public void clearUse(String name) { + level.put(name, 0); + } + + public int getUses(String name) { + return level.get(name) != null ? level.get(name) : 0; + } + + public static String getName(CheckType type) { + char[] chars = type.toString().replaceAll("_", " ").toLowerCase().toCharArray(); + chars[0] = Character.toUpperCase(chars[0]); + return new String(chars); + } } diff --git a/src/main/java/net/h31ix/anticheat/manage/User.java b/src/main/java/net/h31ix/anticheat/manage/User.java index 5e33b96..bad3e84 100644 --- a/src/main/java/net/h31ix/anticheat/manage/User.java +++ b/src/main/java/net/h31ix/anticheat/manage/User.java @@ -21,137 +21,102 @@ package net.h31ix.anticheat.manage; import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.util.Configuration; import net.h31ix.anticheat.util.Utilities; - import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; -public class User -{ - private final String name; - private int level = 0; - private int high; - private int med; - private Location goodLocation; - private boolean silentMode; - - public User(String name) - { - this.name = name; - getConfigInfo(); - } - - public User(String name, int level) - { - this.name = name; - this.level = level; - getConfigInfo(); - } - - private void getConfigInfo() - { - Configuration config = Anticheat.getManager().getConfiguration(); - silentMode = config.silentMode(); - med = config.medThreshold(); - high = config.highThreshold(); - } - - public String getName() - { - return name; - } - - public Player getPlayer() - { - return Bukkit.getPlayer(name); - } - - public int getLevel() - { - return level; - } - - public boolean increaseLevel(CheckType type) - { - if(getPlayer() != null && getPlayer().isOnline()) - { - if(silentMode && type.getUses(name) % 4 != 0) - { - // Prevent silent mode from increasing the level way too fast - return false; - } - else - { - level++; - if(level == med) - { - Anticheat.getManager().getUserManager().alertMed(this, type); - } - else if(level == high) - { - Anticheat.getManager().getUserManager().alertHigh(this, type); - // Prevent the player from going over the high limit - level = high-10; - } - return true; - } - } - else - { - return false; - } - } - - public void decreaseLevel() - { - level = level != 0 ? level-1 : 0; - } - - public void setLevel(int level) - { - if(level > 0 && level <= high) - { - this.level = level; - } - } - - public void resetLevel() - { - level = 0; - for (CheckType type : CheckType.values()) - { - type.clearUse(name); - } - } - - public Location getGoodLocation(Location e) - { - if(goodLocation == null) - { - return e; - } - - return goodLocation; - } - - public boolean hasGoodLocation() - { - return goodLocation != null; - } - - public void setGoodLocation(Location e) - { - if(Utilities.cantStandAtExp(e)) - { - return; - } - - if(e.getBlock().isLiquid() && !Utilities.isFullyInWater(e)) - { - return; - } - - goodLocation = e; - } - +public class User { + private final String name; + private int level = 0; + private int high; + private int med; + private Location goodLocation; + private boolean silentMode; + + public User(String name) { + this.name = name; + getConfigInfo(); + } + + public User(String name, int level) { + this.name = name; + this.level = level; + getConfigInfo(); + } + + private void getConfigInfo() { + Configuration config = Anticheat.getManager().getConfiguration(); + silentMode = config.silentMode(); + med = config.medThreshold(); + high = config.highThreshold(); + } + + public String getName() { + return name; + } + + public Player getPlayer() { + return Bukkit.getPlayer(name); + } + + public int getLevel() { + return level; + } + + public boolean increaseLevel(CheckType type) { + if (getPlayer() != null && getPlayer().isOnline()) { + if (silentMode && type.getUses(name) % 4 != 0) { + // Prevent silent mode from increasing the level way too fast + return false; + } else { + level++; + if (level == med) { + Anticheat.getManager().getUserManager().alertMed(this, type); + } else if (level == high) { + Anticheat.getManager().getUserManager().alertHigh(this, type); + // Prevent the player from going over the high limit + level = high - 10; + } + return true; + } + } else { + return false; + } + } + + public void decreaseLevel() { + level = level != 0 ? level - 1 : 0; + } + + public void setLevel(int level) { + if (level > 0 && level <= high) { + this.level = level; + } + } + + public void resetLevel() { + level = 0; + for (CheckType type : CheckType.values()) { + type.clearUse(name); + } + } + + public Location getGoodLocation(Location e) { + if (goodLocation == null) { return e; } + + return goodLocation; + } + + public boolean hasGoodLocation() { + return goodLocation != null; + } + + public void setGoodLocation(Location e) { + if (Utilities.cantStandAtExp(e)) { return; } + + if (e.getBlock().isLiquid() && !Utilities.isFullyInWater(e)) { return; } + + goodLocation = e; + } + } diff --git a/src/main/java/net/h31ix/anticheat/manage/UserManager.java b/src/main/java/net/h31ix/anticheat/manage/UserManager.java index 0ee1c8b..7b36342 100644 --- a/src/main/java/net/h31ix/anticheat/manage/UserManager.java +++ b/src/main/java/net/h31ix/anticheat/manage/UserManager.java @@ -26,174 +26,133 @@ import net.h31ix.anticheat.util.Utilities; import org.bukkit.Bukkit; import org.bukkit.ChatColor; -public class UserManager -{ - private List users = new ArrayList(); - private static Configuration config; - private static Language lang; - private static final ChatColor GRAY = ChatColor.GRAY; - private static final ChatColor GOLD = ChatColor.GOLD; - private static final ChatColor YELLOW = ChatColor.YELLOW; - private static final ChatColor RED = ChatColor.RED; - - public UserManager(Configuration conf) - { - config = conf; - lang = conf.getLang(); - } - - public User getUser(String name) - { - for(User user : users) - { - if(user.getName().equalsIgnoreCase(name)) - { - return user; - } - } - // Otherwise try to load them - return loadUserFromFile(name); - } - - public List getUsers() - { - return users; - } - - public void addUser(User user) - { - users.add(user); - } - - public void remove(User user) - { - config.saveLevel(user.getName(), user.getLevel()); - users.remove(user); - } - - public int safeGetLevel(String name) - { - User user = getUser(name); - if(user == null) - { - return 0; - } - else - { - return user.getLevel(); - } - } - - public void safeSetLevel(String name, int level) - { - User user = getUser(name); - if(user != null) - { - user.setLevel(level); - } - } - - public void safeReset(String name) - { - User user = getUser(name); - if(user != null) - { - user.resetLevel(); - } - } - - public boolean addUserFromFile(String name) - { - User user = loadUserFromFile(name); - if(user != null) - { - users.add(user); - return true; - } - else - { - return false; - } - } - - public User loadUserFromFile(String name) - { - int level = config.getLevel(name); - if(level == -1) - { - return null; - } - else - { - return new User(name, level); - } - } - - public void alertMed(User user, CheckType type) - { - List messageArray = lang.getMediumAlert(); - for(int i=0;i messageArray = lang.getHighAlert(); - for(int i=0;i message = lang.getWarning(); - for (String string : message) - { - user.getPlayer().sendMessage(RED + string); - } - } - else if (event.equalsIgnoreCase("BAN")) - { - user.getPlayer().setBanned(true); - user.getPlayer().kickPlayer(RED + lang.getBanReason()); - String msg = RED + lang.getBanBroadcast().replaceAll("&player", name); - if(!msg.equals("")) - { - Bukkit.broadcastMessage(msg); - } - } - } - +public class UserManager { + private List users = new ArrayList(); + private static Configuration config; + private static Language lang; + private static final ChatColor GRAY = ChatColor.GRAY; + private static final ChatColor GOLD = ChatColor.GOLD; + private static final ChatColor YELLOW = ChatColor.YELLOW; + private static final ChatColor RED = ChatColor.RED; + + public UserManager(Configuration conf) { + config = conf; + lang = conf.getLang(); + } + + public User getUser(String name) { + for (User user : users) { + if (user.getName().equalsIgnoreCase(name)) { return user; } + } + // Otherwise try to load them + return loadUserFromFile(name); + } + + public List getUsers() { + return users; + } + + public void addUser(User user) { + users.add(user); + } + + public void remove(User user) { + config.saveLevel(user.getName(), user.getLevel()); + users.remove(user); + } + + public int safeGetLevel(String name) { + User user = getUser(name); + if (user == null) { + return 0; + } else { + return user.getLevel(); + } + } + + public void safeSetLevel(String name, int level) { + User user = getUser(name); + if (user != null) { + user.setLevel(level); + } + } + + public void safeReset(String name) { + User user = getUser(name); + if (user != null) { + user.resetLevel(); + } + } + + public boolean addUserFromFile(String name) { + User user = loadUserFromFile(name); + if (user != null) { + users.add(user); + return true; + } else { + return false; + } + } + + public User loadUserFromFile(String name) { + int level = config.getLevel(name); + if (level == -1) { + return null; + } else { + return new User(name, level); + } + } + + public void alertMed(User user, CheckType type) { + List messageArray = lang.getMediumAlert(); + for (int i = 0; i < messageArray.size(); i++) { + String message = messageArray.get(i); + message = message.replaceAll("&player", GOLD + user.getName() + GRAY); + message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY); + message = message.replaceAll("medium", YELLOW + "medium" + GRAY); + messageArray.set(i, message); + } + Utilities.alert(messageArray); + execute(user, config.mediumEvent()); + } + + public void alertHigh(User user, CheckType type) { + List messageArray = lang.getHighAlert(); + for (int i = 0; i < messageArray.size(); i++) { + String message = messageArray.get(i); + message = message.replaceAll("&player", GOLD + user.getName() + GRAY); + message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY); + message = message.replaceAll("high", RED + "high" + GRAY); + messageArray.set(i, message); + } + Utilities.alert(messageArray); + execute(user, config.highEvent()); + } + + public void execute(User user, String event) { + final String name = user.getName(); + if (event.startsWith("COMMAND[")) { + String command = event.replaceAll("COMMAND\\[", "").replaceAll("]", "").replaceAll("&player", name).replaceAll("&world", user.getPlayer().getWorld().getName()); + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command); + } else if (event.equalsIgnoreCase("KICK")) { + user.getPlayer().kickPlayer(RED + lang.getKickReason()); + String msg = RED + lang.getKickBroadcast().replaceAll("&player", name); + if (!msg.equals("")) { + Bukkit.broadcastMessage(msg); + } + } else if (event.equalsIgnoreCase("WARN")) { + List message = lang.getWarning(); + for (String string : message) { + user.getPlayer().sendMessage(RED + string); + } + } else if (event.equalsIgnoreCase("BAN")) { + user.getPlayer().setBanned(true); + user.getPlayer().kickPlayer(RED + lang.getBanReason()); + String msg = RED + lang.getBanBroadcast().replaceAll("&player", name); + if (!msg.equals("")) { + Bukkit.broadcastMessage(msg); + } + } + } + } diff --git a/src/main/java/net/h31ix/anticheat/metrics/Metrics.java b/src/main/java/net/h31ix/anticheat/metrics/Metrics.java index 40427b4..0aabd62 100644 --- a/src/main/java/net/h31ix/anticheat/metrics/Metrics.java +++ b/src/main/java/net/h31ix/anticheat/metrics/Metrics.java @@ -41,8 +41,7 @@ import org.bukkit.plugin.PluginDescriptionFile; /** *

- * The metrics class obtains data about a plugin and submits statistics about it - * to the metrics backend. + * The metrics class obtains data about a plugin and submits statistics about it to the metrics backend. *

*

* Public methods provided by this class: @@ -53,489 +52,413 @@ import org.bukkit.plugin.PluginDescriptionFile; * void start();
* */ -public class Metrics -{ - - /** - * The current revision number - */ - private static final int REVISION = 5; - - /** - * The base url of the metrics domain - */ - private static final String BASE_URL = "http://metrics.griefcraft.com"; - - /** - * The url used to report a server's status - */ - private static final String REPORT_URL = "/report/%s"; - - /** - * The file where guid and opt out is stored in - */ - private static final String CONFIG_FILE = "plugins/PluginMetrics/config.yml"; - - /** - * The separator to use for custom data. This MUST NOT change unless you are - * hosting your own version of metrics and want to change it. - */ - private static final String CUSTOM_DATA_SEPARATOR = "~~"; - - /** - * Interval of time to ping (in minutes) - */ - private static final int PING_INTERVAL = 10; - - /** - * The plugin this metrics submits for - */ - private final Plugin plugin; - - /** - * All of the custom graphs to submit to metrics - */ - private final Set graphs = Collections.synchronizedSet(new HashSet()); - - /** - * The default graph, used for addCustomData when you don't want a specific - * graph - */ - private final Graph defaultGraph = new Graph("Default"); - - /** - * The plugin configuration file - */ - private final YamlConfiguration configuration; - - /** - * Unique server id - */ - private final String guid; - - public Metrics(Plugin plugin) throws IOException - { - if (plugin == null) - { - throw new IllegalArgumentException("Plugin cannot be null"); - } - - this.plugin = plugin; - - // load the config - File file = new File(CONFIG_FILE); - configuration = YamlConfiguration.loadConfiguration(file); - - // add some defaults - configuration.addDefault("opt-out", false); - configuration.addDefault("guid", UUID.randomUUID().toString()); - - // Do we need to create the file? - if (configuration.get("guid", null) == null) - { - configuration.options().header("http://metrics.griefcraft.com").copyDefaults(true); - configuration.save(file); - } - - // Load the guid then - guid = configuration.getString("guid"); - } - - /** - * Construct and create a Graph that can be used to separate specific - * plotters to their own graphs on the metrics website. Plotters can be - * added to the graph object returned. - * - * @param name - * @return Graph object created. Will never return NULL under normal - * circumstances unless bad parameters are given - */ - public Graph createGraph(String name) - { - if (name == null) - { - throw new IllegalArgumentException("Graph name cannot be null"); - } - - // Construct the graph object - Graph graph = new Graph(name); - - // Now we can add our graph - graphs.add(graph); - - // and return back - return graph; - } - - /** - * Adds a custom data plotter to the default graph - * - * @param plotter - */ - public void addCustomData(Plotter plotter) - { - if (plotter == null) - { - throw new IllegalArgumentException("Plotter cannot be null"); - } - - // Add the plotter to the graph o/ - defaultGraph.addPlotter(plotter); - - // Ensure the default graph is included in the submitted graphs - graphs.add(defaultGraph); - } - - /** - * Start measuring statistics. This will immediately create an async - * repeating task as the plugin and send the initial data to the metrics - * backend, and then after that it will post in increments of PING_INTERVAL - * * 1200 ticks. - */ - public void start() - { - // Did we opt out? - if (configuration.getBoolean("opt-out", false)) - { - return; - } - - // Begin hitting the server with glorious data - plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() - { - private boolean firstPost = true; - - @Override - public void run() - { - try - { - // We use the inverse of firstPost because if it is the first time we are posting, - // it is not a interval ping, so it evaluates to FALSE - // Each time thereafter it will evaluate to TRUE, i.e PING! - postPlugin(!firstPost); - - // After the first post we set firstPost to false - // Each post thereafter will be a ping - firstPost = false; - } - catch (IOException e) - { - System.err.println("[Metrics] " + e.getMessage()); - } - } - }, 0, PING_INTERVAL * 1200); - } - - /** - * Generic method that posts a plugin to the metrics website - */ - private void postPlugin(boolean isPing) throws IOException - { - // The plugin's description file containg all of the plugin data such as name, version, author, etc - PluginDescriptionFile description = plugin.getDescription(); - - // Construct the post data - String data = encode("guid") + '=' + encode(guid) + encodeDataPair("version", description.getVersion().split("-b")[0]) + encodeDataPair("server", Bukkit.getVersion()) + encodeDataPair("players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)) + encodeDataPair("revision", String.valueOf(REVISION)); - - // If we're pinging, append it - if (isPing) - { - data += encodeDataPair("ping", "true"); - } - - // Acquire a lock on the graphs, which lets us make the assumption we also lock everything - // inside of the graph (e.g plotters) - synchronized (graphs) - { - Iterator iter = graphs.iterator(); - - while (iter.hasNext()) - { - Graph graph = iter.next(); - - // Because we have a lock on the graphs set already, it is reasonable to assume - // that our lock transcends down to the individual plotters in the graphs also. - // Because our methods are private, no one but us can reasonably access this list - // without reflection so this is a safe assumption without adding more code. - for (Plotter plotter : graph.getPlotters()) - { - // The key name to send to the metrics server - // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top - // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME - String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); - - // The value to send, which for the foreseeable future is just the string - // value of plotter.getValue() - String value = Integer.toString(plotter.getValue()); - - // Add it to the http post data :) - data += encodeDataPair(key, value); - } - } - } - - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, description.getName())); - - // Connect to the website - URLConnection connection; - - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) - { - connection = url.openConnection(Proxy.NO_PROXY); - } - else - { - connection = url.openConnection(); - } - - connection.setDoOutput(true); - - // Write the data - OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); - writer.write(data); - writer.flush(); - - // Now read the response - BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String response = reader.readLine(); - - // close resources - writer.close(); - reader.close(); - - if (response.startsWith("ERR")) - { - throw new IOException(response); //Throw the exception - } - else - { - // Is this the first update this hour? - if (response.contains("OK This is your first update this hour")) - { - synchronized (graphs) - { - Iterator iter = graphs.iterator(); - - while (iter.hasNext()) - { - Graph graph = iter.next(); - - for (Plotter plotter : graph.getPlotters()) - { - plotter.reset(); - } - } - } - } - } - //if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right - } - - /** - * Check if mineshafter is present. If it is, we need to bypass it to send - * POST requests - * - * @return - */ - private boolean isMineshafterPresent() - { - try - { - Class.forName("mineshafter.MineServer"); - return true; - } - catch (Exception e) - { - return false; - } - } - - /** - *

- * Encode a key/value data pair to be used in a HTTP post request. This - * INCLUDES a & so the first key/value pair MUST be included manually, e.g: - *

- * - * String httpData = encode("guid") + '=' + encode("1234") + encodeDataPair("authors") + ".."; - * - * - * @param key - * @param value - * @return - */ - private static String encodeDataPair(String key, String value) throws UnsupportedEncodingException - { - return '&' + encode(key) + '=' + encode(value); - } - - /** - * Encode text as UTF-8 - * - * @param text - * @return - */ - private static String encode(String text) throws UnsupportedEncodingException - { - return URLEncoder.encode(text, "UTF-8"); - } - - /** - * Represents a custom graph on the website - */ - public static class Graph - { - - /** - * The graph's name, alphanumeric and spaces only :) If it does not - * comply to the above when submitted, it is rejected - */ - private final String name; - - /** - * The set of plotters that are contained within this graph - */ - private final Set plotters = new LinkedHashSet(); - - private Graph(String name) - { - this.name = name; - } - - /** - * Gets the graph's name - * - * @return - */ - public String getName() - { - return name; - } - - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter - */ - public void addPlotter(Plotter plotter) - { - plotters.add(plotter); - } - - /** - * Remove a plotter from the graph - * - * @param plotter - */ - public void removePlotter(Plotter plotter) - { - plotters.remove(plotter); - } - - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return - */ - public Set getPlotters() - { - return Collections.unmodifiableSet(plotters); - } - - @Override - public int hashCode() - { - return name.hashCode(); - } - - @Override - public boolean equals(Object object) - { - if (!(object instanceof Graph)) - { - return false; - } - - Graph graph = (Graph) object; - return graph.name.equals(name); - } - - } - - /** - * Interface used to collect custom data for a plugin - */ - public static abstract class Plotter - { - - /** - * The plot's name - */ - private final String name; - - /** - * Construct a plotter with the default plot name - */ - public Plotter() - { - this("Default"); - } - - /** - * Construct a plotter with a specific plot name - * - * @param name - */ - public Plotter(String name) - { - this.name = name; - } - - /** - * Get the current value for the plotted point - * - * @return - */ - public abstract int getValue(); - - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() - { - return name; - } - - /** - * Called after the website graphs have been updated - */ - public void reset() - { - } - - @Override - public int hashCode() - { - return getColumnName().hashCode() + getValue(); - } - - @Override - public boolean equals(Object object) - { - if (!(object instanceof Plotter)) - { - return false; - } - - Plotter plotter = (Plotter) object; - return plotter.name.equals(name) && plotter.getValue() == getValue(); - } - - } - +public class Metrics { + + /** + * The current revision number + */ + private static final int REVISION = 5; + + /** + * The base url of the metrics domain + */ + private static final String BASE_URL = "http://metrics.griefcraft.com"; + + /** + * The url used to report a server's status + */ + private static final String REPORT_URL = "/report/%s"; + + /** + * The file where guid and opt out is stored in + */ + private static final String CONFIG_FILE = "plugins/PluginMetrics/config.yml"; + + /** + * The separator to use for custom data. This MUST NOT change unless you are hosting your own version of metrics and want to change it. + */ + private static final String CUSTOM_DATA_SEPARATOR = "~~"; + + /** + * Interval of time to ping (in minutes) + */ + private static final int PING_INTERVAL = 10; + + /** + * The plugin this metrics submits for + */ + private final Plugin plugin; + + /** + * All of the custom graphs to submit to metrics + */ + private final Set graphs = Collections.synchronizedSet(new HashSet()); + + /** + * The default graph, used for addCustomData when you don't want a specific graph + */ + private final Graph defaultGraph = new Graph("Default"); + + /** + * The plugin configuration file + */ + private final YamlConfiguration configuration; + + /** + * Unique server id + */ + private final String guid; + + public Metrics(Plugin plugin) throws IOException { + if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); } + + this.plugin = plugin; + + // load the config + File file = new File(CONFIG_FILE); + configuration = YamlConfiguration.loadConfiguration(file); + + // add some defaults + configuration.addDefault("opt-out", false); + configuration.addDefault("guid", UUID.randomUUID().toString()); + + // Do we need to create the file? + if (configuration.get("guid", null) == null) { + configuration.options().header("http://metrics.griefcraft.com").copyDefaults(true); + configuration.save(file); + } + + // Load the guid then + guid = configuration.getString("guid"); + } + + /** + * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics website. Plotters can be added to the graph object returned. + * + * @param name + * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given + */ + public Graph createGraph(String name) { + if (name == null) { throw new IllegalArgumentException("Graph name cannot be null"); } + + // Construct the graph object + Graph graph = new Graph(name); + + // Now we can add our graph + graphs.add(graph); + + // and return back + return graph; + } + + /** + * Adds a custom data plotter to the default graph + * + * @param plotter + */ + public void addCustomData(Plotter plotter) { + if (plotter == null) { throw new IllegalArgumentException("Plotter cannot be null"); } + + // Add the plotter to the graph o/ + defaultGraph.addPlotter(plotter); + + // Ensure the default graph is included in the submitted graphs + graphs.add(defaultGraph); + } + + /** + * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 ticks. + */ + public void start() { + // Did we opt out? + if (configuration.getBoolean("opt-out", false)) { return; } + + // Begin hitting the server with glorious data + plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() { + private boolean firstPost = true; + + @Override + public void run() { + try { + // We use the inverse of firstPost because if it is the first time we are posting, + // it is not a interval ping, so it evaluates to FALSE + // Each time thereafter it will evaluate to TRUE, i.e PING! + postPlugin(!firstPost); + + // After the first post we set firstPost to false + // Each post thereafter will be a ping + firstPost = false; + } catch (IOException e) { + System.err.println("[Metrics] " + e.getMessage()); + } + } + }, 0, PING_INTERVAL * 1200); + } + + /** + * Generic method that posts a plugin to the metrics website + */ + private void postPlugin(boolean isPing) throws IOException { + // The plugin's description file containg all of the plugin data such as name, version, author, etc + PluginDescriptionFile description = plugin.getDescription(); + + // Construct the post data + String data = encode("guid") + '=' + encode(guid) + encodeDataPair("version", description.getVersion().split("-b")[0]) + encodeDataPair("server", Bukkit.getVersion()) + encodeDataPair("players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)) + encodeDataPair("revision", String.valueOf(REVISION)); + + // If we're pinging, append it + if (isPing) { + data += encodeDataPair("ping", "true"); + } + + // Acquire a lock on the graphs, which lets us make the assumption we also lock everything + // inside of the graph (e.g plotters) + synchronized (graphs) { + Iterator iter = graphs.iterator(); + + while (iter.hasNext()) { + Graph graph = iter.next(); + + // Because we have a lock on the graphs set already, it is reasonable to assume + // that our lock transcends down to the individual plotters in the graphs also. + // Because our methods are private, no one but us can reasonably access this list + // without reflection so this is a safe assumption without adding more code. + for (Plotter plotter : graph.getPlotters()) { + // The key name to send to the metrics server + // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top + // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME + String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); + + // The value to send, which for the foreseeable future is just the string + // value of plotter.getValue() + String value = Integer.toString(plotter.getValue()); + + // Add it to the http post data :) + data += encodeDataPair(key, value); + } + } + } + + // Create the url + URL url = new URL(BASE_URL + String.format(REPORT_URL, description.getName())); + + // Connect to the website + URLConnection connection; + + // Mineshafter creates a socks proxy, so we can safely bypass it + // It does not reroute POST requests so we need to go around it + if (isMineshafterPresent()) { + connection = url.openConnection(Proxy.NO_PROXY); + } else { + connection = url.openConnection(); + } + + connection.setDoOutput(true); + + // Write the data + OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); + writer.write(data); + writer.flush(); + + // Now read the response + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String response = reader.readLine(); + + // close resources + writer.close(); + reader.close(); + + if (response.startsWith("ERR")) { + throw new IOException(response); // Throw the exception + } else { + // Is this the first update this hour? + if (response.contains("OK This is your first update this hour")) { + synchronized (graphs) { + Iterator iter = graphs.iterator(); + + while (iter.hasNext()) { + Graph graph = iter.next(); + + for (Plotter plotter : graph.getPlotters()) { + plotter.reset(); + } + } + } + } + } + // if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right + } + + /** + * Check if mineshafter is present. If it is, we need to bypass it to send POST requests + * + * @return + */ + private boolean isMineshafterPresent() { + try { + Class.forName("mineshafter.MineServer"); + return true; + } catch (Exception e) { + return false; + } + } + + /** + *

+ * Encode a key/value data pair to be used in a HTTP post request. This INCLUDES a & so the first key/value pair MUST be included manually, e.g: + *

+ * + * String httpData = encode("guid") + '=' + encode("1234") + encodeDataPair("authors") + ".."; + * + * + * @param key + * @param value + * @return + */ + private static String encodeDataPair(String key, String value) throws UnsupportedEncodingException { + return '&' + encode(key) + '=' + encode(value); + } + + /** + * Encode text as UTF-8 + * + * @param text + * @return + */ + private static String encode(String text) throws UnsupportedEncodingException { + return URLEncoder.encode(text, "UTF-8"); + } + + /** + * Represents a custom graph on the website + */ + public static class Graph { + + /** + * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is rejected + */ + private final String name; + + /** + * The set of plotters that are contained within this graph + */ + private final Set plotters = new LinkedHashSet(); + + private Graph(String name) { + this.name = name; + } + + /** + * Gets the graph's name + * + * @return + */ + public String getName() { + return name; + } + + /** + * Add a plotter to the graph, which will be used to plot entries + * + * @param plotter + */ + public void addPlotter(Plotter plotter) { + plotters.add(plotter); + } + + /** + * Remove a plotter from the graph + * + * @param plotter + */ + public void removePlotter(Plotter plotter) { + plotters.remove(plotter); + } + + /** + * Gets an unmodifiable set of the plotter objects in the graph + * + * @return + */ + public Set getPlotters() { + return Collections.unmodifiableSet(plotters); + } + + @Override + public int hashCode() { + return name.hashCode(); + } + + @Override + public boolean equals(Object object) { + if (!(object instanceof Graph)) { return false; } + + Graph graph = (Graph) object; + return graph.name.equals(name); + } + + } + + /** + * Interface used to collect custom data for a plugin + */ + public static abstract class Plotter { + + /** + * The plot's name + */ + private final String name; + + /** + * Construct a plotter with the default plot name + */ + public Plotter() { + this("Default"); + } + + /** + * Construct a plotter with a specific plot name + * + * @param name + */ + public Plotter(String name) { + this.name = name; + } + + /** + * Get the current value for the plotted point + * + * @return + */ + public abstract int getValue(); + + /** + * Get the column name for the plotted point + * + * @return the plotted point's column name + */ + public String getColumnName() { + return name; + } + + /** + * Called after the website graphs have been updated + */ + public void reset() { + } + + @Override + public int hashCode() { + return getColumnName().hashCode() + getValue(); + } + + @Override + public boolean equals(Object object) { + if (!(object instanceof Plotter)) { return false; } + + Plotter plotter = (Plotter) object; + return plotter.name.equals(name) && plotter.getValue() == getValue(); + } + + } + } diff --git a/src/main/java/net/h31ix/anticheat/update/Updater.java b/src/main/java/net/h31ix/anticheat/update/Updater.java index 5a65249..d2460bf 100644 --- a/src/main/java/net/h31ix/anticheat/update/Updater.java +++ b/src/main/java/net/h31ix/anticheat/update/Updater.java @@ -35,629 +35,491 @@ import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; /** - * Check dev.bukkit.org to find updates for a given plugin, and download the - * updates if needed. + * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed. *

- * VERY, VERY IMPORTANT: Because there are no standards for - * adding auto-update toggles in your plugin's config, this system provides NO - * CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating.
- * It is a BUKKIT POLICY that you include a boolean value in - * your config that prevents the auto-updater from running AT - * ALL.
- * If you fail to include this option in your config, your plugin will be - * REJECTED when you attempt to submit it to dev.bukkit.org. + * VERY, VERY IMPORTANT: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating.
+ * It is a BUKKIT POLICY that you include a boolean value in your config that prevents the auto-updater from running AT ALL.
+ * If you fail to include this option in your config, your plugin will be REJECTED when you attempt to submit it to dev.bukkit.org. *

- * An example of a good configuration option would be something similar to - * 'auto-update: true' - if this value is set to false you may NOT run the - * auto-updater.
- * If you are unsure about these rules, please read the plugin submission - * guidelines: http://goo.gl/8iU5l + * An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater.
+ * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l * * @author H31IX */ -public class Updater -{ - private Plugin plugin; - private UpdateType type; - private String versionTitle; - private String versionLink; - private long totalSize; // Holds the total size of the file - private double downloadedSize; // TODO: Holds the number of bytes downloaded - private int sizeLine; // Used for detecting file size - private int multiplier; // Used for determining when to broadcast download updates - private boolean announce; // Whether to announce file downloads - private URL url; // Connecting to RSS - private static final String DBOUrl = "http://dev.bukkit.org/server-mods/"; // Slugs will be appended to this to get to the project's RSS feed - private String[] noUpdateTag = { "-DEV", "-PRE" }; // If the version number contains one of these, don't update. - private static final int BYTE_SIZE = 1024; // Used for downloading files - private String updateFolder = YamlConfiguration.loadConfiguration(new File("bukkit.yml")).getString("settings.update-folder"); // The folder that downloads will be placed in - private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process - - // Strings for reading RSS - private static final String TITLE = "title"; - private static final String LINK = "link"; - private static final String ITEM = "item"; - - /** - * Gives the dev the result of the update process. Can be obtained by called - * getResult(). - */ - public enum UpdateResult - { - /** - * The updater found an update, and has readied it to be loaded the next - * time the server restarts/reloads. - */ - SUCCESS(1), - /** - * The updater did not find an update, and nothing was downloaded. - */ - NO_UPDATE(2), - /** - * The updater found an update, but was unable to download it. - */ - FAIL_DOWNLOAD(3), - /** - * For some reason, the updater was unable to contact dev.bukkit.org to - * download the file. - */ - FAIL_DBO(4), - /** - * When running the version check, the file on DBO did not contain the a - * version in the format 'vVersion' such as 'v1.0'. - */ - FAIL_NOVERSION(5), - /** - * The slug provided by the plugin running the updater was invalid and - * doesn't exist on DBO. - */ - FAIL_BADSLUG(6), - /** - * The updater found an update, but because of the UpdateType being set - * to NO_DOWNLOAD, it wasn't downloaded. - */ - UPDATE_AVAILABLE(7), - /** - * The update was unable to update due to a unknown exception thrown. - */ - UNKNOWN_ERROR(8); - - private static final Map valueList = new HashMap(); - private final int value; - - private UpdateResult(int value) - { - this.value = value; - } - - public int getValue() - { - return this.value; - } - - public static Updater.UpdateResult getResult(int value) - { - return valueList.get(value); - } - - static - { - for (Updater.UpdateResult result : Updater.UpdateResult.values()) - { - valueList.put(result.value, result); - } - } - } - - /** - * Allows the dev to specify the type of update that will be run. - */ - public enum UpdateType - { - /** - * Run a version check, and then if the file is out of date, download - * the newest version. - */ - DEFAULT(1), - /** - * Don't run a version check, just find the latest update and download - * it. - */ - NO_VERSION_CHECK(2), - /** - * Get information about the version and the download size, but don't - * actually download anything. - */ - NO_DOWNLOAD(3); - - private static final Map valueList = new HashMap(); - private final int value; - - private UpdateType(int value) - { - this.value = value; - } - - public int getValue() - { - return this.value; - } - - public static Updater.UpdateType getResult(int value) - { - return valueList.get(value); - } - - static - { - for (Updater.UpdateType result : Updater.UpdateType.values()) - { - valueList.put(result.value, result); - } - } - } - - /** - * Initialize the updater - * - * @param plugin - * The plugin that is checking for an update. - * @param slug - * The dev.bukkit.org slug of the project - * (http://dev.bukkit.org/server-mods/SLUG_IS_HERE) - * @param file - * The file that the plugin is running from, get this by doing - * this.getFile() from within your main class. - * @param type - * Specify the type of update this will be. See - * {@link UpdateType} - * @param announce - * True if the program should announce the progress of new - * updates in console - */ - public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) - { - this.plugin = plugin; - this.type = type; - this.announce = announce; - try - { - // Obtain the results of the project's file feed - url = new URL(DBOUrl + slug + "/files.rss"); - if (url != null) - { - // Obtain the results of the project's file feed - readFeed(); - if (versionCheck(versionTitle)) - { - String fileLink = getFile(versionLink); - if (fileLink != null && type != UpdateType.NO_DOWNLOAD) - { - String name = file.getName(); - // If it's a zip file, it shouldn't be downloaded as the plugin's name - if (fileLink.endsWith(".zip")) - { - String[] split = fileLink.split("/"); - name = split[split.length - 1]; - } - saveFile(new File("plugins/" + updateFolder), name, fileLink); - } - else - { - result = UpdateResult.UPDATE_AVAILABLE; - } - } - } - } - catch (MalformedURLException ex) - { - // The slug doesn't exist - plugin.getLogger().warning("The author of this plugin has misconfigured their Auto Update system"); - plugin.getLogger().warning("The project slug added ('" + slug + "') is invalid, and does not exist on dev.bukkit.org"); - result = Updater.UpdateResult.FAIL_BADSLUG; // Bad slug! Bad! - } - catch (RuntimeException ex) - { - // Something went wrong with the updater and can't check for updates. - if (result == Updater.UpdateResult.SUCCESS) - { - plugin.getLogger().warning("An error had occured and Auto Update was unable to check for updates"); - plugin.getLogger().warning("Here is a stacktrace of what happened: "); - ex.printStackTrace(); - result = Updater.UpdateResult.UNKNOWN_ERROR; - } - } - } - - /** - * Get the result of the update process. - */ - public Updater.UpdateResult getResult() - { - return result; - } - - /** - * Get the total bytes of the file (can only be used after running a version - * check or a normal run). - */ - public long getFileSize() - { - return totalSize; - } - - /** - * Get the version string latest file avaliable online. - */ - public String getLatestVersionString() - { - return versionTitle; - } - - /** - * Save an update from dev.bukkit.org into the server's update folder. - */ - private void saveFile(File folder, String file, String u) - { - if (!folder.exists()) - { - folder.mkdir(); - } - BufferedInputStream in = null; - FileOutputStream fout = null; - try - { - // Download the file - URL url = new URL(u); - int fileLength = url.openConnection().getContentLength(); - in = new BufferedInputStream(url.openStream()); - fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file); - - byte[] data = new byte[BYTE_SIZE]; - int count; - if (announce) - plugin.getLogger().info("About to download a new update: " + versionTitle); - long downloaded = 0; - while ((count = in.read(data, 0, BYTE_SIZE)) != -1) - { - downloaded += count; - fout.write(data, 0, count); - int percent = (int) (downloaded * 100 / fileLength); - if (announce & (percent % 10 == 0)) - { - plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); - } - } - //Just a quick check to make sure we didn't leave any files from last time... - for (File xFile : new File("plugins/" + updateFolder).listFiles()) - { - if (xFile.getName().endsWith(".zip")) - { - xFile.delete(); - } - } - // Check to see if it's a zip file, if it is, unzip it. - File dFile = new File(folder.getAbsolutePath() + "/" + file); - if (dFile.getName().endsWith(".zip")) - { - // Unzip - unzip(dFile.getCanonicalPath()); - } - if (announce) - plugin.getLogger().info("Finished updating."); - } - catch (Exception ex) - { - plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); - result = Updater.UpdateResult.FAIL_DOWNLOAD; - } - finally - { - try - { - if (in != null) - { - in.close(); - } - if (fout != null) - { - fout.close(); - } - } - catch (Exception ex) - { - } - } - } - - /** - * Part of Zip-File-Extractor, modified by H31IX for use with Bukkit - */ - private void unzip(String file) - { - try - { - File fSourceZip = new File(file); - String zipPath = file.substring(0, file.length() - 4); - ZipFile zipFile = new ZipFile(fSourceZip); - Enumeration e = zipFile.entries(); - while (e.hasMoreElements()) - { - ZipEntry entry = (ZipEntry) e.nextElement(); - File destinationFilePath = new File(zipPath, entry.getName()); - destinationFilePath.getParentFile().mkdirs(); - if (entry.isDirectory()) - { - continue; - } - else - { - BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); - int b; - byte buffer[] = new byte[BYTE_SIZE]; - FileOutputStream fos = new FileOutputStream(destinationFilePath); - BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE); - while ((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) - { - bos.write(buffer, 0, b); - } - bos.flush(); - bos.close(); - bis.close(); - String name = destinationFilePath.getName(); - if (name.endsWith(".jar") && pluginFile(name)) - { - destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name)); - } - } - entry = null; - destinationFilePath = null; - } - e = null; - zipFile.close(); - zipFile = null; - // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. - for (File dFile : new File(zipPath).listFiles()) - { - if (dFile.isDirectory()) - { - if (pluginFile(dFile.getName())) - { - File oFile = new File("plugins/" + dFile.getName()); // Get current dir - File[] contents = oFile.listFiles(); // List of existing files in the current dir - for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir - { - boolean found = false; - for (File xFile : contents) // Loop through contents to see if it exists - { - if (xFile.getName().equals(cFile.getName())) - { - found = true; - break; - } - } - if (!found) - { - // Move the new file into the current dir - cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); - } - else - { - // This file already exists, so we don't need it anymore. - cFile.delete(); - } - } - } - } - dFile.delete(); - } - new File(zipPath).delete(); - fSourceZip.delete(); - } - catch (IOException ex) - { - ex.printStackTrace(); - plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); - result = Updater.UpdateResult.FAIL_DOWNLOAD; - } - new File(file).delete(); - } - - /** - * Check if the name of a jar is one of the plugins currently installed, - * used for extracting the correct files out of a zip. - */ - public boolean pluginFile(String name) - { - for (File file : new File("plugins").listFiles()) - { - if (file.getName().equals(name)) - { - return true; - } - } - return false; - } - - /** - * Obtain the direct download file url from the file's page. - */ - private String getFile(String link) - { - String download = null; - try - { - // Open a connection to the page - URL url = new URL(link); - URLConnection urlConn = url.openConnection(); - InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream()); - BufferedReader buff = new BufferedReader(inStream); - - int counter = 0; - String line; - while ((line = buff.readLine()) != null) - { - counter++; - // Search for the download link - if (line.contains("

  • ")) - { - // Get the raw link - download = line.split("Download")[0]; - } - // Search for size - else if (line.contains("
    Size
    ")) - { - sizeLine = counter + 1; - } - else if (counter == sizeLine) - { - String size = line.replaceAll("
    ", "").replaceAll("
    ", ""); - multiplier = size.contains("MiB") ? 1048576 : 1024; - size = size.replace(" KiB", "").replace(" MiB", ""); - totalSize = (long) (Double.parseDouble(size) * multiplier); - } - } - urlConn = null; - inStream = null; - buff.close(); - buff = null; - } - catch (Exception ex) - { - ex.printStackTrace(); - plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); - result = Updater.UpdateResult.FAIL_DBO; - return null; - } - return download; - } - - /** - * Check to see if the program should continue by evaluation whether the - * plugin is already updated, or shouldn't be updated - */ - private boolean versionCheck(String title) - { - if (type != UpdateType.NO_VERSION_CHECK) - { - String version = plugin.getDescription().getVersion(); - if (title.split("v").length == 2) - { - String remoteVersion = title.split("v")[1].split(" ")[0]; // Get the newest file's version number - if (hasTag(version, remoteVersion) || version.equalsIgnoreCase(remoteVersion)) - { - // We already have the latest version, or this build is tagged for no-update - result = Updater.UpdateResult.NO_UPDATE; - return false; - } - } - else - { - // The file's name did not contain the string 'vVersion' - plugin.getLogger().warning("The author of this plugin has misconfigured their Auto Update system"); - plugin.getLogger().warning("Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0"); - plugin.getLogger().warning("Please notify the author (" + plugin.getDescription().getAuthors().get(0) + ") of this error."); - result = Updater.UpdateResult.FAIL_NOVERSION; - return false; - } - } - return true; - } - - /** - * Evaluate whether the version number is marked showing that it should not - * be updated by this program - */ - private boolean hasTag(String version, String remoteVersion) - { - for (String string : noUpdateTag) - { - if (version.contains(string)) - { - if (version.replaceAll(string, "").equals(remoteVersion)) - { - // The build has a tag, but the version was upgraded to release so we should do an update anyway - return false; - } - else - { - return true; - } - } - } - return false; - } - - /** - * Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit - */ - @SuppressWarnings({ "deprecation", "restriction" }) - private void readFeed() - { - try - { - // Set header values intial to the empty string - String title = ""; - String link = ""; - // First create a new XMLInputFactory - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - // Setup a new eventReader - InputStream in = read(); - XMLEventReader eventReader = inputFactory.createXMLEventReader(in); - // Read the XML document - while (eventReader.hasNext()) - { - XMLEvent event = eventReader.nextEvent(); - if (event.isStartElement()) - { - if (event.asStartElement().getName().getLocalPart().equals(TITLE)) - { - event = eventReader.nextEvent(); - title = event.asCharacters().getData(); - continue; - } - if (event.asStartElement().getName().getLocalPart().equals(LINK)) - { - event = eventReader.nextEvent(); - link = event.asCharacters().getData(); - continue; - } - } - else if (event.isEndElement()) - { - if (event.asEndElement().getName().getLocalPart().equals(ITEM)) - { - // Store the title and link of the first entry we get - the first file on the list is all we need - versionTitle = title; - versionLink = link; - // All done, we don't need to know about older files. - break; - } - } - } - } - catch (XMLStreamException e) - { - throw new RuntimeException(e); - } - } - - /** - * Open the RSS feed - */ - private InputStream read() - { - try - { - return url.openStream(); - } - catch (IOException e) - { - e.printStackTrace(); - plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); - result = Updater.UpdateResult.FAIL_DBO; - return null; - } - } +public class Updater { + private Plugin plugin; + private UpdateType type; + private String versionTitle; + private String versionLink; + private long totalSize; // Holds the total size of the file + private double downloadedSize; // TODO: Holds the number of bytes downloaded + private int sizeLine; // Used for detecting file size + private int multiplier; // Used for determining when to broadcast download updates + private boolean announce; // Whether to announce file downloads + private URL url; // Connecting to RSS + private static final String DBOUrl = "http://dev.bukkit.org/server-mods/"; // Slugs will be appended to this to get to the project's RSS feed + private String[] noUpdateTag = { "-DEV", "-PRE" }; // If the version number contains one of these, don't update. + private static final int BYTE_SIZE = 1024; // Used for downloading files + private String updateFolder = YamlConfiguration.loadConfiguration(new File("bukkit.yml")).getString("settings.update-folder"); // The folder that downloads will be placed in + private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process + + // Strings for reading RSS + private static final String TITLE = "title"; + private static final String LINK = "link"; + private static final String ITEM = "item"; + + /** + * Gives the dev the result of the update process. Can be obtained by called getResult(). + */ + public enum UpdateResult { + /** + * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. + */ + SUCCESS(1), + /** + * The updater did not find an update, and nothing was downloaded. + */ + NO_UPDATE(2), + /** + * The updater found an update, but was unable to download it. + */ + FAIL_DOWNLOAD(3), + /** + * For some reason, the updater was unable to contact dev.bukkit.org to download the file. + */ + FAIL_DBO(4), + /** + * When running the version check, the file on DBO did not contain the a version in the format 'vVersion' such as 'v1.0'. + */ + FAIL_NOVERSION(5), + /** + * The slug provided by the plugin running the updater was invalid and doesn't exist on DBO. + */ + FAIL_BADSLUG(6), + /** + * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded. + */ + UPDATE_AVAILABLE(7), + /** + * The update was unable to update due to a unknown exception thrown. + */ + UNKNOWN_ERROR(8); + + private static final Map valueList = new HashMap(); + private final int value; + + private UpdateResult(int value) { + this.value = value; + } + + public int getValue() { + return this.value; + } + + public static Updater.UpdateResult getResult(int value) { + return valueList.get(value); + } + + static { + for (Updater.UpdateResult result : Updater.UpdateResult.values()) { + valueList.put(result.value, result); + } + } + } + + /** + * Allows the dev to specify the type of update that will be run. + */ + public enum UpdateType { + /** + * Run a version check, and then if the file is out of date, download the newest version. + */ + DEFAULT(1), + /** + * Don't run a version check, just find the latest update and download it. + */ + NO_VERSION_CHECK(2), + /** + * Get information about the version and the download size, but don't actually download anything. + */ + NO_DOWNLOAD(3); + + private static final Map valueList = new HashMap(); + private final int value; + + private UpdateType(int value) { + this.value = value; + } + + public int getValue() { + return this.value; + } + + public static Updater.UpdateType getResult(int value) { + return valueList.get(value); + } + + static { + for (Updater.UpdateType result : Updater.UpdateType.values()) { + valueList.put(result.value, result); + } + } + } + + /** + * Initialize the updater + * + * @param plugin The plugin that is checking for an update. + * @param slug The dev.bukkit.org slug of the project (http://dev.bukkit.org/server-mods/SLUG_IS_HERE) + * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. + * @param type Specify the type of update this will be. See {@link UpdateType} + * @param announce True if the program should announce the progress of new updates in console + */ + public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) { + this.plugin = plugin; + this.type = type; + this.announce = announce; + try { + // Obtain the results of the project's file feed + url = new URL(DBOUrl + slug + "/files.rss"); + if (url != null) { + // Obtain the results of the project's file feed + readFeed(); + if (versionCheck(versionTitle)) { + String fileLink = getFile(versionLink); + if (fileLink != null && type != UpdateType.NO_DOWNLOAD) { + String name = file.getName(); + // If it's a zip file, it shouldn't be downloaded as the plugin's name + if (fileLink.endsWith(".zip")) { + String[] split = fileLink.split("/"); + name = split[split.length - 1]; + } + saveFile(new File("plugins/" + updateFolder), name, fileLink); + } else { + result = UpdateResult.UPDATE_AVAILABLE; + } + } + } + } catch (MalformedURLException ex) { + // The slug doesn't exist + plugin.getLogger().warning("The author of this plugin has misconfigured their Auto Update system"); + plugin.getLogger().warning("The project slug added ('" + slug + "') is invalid, and does not exist on dev.bukkit.org"); + result = Updater.UpdateResult.FAIL_BADSLUG; // Bad slug! Bad! + } catch (RuntimeException ex) { + // Something went wrong with the updater and can't check for updates. + if (result == Updater.UpdateResult.SUCCESS) { + plugin.getLogger().warning("An error had occured and Auto Update was unable to check for updates"); + plugin.getLogger().warning("Here is a stacktrace of what happened: "); + ex.printStackTrace(); + result = Updater.UpdateResult.UNKNOWN_ERROR; + } + } + } + + /** + * Get the result of the update process. + */ + public Updater.UpdateResult getResult() { + return result; + } + + /** + * Get the total bytes of the file (can only be used after running a version check or a normal run). + */ + public long getFileSize() { + return totalSize; + } + + /** + * Get the version string latest file avaliable online. + */ + public String getLatestVersionString() { + return versionTitle; + } + + /** + * Save an update from dev.bukkit.org into the server's update folder. + */ + private void saveFile(File folder, String file, String u) { + if (!folder.exists()) { + folder.mkdir(); + } + BufferedInputStream in = null; + FileOutputStream fout = null; + try { + // Download the file + URL url = new URL(u); + int fileLength = url.openConnection().getContentLength(); + in = new BufferedInputStream(url.openStream()); + fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file); + + byte[] data = new byte[BYTE_SIZE]; + int count; + if (announce) plugin.getLogger().info("About to download a new update: " + versionTitle); + long downloaded = 0; + while ((count = in.read(data, 0, BYTE_SIZE)) != -1) { + downloaded += count; + fout.write(data, 0, count); + int percent = (int) (downloaded * 100 / fileLength); + if (announce & (percent % 10 == 0)) { + plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); + } + } + // Just a quick check to make sure we didn't leave any files from last time... + for (File xFile : new File("plugins/" + updateFolder).listFiles()) { + if (xFile.getName().endsWith(".zip")) { + xFile.delete(); + } + } + // Check to see if it's a zip file, if it is, unzip it. + File dFile = new File(folder.getAbsolutePath() + "/" + file); + if (dFile.getName().endsWith(".zip")) { + // Unzip + unzip(dFile.getCanonicalPath()); + } + if (announce) plugin.getLogger().info("Finished updating."); + } catch (Exception ex) { + plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); + result = Updater.UpdateResult.FAIL_DOWNLOAD; + } finally { + try { + if (in != null) { + in.close(); + } + if (fout != null) { + fout.close(); + } + } catch (Exception ex) {} + } + } + + /** + * Part of Zip-File-Extractor, modified by H31IX for use with Bukkit + */ + private void unzip(String file) { + try { + File fSourceZip = new File(file); + String zipPath = file.substring(0, file.length() - 4); + ZipFile zipFile = new ZipFile(fSourceZip); + Enumeration e = zipFile.entries(); + while (e.hasMoreElements()) { + ZipEntry entry = (ZipEntry) e.nextElement(); + File destinationFilePath = new File(zipPath, entry.getName()); + destinationFilePath.getParentFile().mkdirs(); + if (entry.isDirectory()) { + continue; + } else { + BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); + int b; + byte buffer[] = new byte[BYTE_SIZE]; + FileOutputStream fos = new FileOutputStream(destinationFilePath); + BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE); + while ((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) { + bos.write(buffer, 0, b); + } + bos.flush(); + bos.close(); + bis.close(); + String name = destinationFilePath.getName(); + if (name.endsWith(".jar") && pluginFile(name)) { + destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name)); + } + } + entry = null; + destinationFilePath = null; + } + e = null; + zipFile.close(); + zipFile = null; + // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. + for (File dFile : new File(zipPath).listFiles()) { + if (dFile.isDirectory()) { + if (pluginFile(dFile.getName())) { + File oFile = new File("plugins/" + dFile.getName()); // Get current dir + File[] contents = oFile.listFiles(); // List of existing files in the current dir + for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir + { + boolean found = false; + for (File xFile : contents) // Loop through contents to see if it exists + { + if (xFile.getName().equals(cFile.getName())) { + found = true; + break; + } + } + if (!found) { + // Move the new file into the current dir + cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); + } else { + // This file already exists, so we don't need it anymore. + cFile.delete(); + } + } + } + } + dFile.delete(); + } + new File(zipPath).delete(); + fSourceZip.delete(); + } catch (IOException ex) { + ex.printStackTrace(); + plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); + result = Updater.UpdateResult.FAIL_DOWNLOAD; + } + new File(file).delete(); + } + + /** + * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. + */ + public boolean pluginFile(String name) { + for (File file : new File("plugins").listFiles()) { + if (file.getName().equals(name)) { return true; } + } + return false; + } + + /** + * Obtain the direct download file url from the file's page. + */ + private String getFile(String link) { + String download = null; + try { + // Open a connection to the page + URL url = new URL(link); + URLConnection urlConn = url.openConnection(); + InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream()); + BufferedReader buff = new BufferedReader(inStream); + + int counter = 0; + String line; + while ((line = buff.readLine()) != null) { + counter++; + // Search for the download link + if (line.contains("
  • ")) { + // Get the raw link + download = line.split("Download")[0]; + } + // Search for size + else if (line.contains("
    Size
    ")) { + sizeLine = counter + 1; + } else if (counter == sizeLine) { + String size = line.replaceAll("
    ", "").replaceAll("
    ", ""); + multiplier = size.contains("MiB") ? 1048576 : 1024; + size = size.replace(" KiB", "").replace(" MiB", ""); + totalSize = (long) (Double.parseDouble(size) * multiplier); + } + } + urlConn = null; + inStream = null; + buff.close(); + buff = null; + } catch (Exception ex) { + ex.printStackTrace(); + plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); + result = Updater.UpdateResult.FAIL_DBO; + return null; + } + return download; + } + + /** + * Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated + */ + private boolean versionCheck(String title) { + if (type != UpdateType.NO_VERSION_CHECK) { + String version = plugin.getDescription().getVersion(); + if (title.split("v").length == 2) { + String remoteVersion = title.split("v")[1].split(" ")[0]; // Get the newest file's version number + if (hasTag(version, remoteVersion) || version.equalsIgnoreCase(remoteVersion)) { + // We already have the latest version, or this build is tagged for no-update + result = Updater.UpdateResult.NO_UPDATE; + return false; + } + } else { + // The file's name did not contain the string 'vVersion' + plugin.getLogger().warning("The author of this plugin has misconfigured their Auto Update system"); + plugin.getLogger().warning("Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0"); + plugin.getLogger().warning("Please notify the author (" + plugin.getDescription().getAuthors().get(0) + ") of this error."); + result = Updater.UpdateResult.FAIL_NOVERSION; + return false; + } + } + return true; + } + + /** + * Evaluate whether the version number is marked showing that it should not be updated by this program + */ + private boolean hasTag(String version, String remoteVersion) { + for (String string : noUpdateTag) { + if (version.contains(string)) { + if (version.replaceAll(string, "").equals(remoteVersion)) { + // The build has a tag, but the version was upgraded to release so we should do an update anyway + return false; + } else { + return true; + } + } + } + return false; + } + + /** + * Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit + */ + @SuppressWarnings({ "deprecation", "restriction" }) + private void readFeed() { + try { + // Set header values intial to the empty string + String title = ""; + String link = ""; + // First create a new XMLInputFactory + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + // Setup a new eventReader + InputStream in = read(); + XMLEventReader eventReader = inputFactory.createXMLEventReader(in); + // Read the XML document + while (eventReader.hasNext()) { + XMLEvent event = eventReader.nextEvent(); + if (event.isStartElement()) { + if (event.asStartElement().getName().getLocalPart().equals(TITLE)) { + event = eventReader.nextEvent(); + title = event.asCharacters().getData(); + continue; + } + if (event.asStartElement().getName().getLocalPart().equals(LINK)) { + event = eventReader.nextEvent(); + link = event.asCharacters().getData(); + continue; + } + } else if (event.isEndElement()) { + if (event.asEndElement().getName().getLocalPart().equals(ITEM)) { + // Store the title and link of the first entry we get - the first file on the list is all we need + versionTitle = title; + versionLink = link; + // All done, we don't need to know about older files. + break; + } + } + } + } catch (XMLStreamException e) { + throw new RuntimeException(e); + } + } + + /** + * Open the RSS feed + */ + private InputStream read() { + try { + return url.openStream(); + } catch (IOException e) { + e.printStackTrace(); + plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); + result = Updater.UpdateResult.FAIL_DBO; + return null; + } + } } diff --git a/src/main/java/net/h31ix/anticheat/util/BlockHardness.java b/src/main/java/net/h31ix/anticheat/util/BlockHardness.java index c74a93e..049b8cd 100644 --- a/src/main/java/net/h31ix/anticheat/util/BlockHardness.java +++ b/src/main/java/net/h31ix/anticheat/util/BlockHardness.java @@ -2,136 +2,131 @@ package net.h31ix.anticheat.util; import org.bukkit.Material; -public enum BlockHardness -{ - STONE(Material.STONE, 1.50D), - GRASS(Material.GRASS, 0.60D), - DIRT(Material.DIRT, 0.50D), - COBBLESTONE(Material.COBBLESTONE, 2.00D), - WOOD(Material.WOOD, 2.00D), - SAPLING(Material.SAPLING, 0.00D), - WATER(Material.WATER, 100.00D), - STATIONARY_WATER(Material.STATIONARY_WATER, 100.00D), - LAVA(Material.LAVA, 0.00D), - STATIONARY_LAVA(Material.STATIONARY_LAVA, 100.00D), - SAND(Material.SAND, 0.50D), - GRAVEL(Material.GRAVEL, 0.60D), - GOLD_ORE(Material.GOLD_ORE, 3.00D), - IRON_ORE(Material.IRON_ORE, 3.00D), - COAL_ORE(Material.COAL_ORE, 3.00D), - LOG(Material.LOG, 2.00D), - LEAVES(Material.LEAVES, 0.20D), - SPONGE(Material.SPONGE, 0.60D), - GLASS(Material.GLASS, 0.30D), - LAPIS_ORE(Material.LAPIS_ORE, 3.00D), - LAPIS_BLOCK(Material.LAPIS_BLOCK, 3.00D), - DISPENSER(Material.DISPENSER, 3.50D), - SANDSTONE(Material.SANDSTONE, 0.80D), - NOTE_BLOCK(Material.NOTE_BLOCK, 0.80D), - BED(Material.BED, 0.20D), - DETECTOR_RAIL(Material.DETECTOR_RAIL, 0.70D), - WEB(Material.WEB, 4.00D), - LONG_GRASS(Material.LONG_GRASS, 0.00D), - DEAD_BUSH(Material.DEAD_BUSH, 0.00D), - WOOL(Material.WOOL, 0.80D), - YELLOW_FLOWER(Material.YELLOW_FLOWER, 0.00D), - RED_ROSE(Material.RED_ROSE, 0.00D), - BROWN_MUSHROOM(Material.BROWN_MUSHROOM, 0.00D), - RED_MUSHROOM(Material.RED_MUSHROOM, 0.00D), - GOLD_BLOCK(Material.GOLD_BLOCK, 3.00D), - IRON_BLOCK(Material.IRON_BLOCK, 5.00D), - DOUBLE_STEP(Material.DOUBLE_STEP, 2.00D), - STEP(Material.STEP, 2.00D), - BRICK(Material.BRICK, 2.00D), - TNT(Material.TNT, 0.00D), - BOOKSHELF(Material.BOOKSHELF, 1.50D), - MOSSY_COBBLESTONE(Material.MOSSY_COBBLESTONE, 2.00D), - OBSIDIAN(Material.OBSIDIAN, 50.00D), - TORCH(Material.TORCH, 0.00D), - FIRE(Material.FIRE, 0.00D), - MOB_SPAWNER(Material.MOB_SPAWNER, 5.00D), - CHEST(Material.CHEST, 2.50D), - REDSTONE_WIRE(Material.REDSTONE_WIRE, 0.00D), - DIAMOND_ORE(Material.DIAMOND_ORE, 3.00D), - DIAMOND_BLOCK(Material.DIAMOND_BLOCK, 5.00D), - WORKBENCH(Material.WORKBENCH, 2.50D), - SOIL(Material.SOIL, 0.60D), - FURNACE(Material.FURNACE, 3.50D), - BURNING_FURNACE(Material.BURNING_FURNACE, 3.50D), - WOODEN_DOOR(Material.WOODEN_DOOR, 3.00D), - LADDER(Material.LADDER, 0.40D), - RAILS(Material.RAILS, 0.70D), - LEVER(Material.LEVER, 0.50D), - STONE_PLATE(Material.STONE_PLATE, 0.50D), - IRON_DOOR_BLOCK(Material.IRON_DOOR_BLOCK, 5.00D), - WOOD_PLATE(Material.WOOD_PLATE, 0.50D), - REDSTONE_ORE(Material.REDSTONE_ORE, 3.00D), - GLOWING_REDSTONE_ORE(Material.GLOWING_REDSTONE_ORE, 3.00D), - REDSTONE_TORCH_OFF(Material.REDSTONE_TORCH_OFF, 0.00D), - REDSTONE_TORCH_ON(Material.REDSTONE_TORCH_ON, 0.00D), - STONE_BUTTON(Material.STONE_BUTTON, 0.50D), - SNOW(Material.SNOW, 0.10D), - ICE(Material.ICE, 0.50D), - SNOW_BLOCK(Material.SNOW_BLOCK, 0.20D), - CACTUS(Material.CACTUS, 0.40D), - CLAY(Material.CLAY, 0.60D), - SUGAR_CANE_BLOCK(Material.SUGAR_CANE_BLOCK, 0.00D), - JUKEBOX(Material.JUKEBOX, 2.00D), - FENCE(Material.FENCE, 2.00D), - NETHERRACK(Material.NETHERRACK, 0.40D), - SOUL_SAND(Material.SOUL_SAND, 0.50D), - GLOWSTONE(Material.GLOWSTONE, 0.30D), - PORTAL(Material.PORTAL, -1.00D), - CAKE_BLOCK(Material.CAKE_BLOCK, 0.50D), - LOCKED_CHEST(Material.LOCKED_CHEST, 0.00D), - TRAP_DOOR(Material.TRAP_DOOR, 3.00D), - MONSTER_EGGS(Material.MONSTER_EGGS, 0.750D), - SMOOTH_BRICK(Material.SMOOTH_BRICK, 1.50D), - IRON_FENCE(Material.IRON_FENCE, 5.00D), - THIN_GLASS(Material.THIN_GLASS, 0.30D), - PUMPKIN_STEM(Material.PUMPKIN_STEM, 0.00D), - MELON_STEM(Material.MELON_STEM, 0.00D), - VINE(Material.VINE, 0.20D), - FENCE_GATE(Material.FENCE_GATE, 2.00D), - MYCEL(Material.MYCEL, 0.60D), - WATER_LILY(Material.WATER_LILY, 0.00D), - NETHER_BRICK(Material.NETHER_BRICK, 2.00D), - NETHER_FENCE(Material.NETHER_FENCE, 2.00D), - ENCHANTMENT_TABLE(Material.ENCHANTMENT_TABLE, 5.00D), - BREWING_STAND(Material.BREWING_STAND, 0.50D), - CAULDRON(Material.CAULDRON, 2.00D), - ENDER_PORTAL(Material.ENDER_PORTAL, -1.00D), - ENDER_PORTAL_FRAME(Material.ENDER_PORTAL_FRAME, -1.00D), - DRAGON_EGG(Material.DRAGON_EGG, 3.00D), - REDSTONE_LAMP_OFF(Material.REDSTONE_LAMP_OFF, 0.30D), - REDSTONE_LAMP_ON(Material.REDSTONE_LAMP_ON, 0.30D), - WOOD_DOUBLE_STEP(Material.WOOD_DOUBLE_STEP, 2.00D), - WOOD_STEP(Material.WOOD_STEP, 2.00D), - COCOA(Material.COCOA, 0.20D), - EMERALD_ORE(Material.EMERALD_ORE, 3.00D), - ENDER_CHEST(Material.ENDER_CHEST, 22.50D), - EMERALD_BLOCK(Material.EMERALD_BLOCK, 5.00D), - FLOWER_POT(Material.FLOWER_POT, 0.00D), - WOOD_BUTTON(Material.WOOD_BUTTON, 0.50D), - ANVIL(Material.ANVIL, 5.00D); - - Material mat; - double hardness; - - BlockHardness(Material m, double hard) - { - mat = m; - hardness = hard; - } - - public static double getBlockHardness(Material m) - { - for (BlockHardness e : BlockHardness.values()) - { - if (e.mat.equals(m)) - return e.hardness; - } - - return 1.0D; - } +public enum BlockHardness { + STONE(Material.STONE, 1.50D), + GRASS(Material.GRASS, 0.60D), + DIRT(Material.DIRT, 0.50D), + COBBLESTONE(Material.COBBLESTONE, 2.00D), + WOOD(Material.WOOD, 2.00D), + SAPLING(Material.SAPLING, 0.00D), + WATER(Material.WATER, 100.00D), + STATIONARY_WATER(Material.STATIONARY_WATER, 100.00D), + LAVA(Material.LAVA, 0.00D), + STATIONARY_LAVA(Material.STATIONARY_LAVA, 100.00D), + SAND(Material.SAND, 0.50D), + GRAVEL(Material.GRAVEL, 0.60D), + GOLD_ORE(Material.GOLD_ORE, 3.00D), + IRON_ORE(Material.IRON_ORE, 3.00D), + COAL_ORE(Material.COAL_ORE, 3.00D), + LOG(Material.LOG, 2.00D), + LEAVES(Material.LEAVES, 0.20D), + SPONGE(Material.SPONGE, 0.60D), + GLASS(Material.GLASS, 0.30D), + LAPIS_ORE(Material.LAPIS_ORE, 3.00D), + LAPIS_BLOCK(Material.LAPIS_BLOCK, 3.00D), + DISPENSER(Material.DISPENSER, 3.50D), + SANDSTONE(Material.SANDSTONE, 0.80D), + NOTE_BLOCK(Material.NOTE_BLOCK, 0.80D), + BED(Material.BED, 0.20D), + DETECTOR_RAIL(Material.DETECTOR_RAIL, 0.70D), + WEB(Material.WEB, 4.00D), + LONG_GRASS(Material.LONG_GRASS, 0.00D), + DEAD_BUSH(Material.DEAD_BUSH, 0.00D), + WOOL(Material.WOOL, 0.80D), + YELLOW_FLOWER(Material.YELLOW_FLOWER, 0.00D), + RED_ROSE(Material.RED_ROSE, 0.00D), + BROWN_MUSHROOM(Material.BROWN_MUSHROOM, 0.00D), + RED_MUSHROOM(Material.RED_MUSHROOM, 0.00D), + GOLD_BLOCK(Material.GOLD_BLOCK, 3.00D), + IRON_BLOCK(Material.IRON_BLOCK, 5.00D), + DOUBLE_STEP(Material.DOUBLE_STEP, 2.00D), + STEP(Material.STEP, 2.00D), + BRICK(Material.BRICK, 2.00D), + TNT(Material.TNT, 0.00D), + BOOKSHELF(Material.BOOKSHELF, 1.50D), + MOSSY_COBBLESTONE(Material.MOSSY_COBBLESTONE, 2.00D), + OBSIDIAN(Material.OBSIDIAN, 50.00D), + TORCH(Material.TORCH, 0.00D), + FIRE(Material.FIRE, 0.00D), + MOB_SPAWNER(Material.MOB_SPAWNER, 5.00D), + CHEST(Material.CHEST, 2.50D), + REDSTONE_WIRE(Material.REDSTONE_WIRE, 0.00D), + DIAMOND_ORE(Material.DIAMOND_ORE, 3.00D), + DIAMOND_BLOCK(Material.DIAMOND_BLOCK, 5.00D), + WORKBENCH(Material.WORKBENCH, 2.50D), + SOIL(Material.SOIL, 0.60D), + FURNACE(Material.FURNACE, 3.50D), + BURNING_FURNACE(Material.BURNING_FURNACE, 3.50D), + WOODEN_DOOR(Material.WOODEN_DOOR, 3.00D), + LADDER(Material.LADDER, 0.40D), + RAILS(Material.RAILS, 0.70D), + LEVER(Material.LEVER, 0.50D), + STONE_PLATE(Material.STONE_PLATE, 0.50D), + IRON_DOOR_BLOCK(Material.IRON_DOOR_BLOCK, 5.00D), + WOOD_PLATE(Material.WOOD_PLATE, 0.50D), + REDSTONE_ORE(Material.REDSTONE_ORE, 3.00D), + GLOWING_REDSTONE_ORE(Material.GLOWING_REDSTONE_ORE, 3.00D), + REDSTONE_TORCH_OFF(Material.REDSTONE_TORCH_OFF, 0.00D), + REDSTONE_TORCH_ON(Material.REDSTONE_TORCH_ON, 0.00D), + STONE_BUTTON(Material.STONE_BUTTON, 0.50D), + SNOW(Material.SNOW, 0.10D), + ICE(Material.ICE, 0.50D), + SNOW_BLOCK(Material.SNOW_BLOCK, 0.20D), + CACTUS(Material.CACTUS, 0.40D), + CLAY(Material.CLAY, 0.60D), + SUGAR_CANE_BLOCK(Material.SUGAR_CANE_BLOCK, 0.00D), + JUKEBOX(Material.JUKEBOX, 2.00D), + FENCE(Material.FENCE, 2.00D), + NETHERRACK(Material.NETHERRACK, 0.40D), + SOUL_SAND(Material.SOUL_SAND, 0.50D), + GLOWSTONE(Material.GLOWSTONE, 0.30D), + PORTAL(Material.PORTAL, -1.00D), + CAKE_BLOCK(Material.CAKE_BLOCK, 0.50D), + LOCKED_CHEST(Material.LOCKED_CHEST, 0.00D), + TRAP_DOOR(Material.TRAP_DOOR, 3.00D), + MONSTER_EGGS(Material.MONSTER_EGGS, 0.750D), + SMOOTH_BRICK(Material.SMOOTH_BRICK, 1.50D), + IRON_FENCE(Material.IRON_FENCE, 5.00D), + THIN_GLASS(Material.THIN_GLASS, 0.30D), + PUMPKIN_STEM(Material.PUMPKIN_STEM, 0.00D), + MELON_STEM(Material.MELON_STEM, 0.00D), + VINE(Material.VINE, 0.20D), + FENCE_GATE(Material.FENCE_GATE, 2.00D), + MYCEL(Material.MYCEL, 0.60D), + WATER_LILY(Material.WATER_LILY, 0.00D), + NETHER_BRICK(Material.NETHER_BRICK, 2.00D), + NETHER_FENCE(Material.NETHER_FENCE, 2.00D), + ENCHANTMENT_TABLE(Material.ENCHANTMENT_TABLE, 5.00D), + BREWING_STAND(Material.BREWING_STAND, 0.50D), + CAULDRON(Material.CAULDRON, 2.00D), + ENDER_PORTAL(Material.ENDER_PORTAL, -1.00D), + ENDER_PORTAL_FRAME(Material.ENDER_PORTAL_FRAME, -1.00D), + DRAGON_EGG(Material.DRAGON_EGG, 3.00D), + REDSTONE_LAMP_OFF(Material.REDSTONE_LAMP_OFF, 0.30D), + REDSTONE_LAMP_ON(Material.REDSTONE_LAMP_ON, 0.30D), + WOOD_DOUBLE_STEP(Material.WOOD_DOUBLE_STEP, 2.00D), + WOOD_STEP(Material.WOOD_STEP, 2.00D), + COCOA(Material.COCOA, 0.20D), + EMERALD_ORE(Material.EMERALD_ORE, 3.00D), + ENDER_CHEST(Material.ENDER_CHEST, 22.50D), + EMERALD_BLOCK(Material.EMERALD_BLOCK, 5.00D), + FLOWER_POT(Material.FLOWER_POT, 0.00D), + WOOD_BUTTON(Material.WOOD_BUTTON, 0.50D), + ANVIL(Material.ANVIL, 5.00D); + + Material mat; + double hardness; + + BlockHardness(Material m, double hard) { + mat = m; + hardness = hard; + } + + public static double getBlockHardness(Material m) { + for (BlockHardness e : BlockHardness.values()) { + if (e.mat.equals(m)) return e.hardness; + } + + return 1.0D; + } } \ No newline at end of file diff --git a/src/main/java/net/h31ix/anticheat/util/Calibrator.java b/src/main/java/net/h31ix/anticheat/util/Calibrator.java index d72b521..9e736af 100644 --- a/src/main/java/net/h31ix/anticheat/util/Calibrator.java +++ b/src/main/java/net/h31ix/anticheat/util/Calibrator.java @@ -14,292 +14,226 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; -public class Calibrator implements Listener -{ - private final Player player; - private int step = 0; - private static final int TOTAL = 30; - private long lastLong; - private int lastInt; - private int lastDouble; - private long [] longs = new long[10]; - private double [] doubles = new double[10]; - private int [] ints = new int[10]; - private int times = 0; - - // Value-specific calculations - private long projectileTime; - private long dropItemTime; - private long punchAvg; - private double blockBreakMax; - private double blockPlaceMax; - - public Calibrator(Player player) - { - this.player = player; - player.sendMessage(ChatColor.GREEN+"----You have entered calibration mode.----"); - // Wait for listener to be registered and calibrate method called. - } - - public void calibrate() - { - switch(step) - { - case 0: - sendStep(); - player.getInventory().setItemInHand(new ItemStack(Material.BOW)); - player.getInventory().addItem(new ItemStack(Material.ARROW, 64)); - player.sendMessage("Fire arrows as fast as possible (don't pull all the way back)"); - break; - case 2: - player.getInventory().clear(); - player.getInventory().setItemInHand(new ItemStack(Material.DIRT, 64)); - player.sendMessage("Drop items as fast as possible."); - /*case 0: - sendStep(); - player.sendMessage("Spam the left mouse button as fast as possible."); - break; - case 2: - player.setGameMode(GameMode.CREATIVE); - player.sendMessage("Break blocks from as far away as you can possibly get from them."); - break; - case 3: - player.sendMessage("Place blocks from as far away as you can possibly get from them."); - break;*/ - } - - } - - private int getLongCount() - { - int fill = 0; - for(long l : longs) - { - if(l != 0) - { - fill++; - } - } - return fill; - } - - private int getDoubleCount() - { - int fill = 0; - for(double d : doubles) - { - if(d != 0) - { - fill++; - } - } - return fill; - } - - private void clear() - { - for(int i =0;i max) - { - max = d; - } - } - clear(); - player.sendMessage(ChatColor.AQUA+"Done. Maximum calculated at "+ChatColor.WHITE+max); - sendStep(); - calibrate(); - return max; - } - return -1; - } - - // Get the absolute time it takes to do something X times - private long getAbsoluteLong() - { - int count = getLongCount(); - if(count < 10) - { - if(lastLong == 0) - { - lastLong = System.currentTimeMillis(); - } - else - { - longs[count] = System.currentTimeMillis(); - lastLong = System.currentTimeMillis(); - } - } - else - { - long val = longs[9]-longs[0]; - clear(); - player.sendMessage(ChatColor.AQUA+"Done. Value calculated at "+ChatColor.WHITE+val); - sendStep(); - calibrate(); - return val; - } - return -1; - } - - - - // Begin event listeners - - @EventHandler - public void onPlayerDropItem(PlayerDropItemEvent event) - { - if(event.getPlayer() == player) - { - if(step == 2) - { - long v = getAbsoluteLong(); - if(v != -1) - { - dropItemTime = v; - } - } - } - } - - @EventHandler - public void onEntityShootBow(EntityShootBowEvent event) - { - if(event.getEntity() instanceof Player && ((Player)event.getEntity()) == player) - { - if(step == 1) - { - long v = getAbsoluteLong(); - if(v != -1) - { - projectileTime = v; - } - } - } - } - - @EventHandler - public void onPlayerInteract(PlayerInteractEvent event) - { - if(event.getPlayer() == player) - { - if(step == -1) - { - long v = getAvgLong(); - if(v != -1) - { - punchAvg = v; - } - } - else if(step == 1) - { - - } - } - } - - @EventHandler - public void onBlockBreak(BlockBreakEvent event) - { - if(event.getPlayer() == player) - { - if(step == -1) - { - double lengthX = Math.abs(event.getBlock().getX()-event.getPlayer().getLocation().getX()); - double lengthZ = Math.abs(event.getBlock().getZ()-event.getPlayer().getLocation().getZ()); - double v = getMaxDouble(lengthX >= lengthZ ? lengthX : lengthZ); - if(v != -1) - { - blockBreakMax = v; - } - } - } - } - - @EventHandler - public void onBlockPlace(BlockPlaceEvent event) - { - if(event.getPlayer() == player) - { - if(step == -1) - { - double lengthX = Math.abs(event.getBlock().getX()-event.getPlayer().getLocation().getX()); - double lengthZ = Math.abs(event.getBlock().getZ()-event.getPlayer().getLocation().getZ()); - double v = getMaxDouble(lengthX >= lengthZ ? lengthX : lengthZ); - if(v != -1) - { - blockPlaceMax = v; - } - } - } - } +public class Calibrator implements Listener { + private final Player player; + private int step = 0; + private static final int TOTAL = 30; + private long lastLong; + private int lastInt; + private int lastDouble; + private long[] longs = new long[10]; + private double[] doubles = new double[10]; + private int[] ints = new int[10]; + private int times = 0; + + // Value-specific calculations + private long projectileTime; + private long dropItemTime; + private long punchAvg; + private double blockBreakMax; + private double blockPlaceMax; + + public Calibrator(Player player) { + this.player = player; + player.sendMessage(ChatColor.GREEN + "----You have entered calibration mode.----"); + // Wait for listener to be registered and calibrate method called. + } + + public void calibrate() { + switch (step) { + case 0: + sendStep(); + player.getInventory().setItemInHand(new ItemStack(Material.BOW)); + player.getInventory().addItem(new ItemStack(Material.ARROW, 64)); + player.sendMessage("Fire arrows as fast as possible (don't pull all the way back)"); + break; + case 2: + player.getInventory().clear(); + player.getInventory().setItemInHand(new ItemStack(Material.DIRT, 64)); + player.sendMessage("Drop items as fast as possible."); + /* + * case 0: sendStep(); player.sendMessage("Spam the left mouse button as fast as possible."); break; case 2: player.setGameMode(GameMode.CREATIVE); player.sendMessage("Break blocks from as far away as you can possibly get from them."); break; case 3: + * player.sendMessage("Place blocks from as far away as you can possibly get from them."); break; + */ + } + + } + + private int getLongCount() { + int fill = 0; + for (long l : longs) { + if (l != 0) { + fill++; + } + } + return fill; + } + + private int getDoubleCount() { + int fill = 0; + for (double d : doubles) { + if (d != 0) { + fill++; + } + } + return fill; + } + + private void clear() { + for (int i = 0; i < longs.length; i++) { + longs[i] = 0; + } + for (int i = 0; i < ints.length; i++) { + ints[i] = 0; + } + for (int i = 0; i < doubles.length; i++) { + doubles[i] = 0; + } + lastInt = 0; + lastDouble = 0; + lastLong = 0; + times = 0; + + } + + private void sendStep() { + step++; + player.sendMessage(ChatColor.GREEN + "Step " + step + "/" + TOTAL); + } + + // Find the average time it takes to do a task + private long getAvgLong() { + int count = getLongCount(); + if (count < 10) { + if (lastLong == 0) { + lastLong = System.currentTimeMillis(); + } else { + longs[count] = System.currentTimeMillis() - lastLong; + lastLong = System.currentTimeMillis(); + } + } else { + long avg = 0; + for (long l : longs) { + avg += l; + } + clear(); + avg /= 10; + player.sendMessage(ChatColor.AQUA + "Done. Average calculated at " + ChatColor.WHITE + avg); + sendStep(); + calibrate(); + return avg; + } + return -1; + } + + // Find the maximum time it takes to do a task + private double getMaxDouble(double length) { + int count = getDoubleCount(); + if (count < 10) { + doubles[count] = length; + } else { + double max = 0; + for (double d : doubles) { + if (max == 0 || d > max) { + max = d; + } + } + clear(); + player.sendMessage(ChatColor.AQUA + "Done. Maximum calculated at " + ChatColor.WHITE + max); + sendStep(); + calibrate(); + return max; + } + return -1; + } + + // Get the absolute time it takes to do something X times + private long getAbsoluteLong() { + int count = getLongCount(); + if (count < 10) { + if (lastLong == 0) { + lastLong = System.currentTimeMillis(); + } else { + longs[count] = System.currentTimeMillis(); + lastLong = System.currentTimeMillis(); + } + } else { + long val = longs[9] - longs[0]; + clear(); + player.sendMessage(ChatColor.AQUA + "Done. Value calculated at " + ChatColor.WHITE + val); + sendStep(); + calibrate(); + return val; + } + return -1; + } + + + // Begin event listeners + + @EventHandler + public void onPlayerDropItem(PlayerDropItemEvent event) { + if (event.getPlayer() == player) { + if (step == 2) { + long v = getAbsoluteLong(); + if (v != -1) { + dropItemTime = v; + } + } + } + } + + @EventHandler + public void onEntityShootBow(EntityShootBowEvent event) { + if (event.getEntity() instanceof Player && ((Player) event.getEntity()) == player) { + if (step == 1) { + long v = getAbsoluteLong(); + if (v != -1) { + projectileTime = v; + } + } + } + } + + @EventHandler + public void onPlayerInteract(PlayerInteractEvent event) { + if (event.getPlayer() == player) { + if (step == -1) { + long v = getAvgLong(); + if (v != -1) { + punchAvg = v; + } + } else if (step == 1) { + + } + } + } + + @EventHandler + public void onBlockBreak(BlockBreakEvent event) { + if (event.getPlayer() == player) { + if (step == -1) { + double lengthX = Math.abs(event.getBlock().getX() - event.getPlayer().getLocation().getX()); + double lengthZ = Math.abs(event.getBlock().getZ() - event.getPlayer().getLocation().getZ()); + double v = getMaxDouble(lengthX >= lengthZ ? lengthX : lengthZ); + if (v != -1) { + blockBreakMax = v; + } + } + } + } + + @EventHandler + public void onBlockPlace(BlockPlaceEvent event) { + if (event.getPlayer() == player) { + if (step == -1) { + double lengthX = Math.abs(event.getBlock().getX() - event.getPlayer().getLocation().getX()); + double lengthZ = Math.abs(event.getBlock().getZ() - event.getPlayer().getLocation().getZ()); + double v = getMaxDouble(lengthX >= lengthZ ? lengthX : lengthZ); + if (v != -1) { + blockPlaceMax = v; + } + } + } + } } diff --git a/src/main/java/net/h31ix/anticheat/util/Configuration.java b/src/main/java/net/h31ix/anticheat/util/Configuration.java index 0f9ef78..16eeb48 100644 --- a/src/main/java/net/h31ix/anticheat/util/Configuration.java +++ b/src/main/java/net/h31ix/anticheat/util/Configuration.java @@ -31,337 +31,272 @@ import org.bukkit.World; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; -public class Configuration -{ - private AnticheatManager micromanage = null; - private File configFile = null; - private File levelFile = null; - private File langFile = null; - private File magicFile = null; - private CommentedConfiguration config; - private FileConfiguration level; - private FileConfiguration magic; - private boolean logConsole; - private boolean logXRay; - private boolean alertXRay; - private boolean autoUpdate; - private boolean verboseStartup; - private boolean chatSpam; - private boolean commandSpam; - private boolean silentMode; - private boolean opExempt; - private boolean trackCreativeXRay; - private int fileLogLevel = 0; - private int medThreshold = 0; - private int highThreshold = 0; - private String updateFolder; - private String eventMed; - private String eventHigh; - private String chatActionKick; - private String chatActionBan; - private static Language language; - private List exemptWorlds = new ArrayList(); - - public Configuration(AnticheatManager instance) - { - micromanage = instance; - configFile = new File(micromanage.getPlugin().getDataFolder() + "/config.yml"); - levelFile = new File(micromanage.getPlugin().getDataFolder() + "/data/level.yml"); - langFile = new File(micromanage.getPlugin().getDataFolder() + "/lang.yml"); - magicFile = new File(micromanage.getPlugin().getDataFolder() + "/magic.yml"); - load(); - } - - private void save() - { - try - { - config.save(configFile); - } - catch (IOException ex) - { - Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); - } - } - - public boolean logConsole() - { - return logConsole; - } - - public boolean logXRay() - { - return logXRay; - } - - public boolean alertXRay() - { - return alertXRay; - } - - public boolean autoUpdate() - { - return autoUpdate; - } - - public boolean verboseStartup() - { - return verboseStartup; - } - - public boolean chatSpam() - { - return chatSpam; - } - - public boolean commandSpam() - { - return commandSpam; - } - - public String updateFolder() - { - return updateFolder; - } - - public boolean silentMode() - { - return silentMode; - } - - public boolean opExempt() - { - return opExempt; - } - - public boolean trackCreativeXRay() - { - return trackCreativeXRay; - } - - public int medThreshold() - { - return medThreshold; - } - - public int highThreshold() - { - return highThreshold; - } - - public String mediumEvent() - { - return eventMed; - } - - public String highEvent() - { - return eventHigh; - } - - public String chatActionKick() - { - return chatActionKick; - } - - public String chatActionBan() - { - return chatActionBan; - } - - public int getFileLogLevel() - { - return fileLogLevel; - } - - public Language getLang() - { - return language; - } - - public final void load() - { - micromanage.getPlugin().checkConfigs(); - config = CommentedConfiguration.loadConfig(configFile); - level = YamlConfiguration.loadConfiguration(levelFile); - magic = YamlConfiguration.loadConfiguration(magicFile); - language = new Language(YamlConfiguration.loadConfiguration(langFile), langFile); - updateFolder = Bukkit.getUpdateFolder(); - - // Begin pulling values from config. - logConsole = getBoolean("System.Log to console", false); - logXRay = getBoolean ("XRay.Log xray stats", true); - autoUpdate = getBoolean ("System.Auto update", true); - verboseStartup = getBoolean ("System.Verbose startup", false); - alertXRay = getBoolean("XRay.Alert when xray is found", false); - fileLogLevel = getInt("System.File log level", 1); - silentMode = getBoolean("System.Silent mode", false); - medThreshold = getInt("Events.Medium threshold", 20); - highThreshold = getInt("Events.High threshold", 50); - opExempt = getBoolean("System.Exempt op", false); - trackCreativeXRay = getBoolean("XRay.Track creative", true); - eventMed = getString("Events.Level Medium", "WARN"); - eventHigh = getString("Events.Level High", "KICK"); - chatActionKick = getString("Chat.Kick Action", "KICK"); - chatActionBan = getString("Chat.Ban Action", "BAN"); - chatSpam = getBoolean("Chat.Block chat spam", true); - commandSpam = getBoolean("Chat.Block command spam", false); - // Cleanup old values - if(config.getString("System.Block command spam") != null) - { - config.set("System.Block command spam", null); - } - if(config.getString("System.Block chat spam") != null) - { - config.set("System.Block chat spam", null); - } - - // Worlds - List list = new ArrayList(); - list.add("example-world"); - list.add("example-world-2"); - - if (config.getList("Enable in") != null) - { - List list2 = config.getStringList("Enable in"); - List list3 = new ArrayList(); - for(World world : micromanage.getPlugin().getServer().getWorlds()) - { - if(!list2.contains(world.getName())) - { - list3.add(world.getName()); - } - } - if(!list3.isEmpty()) - { - list = list3; - } - config.set("Enable in", null); - } - if (config.getList("Disable in") == null) - { - config.set("Disable in", list); - } - - exemptWorlds = config.getStringList("Disable in"); - // End pulling values from config - save(); - } - - private boolean getBoolean(String entry, boolean d) - { - if (config.getString(entry) == null) - { - config.set(entry, d); - return d; - } - else - { - return config.getBoolean(entry); - } - } - - private int getInt(String entry, int d) - { - if (config.getString(entry) == null) - { - config.set(entry, d); - return d; - } - else - { - return config.getInt(entry); - } - } - - private String getString(String entry, String d) - { - if (config.getString(entry) == null) - { - config.set(entry, d); - return d; - } - else - { - return config.getString(entry); - } - } - - public void setLog(boolean b) - { - config.set("System.Log to console", b); - this.logConsole = b; - try - { - config.save(configFile); - } - catch (IOException ex) - { - Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); - } - } - - public List getWorldsExempt() - { - return exemptWorlds; - } - - public File getConfigFile() - { - return configFile; - } - - public File getLevelFile() - { - return levelFile; - } - - public FileConfiguration getMagic() - { - return magic; - } - - public boolean checkInWorld(World world) - { - return !exemptWorlds.contains(world.getName()); - } - - public int getLevel(String player) - { - int x = -1; - if (level.getString(player) != null) - { - x = level.getInt(player); - } - return x; - } - - public void saveLevel(String user, int x) - { - level.set(user, x); - } - - public void saveLevels() - { - try - { - level.save(levelFile); - } - catch (IOException ex) - { - Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); - } - } - - public void saveMagic(FileConfiguration newMagic) - { - try - { - newMagic.save(magicFile); - } - catch (IOException ex) - { - Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); - } - } +public class Configuration { + private AnticheatManager micromanage = null; + private File configFile = null; + private File levelFile = null; + private File langFile = null; + private File magicFile = null; + private CommentedConfiguration config; + private FileConfiguration level; + private FileConfiguration magic; + private boolean logConsole; + private boolean logXRay; + private boolean alertXRay; + private boolean autoUpdate; + private boolean verboseStartup; + private boolean chatSpam; + private boolean commandSpam; + private boolean silentMode; + private boolean opExempt; + private boolean trackCreativeXRay; + private int fileLogLevel = 0; + private int medThreshold = 0; + private int highThreshold = 0; + private String updateFolder; + private String eventMed; + private String eventHigh; + private String chatActionKick; + private String chatActionBan; + private static Language language; + private List exemptWorlds = new ArrayList(); + + public Configuration(AnticheatManager instance) { + micromanage = instance; + configFile = new File(micromanage.getPlugin().getDataFolder() + "/config.yml"); + levelFile = new File(micromanage.getPlugin().getDataFolder() + "/data/level.yml"); + langFile = new File(micromanage.getPlugin().getDataFolder() + "/lang.yml"); + magicFile = new File(micromanage.getPlugin().getDataFolder() + "/magic.yml"); + load(); + } + + private void save() { + try { + config.save(configFile); + } catch (IOException ex) { + Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public boolean logConsole() { + return logConsole; + } + + public boolean logXRay() { + return logXRay; + } + + public boolean alertXRay() { + return alertXRay; + } + + public boolean autoUpdate() { + return autoUpdate; + } + + public boolean verboseStartup() { + return verboseStartup; + } + + public boolean chatSpam() { + return chatSpam; + } + + public boolean commandSpam() { + return commandSpam; + } + + public String updateFolder() { + return updateFolder; + } + + public boolean silentMode() { + return silentMode; + } + + public boolean opExempt() { + return opExempt; + } + + public boolean trackCreativeXRay() { + return trackCreativeXRay; + } + + public int medThreshold() { + return medThreshold; + } + + public int highThreshold() { + return highThreshold; + } + + public String mediumEvent() { + return eventMed; + } + + public String highEvent() { + return eventHigh; + } + + public String chatActionKick() { + return chatActionKick; + } + + public String chatActionBan() { + return chatActionBan; + } + + public int getFileLogLevel() { + return fileLogLevel; + } + + public Language getLang() { + return language; + } + + public final void load() { + micromanage.getPlugin().checkConfigs(); + config = CommentedConfiguration.loadConfig(configFile); + level = YamlConfiguration.loadConfiguration(levelFile); + magic = YamlConfiguration.loadConfiguration(magicFile); + language = new Language(YamlConfiguration.loadConfiguration(langFile), langFile); + updateFolder = Bukkit.getUpdateFolder(); + + // Begin pulling values from config. + logConsole = getBoolean("System.Log to console", false); + logXRay = getBoolean("XRay.Log xray stats", true); + autoUpdate = getBoolean("System.Auto update", true); + verboseStartup = getBoolean("System.Verbose startup", false); + alertXRay = getBoolean("XRay.Alert when xray is found", false); + fileLogLevel = getInt("System.File log level", 1); + silentMode = getBoolean("System.Silent mode", false); + medThreshold = getInt("Events.Medium threshold", 20); + highThreshold = getInt("Events.High threshold", 50); + opExempt = getBoolean("System.Exempt op", false); + trackCreativeXRay = getBoolean("XRay.Track creative", true); + eventMed = getString("Events.Level Medium", "WARN"); + eventHigh = getString("Events.Level High", "KICK"); + chatActionKick = getString("Chat.Kick Action", "KICK"); + chatActionBan = getString("Chat.Ban Action", "BAN"); + chatSpam = getBoolean("Chat.Block chat spam", true); + commandSpam = getBoolean("Chat.Block command spam", false); + // Cleanup old values + if (config.getString("System.Block command spam") != null) { + config.set("System.Block command spam", null); + } + if (config.getString("System.Block chat spam") != null) { + config.set("System.Block chat spam", null); + } + + // Worlds + List list = new ArrayList(); + list.add("example-world"); + list.add("example-world-2"); + + if (config.getList("Enable in") != null) { + List list2 = config.getStringList("Enable in"); + List list3 = new ArrayList(); + for (World world : micromanage.getPlugin().getServer().getWorlds()) { + if (!list2.contains(world.getName())) { + list3.add(world.getName()); + } + } + if (!list3.isEmpty()) { + list = list3; + } + config.set("Enable in", null); + } + if (config.getList("Disable in") == null) { + config.set("Disable in", list); + } + + exemptWorlds = config.getStringList("Disable in"); + // End pulling values from config + save(); + } + + private boolean getBoolean(String entry, boolean d) { + if (config.getString(entry) == null) { + config.set(entry, d); + return d; + } else { + return config.getBoolean(entry); + } + } + + private int getInt(String entry, int d) { + if (config.getString(entry) == null) { + config.set(entry, d); + return d; + } else { + return config.getInt(entry); + } + } + + private String getString(String entry, String d) { + if (config.getString(entry) == null) { + config.set(entry, d); + return d; + } else { + return config.getString(entry); + } + } + + public void setLog(boolean b) { + config.set("System.Log to console", b); + this.logConsole = b; + try { + config.save(configFile); + } catch (IOException ex) { + Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public List getWorldsExempt() { + return exemptWorlds; + } + + public File getConfigFile() { + return configFile; + } + + public File getLevelFile() { + return levelFile; + } + + public FileConfiguration getMagic() { + return magic; + } + + public boolean checkInWorld(World world) { + return !exemptWorlds.contains(world.getName()); + } + + public int getLevel(String player) { + int x = -1; + if (level.getString(player) != null) { + x = level.getInt(player); + } + return x; + } + + public void saveLevel(String user, int x) { + level.set(user, x); + } + + public void saveLevels() { + try { + level.save(levelFile); + } catch (IOException ex) { + Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void saveMagic(FileConfiguration newMagic) { + try { + newMagic.save(magicFile); + } catch (IOException ex) { + Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); + } + } } diff --git a/src/main/java/net/h31ix/anticheat/util/ConsoleFormatter.java b/src/main/java/net/h31ix/anticheat/util/ConsoleFormatter.java index cfe6200..3bb96ff 100644 --- a/src/main/java/net/h31ix/anticheat/util/ConsoleFormatter.java +++ b/src/main/java/net/h31ix/anticheat/util/ConsoleFormatter.java @@ -21,13 +21,11 @@ package net.h31ix.anticheat.util; import java.util.logging.Formatter; import java.util.logging.LogRecord; -public class ConsoleFormatter extends Formatter -{ - - @Override - public String format(LogRecord record) - { - StringBuilder output = new StringBuilder().append(record.getMessage()).append(' '); - return output.toString(); - } +public class ConsoleFormatter extends Formatter { + + @Override + public String format(LogRecord record) { + StringBuilder output = new StringBuilder().append(record.getMessage()).append(' '); + return output.toString(); + } } diff --git a/src/main/java/net/h31ix/anticheat/util/Distance.java b/src/main/java/net/h31ix/anticheat/util/Distance.java index 47c137f..c705b67 100644 --- a/src/main/java/net/h31ix/anticheat/util/Distance.java +++ b/src/main/java/net/h31ix/anticheat/util/Distance.java @@ -20,38 +20,31 @@ package net.h31ix.anticheat.util; import org.bukkit.Location; -public class Distance -{ - private final Location l1, l2; - - public Distance(Location from, Location to) - { - l1 = to; - l2 = from; - } - - public double fromY() - { - return l2.getY(); - } - - public double toY() - { - return l1.getY(); - } - - public double getXDifference() - { - return Math.abs(l1.getX() - l2.getX()); - } - - public double getZDifference() - { - return Math.abs(l1.getZ() - l2.getZ()); - } - - public double getYDifference() - { - return Math.abs(l1.getY() - l2.getY()); - } +public class Distance { + private final Location l1, l2; + + public Distance(Location from, Location to) { + l1 = to; + l2 = from; + } + + public double fromY() { + return l2.getY(); + } + + public double toY() { + return l1.getY(); + } + + public double getXDifference() { + return Math.abs(l1.getX() - l2.getX()); + } + + public double getZDifference() { + return Math.abs(l1.getZ() - l2.getZ()); + } + + public double getYDifference() { + return Math.abs(l1.getY() - l2.getY()); + } } diff --git a/src/main/java/net/h31ix/anticheat/util/FileFormatter.java b/src/main/java/net/h31ix/anticheat/util/FileFormatter.java index 7d4a298..f74a832 100644 --- a/src/main/java/net/h31ix/anticheat/util/FileFormatter.java +++ b/src/main/java/net/h31ix/anticheat/util/FileFormatter.java @@ -24,15 +24,13 @@ import java.util.Date; import java.util.logging.Formatter; import java.util.logging.LogRecord; -public class FileFormatter extends Formatter -{ - private static final DateFormat FORMAT = new SimpleDateFormat("h:mm:ss"); - private static final String LINE_SEP = System.getProperty("line.separator"); - - @Override - public String format(LogRecord record) - { - StringBuilder output = new StringBuilder().append("[").append(record.getLevel()).append('|').append(FORMAT.format(new Date(record.getMillis()))).append("]: ").append(record.getMessage()).append(' ').append(LINE_SEP); - return output.toString(); - } +public class FileFormatter extends Formatter { + private static final DateFormat FORMAT = new SimpleDateFormat("h:mm:ss"); + private static final String LINE_SEP = System.getProperty("line.separator"); + + @Override + public String format(LogRecord record) { + StringBuilder output = new StringBuilder().append("[").append(record.getLevel()).append('|').append(FORMAT.format(new Date(record.getMillis()))).append("]: ").append(record.getMessage()).append(' ').append(LINE_SEP); + return output.toString(); + } } diff --git a/src/main/java/net/h31ix/anticheat/util/Language.java b/src/main/java/net/h31ix/anticheat/util/Language.java index 7a6783d..8d99b07 100644 --- a/src/main/java/net/h31ix/anticheat/util/Language.java +++ b/src/main/java/net/h31ix/anticheat/util/Language.java @@ -28,135 +28,112 @@ import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; -public class Language -{ - private static String[] medAlert = null; - private static String[] highAlert = null; - private static String[] warning = null; - private static String banReason = null; - private static String banBroadcast = null; - private static String kickReason = null; - private static String kickBroadcast = null; - private static String chatWarning = null; - private static String chatKickBroadcast = null; - private static String chatKickReason = null; - private static String chatBanBroadcast = null; - private static String chatBanReason = null; - - private static final ChatColor GOLD = ChatColor.GOLD; - private static final ChatColor GRAY = ChatColor.GRAY; - private FileConfiguration file; - - public Language(FileConfiguration file, File f) - { - this.file = file; - String [] temp = file.getList("alert.medium_alert").toArray(new String[file.getList("alert.medium_alert").size()]); - medAlert = new String [temp.length+2]; - medAlert[0] = GOLD + "----------------------[" + GRAY + "AntiCheat" + GOLD + "]----------------------"; - for(int i=0;i getMediumAlert() - { - return new ArrayList(Arrays.asList(medAlert)); - } - - public List getHighAlert() - { - return new ArrayList(Arrays.asList(highAlert)); - } - - public List getWarning() - { - return new ArrayList(Arrays.asList(warning)); - } - - public String getBanReason() - { - return banReason; - } - - public String getBanBroadcast() - { - return banBroadcast; - } - - public String getKickReason() - { - return kickReason; - } - - public String getKickBroadcast() - { - return kickBroadcast; - } - - public String getChatKickReason() - { - return chatKickReason; - } - - public String getChatKickBroadcast() - { - return chatKickBroadcast; - } - - public String getChatBanReason() - { - return chatBanReason; - } - - public String getChatBanBroadcast() - { - return chatBanBroadcast; - } - - public String getChatWarning() - { - return chatWarning; - } - - private String getString(String entry, String d) - { - if (file.getString(entry) == null) - { - file.set(entry, d); - return d; - } - else - { - return file.getString(entry); - } - } +public class Language { + private static String[] medAlert = null; + private static String[] highAlert = null; + private static String[] warning = null; + private static String banReason = null; + private static String banBroadcast = null; + private static String kickReason = null; + private static String kickBroadcast = null; + private static String chatWarning = null; + private static String chatKickBroadcast = null; + private static String chatKickReason = null; + private static String chatBanBroadcast = null; + private static String chatBanReason = null; + + private static final ChatColor GOLD = ChatColor.GOLD; + private static final ChatColor GRAY = ChatColor.GRAY; + private FileConfiguration file; + + public Language(FileConfiguration file, File f) { + this.file = file; + String[] temp = file.getList("alert.medium_alert").toArray(new String[file.getList("alert.medium_alert").size()]); + medAlert = new String[temp.length + 2]; + medAlert[0] = GOLD + "----------------------[" + GRAY + "AntiCheat" + GOLD + "]----------------------"; + for (int i = 0; i < temp.length; i++) { + medAlert[i + 1] = GRAY + temp[i]; + } + medAlert[medAlert.length - 1] = GOLD + "-----------------------------------------------------"; + temp = file.getList("alert.high_alert").toArray(new String[file.getList("alert.high_alert").size()]); + highAlert = new String[temp.length + 2]; + highAlert[0] = GOLD + "----------------------[" + GRAY + "AntiCheat" + GOLD + "]----------------------"; + for (int i = 0; i < temp.length; i++) { + highAlert[i + 1] = GRAY + temp[i]; + } + highAlert[highAlert.length - 1] = GOLD + "-----------------------------------------------------"; + + warning = file.getList("warning.player_warning").toArray(new String[file.getList("warning.player_warning").size()]); + banReason = getString("ban.ban_reason", "Banned by AntiCheat"); + banBroadcast = getString("ban.ban_broadcast", "[AntiCheat] &player was banned for hacking."); + kickReason = getString("kick.kick_reason", "Kicked by AntiCheat"); + kickBroadcast = getString("kick.kick_broadcast", "[AntiCheat] &player was kicked for hacking."); + chatWarning = getString("chat.warning", "Stop spamming the server or you will be kicked!"); + chatKickReason = getString("chat.kick_reason", "Kicked for spamming"); + chatBanReason = getString("chat.ban_reason", "Banned for spamming"); + chatKickBroadcast = getString("chat.kick_broadcast", "[AntiCheat] &player was kicked for spamming"); + chatBanBroadcast = getString("chat.ban_broadcast", "[AntiCheat] &player was banned for spamming"); + try { + file.save(f); + } catch (IOException ex) { + Logger.getLogger(Language.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public List getMediumAlert() { + return new ArrayList(Arrays.asList(medAlert)); + } + + public List getHighAlert() { + return new ArrayList(Arrays.asList(highAlert)); + } + + public List getWarning() { + return new ArrayList(Arrays.asList(warning)); + } + + public String getBanReason() { + return banReason; + } + + public String getBanBroadcast() { + return banBroadcast; + } + + public String getKickReason() { + return kickReason; + } + + public String getKickBroadcast() { + return kickBroadcast; + } + + public String getChatKickReason() { + return chatKickReason; + } + + public String getChatKickBroadcast() { + return chatKickBroadcast; + } + + public String getChatBanReason() { + return chatBanReason; + } + + public String getChatBanBroadcast() { + return chatBanBroadcast; + } + + public String getChatWarning() { + return chatWarning; + } + + private String getString(String entry, String d) { + if (file.getString(entry) == null) { + file.set(entry, d); + return d; + } else { + return file.getString(entry); + } + } } diff --git a/src/main/java/net/h31ix/anticheat/util/Magic.java b/src/main/java/net/h31ix/anticheat/util/Magic.java index 527f141..4a0ade6 100644 --- a/src/main/java/net/h31ix/anticheat/util/Magic.java +++ b/src/main/java/net/h31ix/anticheat/util/Magic.java @@ -23,451 +23,431 @@ import org.bukkit.configuration.file.FileConfiguration; /** * Magic number class. Modifications to values in magic.yml will be accepted here. *

    - * Note that although each value is documented, changing it may have unintended side-effects. For instance, setting something to 0 that the plugin then uses as a dividend will result in an error. - *
    + * Note that although each value is documented, changing it may have unintended side-effects. For instance, setting something to 0 that the plugin then uses as a dividend will result in an error.
    * Also realize that the smaller a value is, the less you should change it; it's probably small for a reason. The larger a value is, the safer it is to probably change it. *

    - * How to read the value documentation: - *
    - * First, you will see a description of the value. Then, you will see a type: - *
    - * Type SYSTEM: This is a 'long' value, measured in milliseconds, used to compare past and future events with the current system time. Remember, 1000 ms = 1 second. - *
    - * Type INTEGER: This is a regular number. It's typically used as something trivial, such as how many times X event can occur. - *
    + * How to read the value documentation:
    + * First, you will see a description of the value. Then, you will see a type:
    + * Type SYSTEM: This is a 'long' value, measured in milliseconds, used to compare past and future events with the current system time. Remember, 1000 ms = 1 second.
    + * Type INTEGER: This is a regular number. It's typically used as something trivial, such as how many times X event can occur.
    * Type DOUBLE: This is a number that has a decimal in it. It's typically used to evaluate speed or distance. *

    - * After the type, you may see a recommendation labeled as '+Leniency'. This means 'In order to add leniency to this value, do X' - *
    + * After the type, you may see a recommendation labeled as '+Leniency'. This means 'In order to add leniency to this value, do X'
    * The suggestion for adding leniency will either be to INCREASE or DECREASE the variable. Doing what it suggests will cause the system to not judge the people being checked so vigorously. */ -public class Magic -{ - /** - * Time to exempt a player from moving because of entering/exiting a vehicle; Type=system, +Leniency=Increase. - */ - public final int ENTERED_EXITED_TIME; - /** - * Time to exempt a player from moving because of entering/exiting sneak mode; Type=system, +Leniency=Increase. - */ - public final int SNEAK_TIME; - /** - * Time to exempt a player from moving because of teleporting; Type=system, +Leniency=Increase. - */ - public final int TELEPORT_TIME; - /** - * Time to exempt a player from moving because of exiting fly mode; Type=system, +Leniency=Increase. - */ - public final int EXIT_FLY_TIME; - /** - * Time to exempt a player from moving because of joining the server; Type=system, +Leniency=Increase. - */ - public final int JOIN_TIME; - /** - * Time to exempt a player from fastbreak check because of using instant break; Type=seconds, +Leniency=Increase. - */ - public final int INSTANT_BREAK_TIME; - /** - * Time to exempt a player from moving because of taking damage; Type=system, +Leniency=Increase. - */ - public final long DAMAGE_TIME; - /** - * Time to exempt a player from moving because of taking damage with knockback effects; Type=system, +Leniency=Increase. - */ - public final long KNOCKBACK_DAMAGE_TIME; - /** - * Time to exempt a player from moving because of taking damage from an explosion; Type=system, +Leniency=Increase. - */ - public final long EXPLOSION_DAMAGE_TIME; - /** - * Minimum time it takes to fire X projectiles; Type=system, +Leniency=Decrease. - */ - public final int PROJECTILE_TIME_MIN; - /** - * Number of projectiles to wait for before checking how long they took to fire off; Type=integer. - */ - public final int PROJECTILE_CHECK; - /** - * Minimum time it takes to drop X items; Type=system, +Leniency=Decrease. - */ - public final int DROP_TIME_MIN; - /** - * Number of item drops to wait for before checking how long they took to drop; Type=integer. - */ - public final int DROP_CHECK; - /** - * Max number of blocks that can be broken in a given time; Type=integer, +Leniency=Increase. - */ - public final int FASTBREAK_LIMIT; - /** - * Time to wait before checking block breaks; Type=system, +Leniency=Increase. - */ - public final int FASTBREAK_TIMEMAX; - /** - * Time to wait before checking block breaks in creative mode; Type=system, +Leniency=Increase. - */ - public final int FASTBREAK_TIMEMAX_CREATIVE; - /** - * Number of times fastbreak can be observed before taking action; Type=integer, +Leniency=Increase. - */ - public final int FASTBREAK_MAXVIOLATIONS; - /** - * Number of times fastbreak can be observed before taking action in creative mode; Type=integer, +Leniency=Increase. - */ - public final int FASTBREAK_MAXVIOLATIONS_CREATIVE; - /** - * Time a player is forced to wait after fastbreak has been detected; Type=system, +Leniency=Decrease. - */ - public final int FASTBREAK_MAXVIOLATIONTIME; - /** - * Number of blocks that can be broken without being hit before taking action; Type=integer, +Leniency=Increase. - */ - public final int FASTPLACE_ZEROLIMIT; - /** - * Time to wait before checking block places; Type=system, +Leniency=Increase. - */ - public final int FASTPLACE_TIMEMAX; - /** - * Number of times fastplace can be observed before taking action; Type=integer, +Leniency=Increase. - */ - public final int FASTPLACE_MAXVIOLATIONS; - /** - * Number of times fastplace can be observed before taking action in creative mode; Type=integer, +Leniency=Increase. - */ - public final int FASTPLACE_MAXVIOLATIONS_CREATIVE; - /** - * Time a player is forced to wait after fastplace has been detected; Type=system, +Leniency=Decrease. - */ - public final int FASTPLACE_MAXVIOLATIONTIME; - /** - * Number of times required to punch a block before it breaks; Type=integer, +Leniency=Decrease. - */ - public final int BLOCK_PUNCH_MIN; - /** - * Number of chat spam violations before a player is warned; Type=integer, +Leniency=Increase. - */ - public final int CHAT_WARN_LEVEL; - /** - * Number of chat spam violations before a player is kicked; Type=integer, +Leniency=Increase. - */ - public final int CHAT_KICK_LEVEL; - /** - * Number of kicks for chat violation before a player is banned; Type=integer, +Leniency=Increase. - */ - public final int CHAT_BAN_LEVEL; - /** - * Number of times a player can be caught in-flight before action is taken; Type=integer, +Leniency=Increase. - */ - public final int FLIGHT_LIMIT; - /** - * How many blocks you can travel before action is taken; Type=integer, +Leniency=Increase. - */ - public final double FLIGHT_BLOCK_LIMIT; - /** - * Maximum speed that a player can climb a waterfall; Type=double, +Leniency=Increase. - */ - public final double WATER_CLIMB_MAX; - /** - * Number of times a player can fly on the y-axis before action is taken; Type=integer, +Leniency=Increase. - */ - public final int Y_MAXVIOLATIONS; - /** - * Time a player is forced to wait after flying on the y-axis; Type=system, +Leniency=Decrease. - */ - public final int Y_MAXVIOTIME; - /** - * Number of times a player can fail a velocity check before action is taken; Type=integer, +Leniency=Increase. - */ - public final int VELOCITY_TIME; - /** - * Time used to schedule increasing a players velocity count - probably not touching this would be good; Type=integer. - */ - public final long VELOCITY_SCHETIME; - /** - * Maximum time a player is considered to have a change in velocity; Type=system, +Leniency=Increase. - */ - public final long VELOCITY_CHECKTIME; - /** - * Time to extend a player's velocity count by; Type=system, +Leniency=Increase. - */ - public final long VELOCITY_PREVENT; - /** - * Number of times a player can fail the velocity check before action is taken; Type=integer, +Leniency=Increase. - */ - public final int VELOCITY_MAXTIMES; - /** - * Number of times a player can fail the nofall check before action is taken; Type=integer, +Leniency=Increase. - */ - public final int NOFALL_LIMIT; - /** - * Number of times a player can fail the ascension check before action is taken; Type=integer, +Leniency=Increase. - */ - public final int ASCENSION_COUNT_MAX; - /** - * Number of times a player can fail the ascension check while in water before action is taken; Type=integer, +Leniency=Increase. - */ - public final int WATER_ASCENSION_VIOLATION_MAX; - /** - * Number of times a player can be caught speeding in water before action is taken; Type=integer, +Leniency=Increase. - */ - public final int WATER_SPEED_VIOLATION_MAX; - /** - * Number of times a player can sprint without proper food level before action is taken; Type=integer, +Leniency=Increase. - */ - public final int SPRINT_FOOD_MIN; - /** - * Minimum time between animations; Type=system, +Leniency=Increase. - */ - public final int ANIMATION_MIN; - /** - * Minimum time between chats; Type=system, +Leniency=Increase. - */ - public final int CHAT_MIN; - /** - * Minimum time between repeating yourself in the chat; Type=system, +Leniency=Increase. - */ - public final int CHAT_REPEAT_MIN; - /** - * Maximum speed you can travel while sprinting; Type=double, +Leniency=Increase. - */ - public final double SPRINT_MIN; - /** - * Minimum time in between block breaks; Type=seconds, +Leniency=Decrease. - */ - public final double BLOCK_BREAK_MIN; - /** - * Minimum time in between block placing; Type=seconds, +Leniency=Decrease. - */ - public final double BLOCK_PLACE_MIN; - /** - * Minimum time in between healing; Type=system, +Leniency=Decrease. - */ - public final long HEAL_TIME_MIN; - /** - * Minimum time in between eating; Type=system, +Leniency=Decrease. - */ - public final long EAT_TIME_MIN; - /** - * Maximum percent error between predicted bow force and actual bow force; Type=double, +Leniency=Increase. - */ - public final double BOW_ERROR; - /** - * Minimum distance a player can break a block from; Type=double, +Leniency=Increase. - */ - public final double BLOCK_MAX_DISTANCE; - /** - * Minimum distance a player can damage an entity from; Type=double, +Leniency=Increase. - */ - public final double ENTITY_MAX_DISTANCE; - /** - * Maximum speed a player on a ladder can travel; Type=double, +Leniency=Increase. - */ - public final double LADDER_Y_MAX; - /** - * Minimum speed a player on a ladder can travel; Type=double, +Leniency=Decrease. - */ - public final double LADDER_Y_MIN; - /** - * Maximum speed a player can travel up; Type=double, +Leniency=Increase. - */ - public final double Y_SPEED_MAX; - /** - * Maximum difference between the player's last 2 Y values when traveling up; Type=double, +Leniency=Increase. - */ - public final double Y_MAXDIFF; - /** - * Time in between Y difference measures; Type=system, +Leniency=Decrease. - */ - public final long Y_TIME; - /** - * Maximum speed a player can travel forwards or backwards; Type=double, +Leniency=Increase. - */ - public final double XZ_SPEED_MAX; - /** - * Maximum speed a player can travel forwards or backwards while sprinting; Type=double, +Leniency=Increase. - */ - public final double XZ_SPEED_MAX_SPRINT; - /** - * Maximum speed a player can travel forwards or backwards while flying; Type=double, +Leniency=Increase. - */ - public final double XZ_SPEED_MAX_FLY; - /** - * Maximum speed a player can travel forwards or backwards while under the influence; Type=double, +Leniency=Increase. - */ - public final double XZ_SPEED_MAX_POTION; - /** - * Maximum speed a player can travel forwards or backwards while sneaking; Type=double, +Leniency=Increase. - */ - public final double XZ_SPEED_MAX_SNEAK; - /** - * Maximum speed a player can travel forwards or backwards in water; Type=double, +Leniency=Increase. - */ - public final double XZ_SPEED_MAX_WATER; - /** - * Maximum speed a player can travel forwards or backwards in water while sprinting; Type=double, +Leniency=Increase. - */ - public final double XZ_SPEED_MAX_WATER_SPRINT; - /** - * Maximum speed a player can travel forwards or backwards on soul sand; Type=double, +Leniency=Increase. - */ - public final double XZ_SPEED_MAX_SOULSAND; - /** - * Maximum speed a player can travel forwards or backwards on soul sand while sprinting; Type=double, +Leniency=Increase. - */ - public final double XZ_SPEED_MAX_SOULSAND_SPRINT; - /** - * Maximum times a player can fail the speed check before action is taken; Type=integer, +Leniency=Increase. - */ - public final int SPEED_MAX; - /** - * The number of clicks we should wait before checking if the player has used fast inventory; Type=integer; +Leniency=Increase. - */ - public final int INVENTORY_CHECK; - /** - * The minimum time it should have taken for the player to click X times; Type=integer; +Leniency=Increase. - */ - public final long INVENTORY_TIMEMIN; - /** - * The number of steps we should wait before checking if the player has used timer cheating; Type=integer; +Leniency=Increase. - */ - public final int TIMER_STEP_CHECK; - /** - * The minimum time it should have taken for the player to travel X steps; Type=system; +Leniency=Decrease. - */ - public final long TIMER_TIMEMIN; - - private FileConfiguration defaults; - private FileConfiguration magic; - private Configuration config; - - public Magic(FileConfiguration magic, Configuration config, FileConfiguration defaults) - { - this.magic = magic; - this.config = config; - this.defaults = defaults; - - // - - ENTERED_EXITED_TIME = getInt("ENTERED_EXITED_TIME"); - SNEAK_TIME = getInt("SNEAK_TIME"); - TELEPORT_TIME = getInt("TELEPORT_TIME"); - EXIT_FLY_TIME = getInt("EXIT_FLY_TIME"); - JOIN_TIME = getInt("JOIN_TIME"); - INSTANT_BREAK_TIME = getInt("INSTANT_BREAK_TIME"); - DAMAGE_TIME = getLong("DAMAGE_TIME"); - KNOCKBACK_DAMAGE_TIME = getLong("KNOCKBACK_DAMAGE_TIME"); - EXPLOSION_DAMAGE_TIME = getLong("EXPLOSION_DAMAGE_TIME"); - PROJECTILE_TIME_MIN = getInt("PROJECTILE_TIME_MIN"); - PROJECTILE_CHECK = getInt("PROJECTILE_CHECK"); - DROP_TIME_MIN = getInt("DROP_TIME_MIN"); - DROP_CHECK = getInt("DROP_CHECK"); - FASTBREAK_LIMIT = getInt("FASTBREAK_LIMIT"); - FASTBREAK_TIMEMAX = getInt("FASTBREAK_TIMEMAX"); - FASTBREAK_TIMEMAX_CREATIVE = getInt("FASTBREAK_TIMEMAX_CREATIVE"); - FASTBREAK_MAXVIOLATIONS = getInt("FASTBREAK_MAXVIOLATIONS"); - FASTBREAK_MAXVIOLATIONS_CREATIVE = getInt("FASTBREAK_MAXVIOLATIONS_CREATIVE"); - FASTBREAK_MAXVIOLATIONTIME = getInt("FASTBREAK_MAXVIOLATIONTIME"); - FASTPLACE_ZEROLIMIT = getInt("FASTPLACE_ZEROLIMIT"); - FASTPLACE_TIMEMAX = getInt("FASTPLACE_TIMEMAX"); - FASTPLACE_MAXVIOLATIONS = getInt("FASTPLACE_MAXVIOLATIONS"); - FASTPLACE_MAXVIOLATIONS_CREATIVE = getInt("FASTPLACE_MAXVIOLATIONS_CREATIVE"); - FASTPLACE_MAXVIOLATIONTIME = getInt("FASTPLACE_MAXVIOLATIONTIME"); - BLOCK_PUNCH_MIN = getInt("BLOCK_PUNCH_MIN"); - CHAT_WARN_LEVEL = getInt("CHAT_WARN_LEVEL"); - CHAT_KICK_LEVEL = getInt("CHAT_KICK_LEVEL"); - CHAT_BAN_LEVEL = getInt("CHAT_BAN_LEVEL"); - FLIGHT_LIMIT = getInt("FLIGHT_LIMIT"); - FLIGHT_BLOCK_LIMIT = getDouble("FLIGHT_BLOCK_LIMIT"); - WATER_CLIMB_MAX = getDouble("WATER_CLIMB_MAX"); - Y_MAXVIOLATIONS = getInt("Y_MAXVIOLATIONS"); - Y_MAXVIOTIME = getInt("Y_MAXVIOTIME"); - VELOCITY_TIME = getInt("VELOCITY_TIME"); - VELOCITY_SCHETIME = getLong("VELOCITY_SCHETIME"); - VELOCITY_CHECKTIME = getLong("VELOCITY_CHECKTIME"); - VELOCITY_PREVENT = getLong("VELOCITY_PREVENT"); - VELOCITY_MAXTIMES = getInt("VELOCITY_MAXTIMES"); - NOFALL_LIMIT = getInt("NOFALL_LIMIT"); - ASCENSION_COUNT_MAX = getInt("ASCENSION_COUNT_MAX"); - WATER_ASCENSION_VIOLATION_MAX = getInt("WATER_ASCENSION_VIOLATION_MAX"); - WATER_SPEED_VIOLATION_MAX = getInt("WATER_SPEED_VIOLATION_MAX"); - SPRINT_FOOD_MIN = getInt("SPRINT_FOOD_MIN"); - ANIMATION_MIN = getInt("ANIMATION_MIN"); - CHAT_MIN = getInt("CHAT_MIN"); - CHAT_REPEAT_MIN = getInt("CHAT_REPEAT_MIN"); - SPRINT_MIN = getDouble("SPRINT_MIN"); - BLOCK_BREAK_MIN = getDouble("BLOCK_BREAK_MIN"); - BLOCK_PLACE_MIN = getDouble("BLOCK_PLACE_MIN"); - HEAL_TIME_MIN = getLong("HEAL_TIME_MIN"); - EAT_TIME_MIN = getLong("EAT_TIME_MIN"); - BOW_ERROR = getDouble("BOW_ERROR"); - BLOCK_MAX_DISTANCE = getDouble("BLOCK_MAX_DISTANCE"); - ENTITY_MAX_DISTANCE = getDouble("ENTITY_MAX_DISTANCE"); - LADDER_Y_MAX = getDouble("LADDER_Y_MAX"); - LADDER_Y_MIN = getDouble("LADDER_Y_MIN"); - Y_SPEED_MAX = getDouble("Y_SPEED_MAX"); - Y_MAXDIFF = getDouble("Y_MAXDIFF"); - Y_TIME = getLong("Y_TIME"); - XZ_SPEED_MAX = getDouble("XZ_SPEED_MAX"); - XZ_SPEED_MAX_SPRINT = getDouble("XZ_SPEED_MAX_SPRINT"); - XZ_SPEED_MAX_FLY = getDouble("XZ_SPEED_MAX_FLY"); - XZ_SPEED_MAX_POTION = getDouble("XZ_SPEED_MAX_POTION"); - XZ_SPEED_MAX_SNEAK = getDouble("XZ_SPEED_MAX_SNEAK"); - XZ_SPEED_MAX_WATER = getDouble("XZ_SPEED_MAX_WATER"); - XZ_SPEED_MAX_SOULSAND = getDouble("XZ_SPEED_MAX_SOULSAND"); - XZ_SPEED_MAX_SOULSAND_SPRINT = getDouble("XZ_SPEED_MAX_SOULSAND_SPRINT"); - XZ_SPEED_MAX_WATER_SPRINT = getDouble("XZ_SPEED_MAX_WATER_SPRINT"); - SPEED_MAX = getInt("SPEED_MAX"); - INVENTORY_CHECK = getInt("INVENTORY_CHECK"); - INVENTORY_TIMEMIN = getInt("INVENTORY_TIMEMIN"); - TIMER_STEP_CHECK = getInt("TIMER_STEP_CHECK"); - TIMER_TIMEMIN = getLong("TIMER_TIMEMIN"); - } - - private int getInt(String path) - { - if(magic.contains(path)) - { - return magic.getInt(path); - } - else - { - int i = defaults.getInt(path); - magic.set(path, i); - config.saveMagic(magic); - return i; - } - } - - private double getDouble(String path) - { - if(magic.contains(path)) - { - return magic.getDouble(path); - } - else - { - double i = defaults.getDouble(path); - magic.set(path, i); - config.saveMagic(magic); - return i; - } - } - - private long getLong(String path) - { - if(magic.contains(path)) - { - return magic.getLong(path); - } - else - { - long i = defaults.getLong(path); - magic.set(path, i); - config.saveMagic(magic); - return i; - } - } - - +public class Magic { + /** + * Time to exempt a player from moving because of entering/exiting a vehicle; Type=system, +Leniency=Increase. + */ + public final int ENTERED_EXITED_TIME; + /** + * Time to exempt a player from moving because of entering/exiting sneak mode; Type=system, +Leniency=Increase. + */ + public final int SNEAK_TIME; + /** + * Time to exempt a player from moving because of teleporting; Type=system, +Leniency=Increase. + */ + public final int TELEPORT_TIME; + /** + * Time to exempt a player from moving because of exiting fly mode; Type=system, +Leniency=Increase. + */ + public final int EXIT_FLY_TIME; + /** + * Time to exempt a player from moving because of joining the server; Type=system, +Leniency=Increase. + */ + public final int JOIN_TIME; + /** + * Time to exempt a player from fastbreak check because of using instant break; Type=seconds, +Leniency=Increase. + */ + public final int INSTANT_BREAK_TIME; + /** + * Time to exempt a player from moving because of taking damage; Type=system, +Leniency=Increase. + */ + public final long DAMAGE_TIME; + /** + * Time to exempt a player from moving because of taking damage with knockback effects; Type=system, +Leniency=Increase. + */ + public final long KNOCKBACK_DAMAGE_TIME; + /** + * Time to exempt a player from moving because of taking damage from an explosion; Type=system, +Leniency=Increase. + */ + public final long EXPLOSION_DAMAGE_TIME; + /** + * Minimum time it takes to fire X projectiles; Type=system, +Leniency=Decrease. + */ + public final int PROJECTILE_TIME_MIN; + /** + * Number of projectiles to wait for before checking how long they took to fire off; Type=integer. + */ + public final int PROJECTILE_CHECK; + /** + * Minimum time it takes to drop X items; Type=system, +Leniency=Decrease. + */ + public final int DROP_TIME_MIN; + /** + * Number of item drops to wait for before checking how long they took to drop; Type=integer. + */ + public final int DROP_CHECK; + /** + * Max number of blocks that can be broken in a given time; Type=integer, +Leniency=Increase. + */ + public final int FASTBREAK_LIMIT; + /** + * Time to wait before checking block breaks; Type=system, +Leniency=Increase. + */ + public final int FASTBREAK_TIMEMAX; + /** + * Time to wait before checking block breaks in creative mode; Type=system, +Leniency=Increase. + */ + public final int FASTBREAK_TIMEMAX_CREATIVE; + /** + * Number of times fastbreak can be observed before taking action; Type=integer, +Leniency=Increase. + */ + public final int FASTBREAK_MAXVIOLATIONS; + /** + * Number of times fastbreak can be observed before taking action in creative mode; Type=integer, +Leniency=Increase. + */ + public final int FASTBREAK_MAXVIOLATIONS_CREATIVE; + /** + * Time a player is forced to wait after fastbreak has been detected; Type=system, +Leniency=Decrease. + */ + public final int FASTBREAK_MAXVIOLATIONTIME; + /** + * Number of blocks that can be broken without being hit before taking action; Type=integer, +Leniency=Increase. + */ + public final int FASTPLACE_ZEROLIMIT; + /** + * Time to wait before checking block places; Type=system, +Leniency=Increase. + */ + public final int FASTPLACE_TIMEMAX; + /** + * Number of times fastplace can be observed before taking action; Type=integer, +Leniency=Increase. + */ + public final int FASTPLACE_MAXVIOLATIONS; + /** + * Number of times fastplace can be observed before taking action in creative mode; Type=integer, +Leniency=Increase. + */ + public final int FASTPLACE_MAXVIOLATIONS_CREATIVE; + /** + * Time a player is forced to wait after fastplace has been detected; Type=system, +Leniency=Decrease. + */ + public final int FASTPLACE_MAXVIOLATIONTIME; + /** + * Number of times required to punch a block before it breaks; Type=integer, +Leniency=Decrease. + */ + public final int BLOCK_PUNCH_MIN; + /** + * Number of chat spam violations before a player is warned; Type=integer, +Leniency=Increase. + */ + public final int CHAT_WARN_LEVEL; + /** + * Number of chat spam violations before a player is kicked; Type=integer, +Leniency=Increase. + */ + public final int CHAT_KICK_LEVEL; + /** + * Number of kicks for chat violation before a player is banned; Type=integer, +Leniency=Increase. + */ + public final int CHAT_BAN_LEVEL; + /** + * Number of times a player can be caught in-flight before action is taken; Type=integer, +Leniency=Increase. + */ + public final int FLIGHT_LIMIT; + /** + * How many blocks you can travel before action is taken; Type=integer, +Leniency=Increase. + */ + public final double FLIGHT_BLOCK_LIMIT; + /** + * Maximum speed that a player can climb a waterfall; Type=double, +Leniency=Increase. + */ + public final double WATER_CLIMB_MAX; + /** + * Number of times a player can fly on the y-axis before action is taken; Type=integer, +Leniency=Increase. + */ + public final int Y_MAXVIOLATIONS; + /** + * Time a player is forced to wait after flying on the y-axis; Type=system, +Leniency=Decrease. + */ + public final int Y_MAXVIOTIME; + /** + * Number of times a player can fail a velocity check before action is taken; Type=integer, +Leniency=Increase. + */ + public final int VELOCITY_TIME; + /** + * Time used to schedule increasing a players velocity count - probably not touching this would be good; Type=integer. + */ + public final long VELOCITY_SCHETIME; + /** + * Maximum time a player is considered to have a change in velocity; Type=system, +Leniency=Increase. + */ + public final long VELOCITY_CHECKTIME; + /** + * Time to extend a player's velocity count by; Type=system, +Leniency=Increase. + */ + public final long VELOCITY_PREVENT; + /** + * Number of times a player can fail the velocity check before action is taken; Type=integer, +Leniency=Increase. + */ + public final int VELOCITY_MAXTIMES; + /** + * Number of times a player can fail the nofall check before action is taken; Type=integer, +Leniency=Increase. + */ + public final int NOFALL_LIMIT; + /** + * Number of times a player can fail the ascension check before action is taken; Type=integer, +Leniency=Increase. + */ + public final int ASCENSION_COUNT_MAX; + /** + * Number of times a player can fail the ascension check while in water before action is taken; Type=integer, +Leniency=Increase. + */ + public final int WATER_ASCENSION_VIOLATION_MAX; + /** + * Number of times a player can be caught speeding in water before action is taken; Type=integer, +Leniency=Increase. + */ + public final int WATER_SPEED_VIOLATION_MAX; + /** + * Number of times a player can sprint without proper food level before action is taken; Type=integer, +Leniency=Increase. + */ + public final int SPRINT_FOOD_MIN; + /** + * Minimum time between animations; Type=system, +Leniency=Increase. + */ + public final int ANIMATION_MIN; + /** + * Minimum time between chats; Type=system, +Leniency=Increase. + */ + public final int CHAT_MIN; + /** + * Minimum time between repeating yourself in the chat; Type=system, +Leniency=Increase. + */ + public final int CHAT_REPEAT_MIN; + /** + * Maximum speed you can travel while sprinting; Type=double, +Leniency=Increase. + */ + public final double SPRINT_MIN; + /** + * Minimum time in between block breaks; Type=seconds, +Leniency=Decrease. + */ + public final double BLOCK_BREAK_MIN; + /** + * Minimum time in between block placing; Type=seconds, +Leniency=Decrease. + */ + public final double BLOCK_PLACE_MIN; + /** + * Minimum time in between healing; Type=system, +Leniency=Decrease. + */ + public final long HEAL_TIME_MIN; + /** + * Minimum time in between eating; Type=system, +Leniency=Decrease. + */ + public final long EAT_TIME_MIN; + /** + * Maximum percent error between predicted bow force and actual bow force; Type=double, +Leniency=Increase. + */ + public final double BOW_ERROR; + /** + * Minimum distance a player can break a block from; Type=double, +Leniency=Increase. + */ + public final double BLOCK_MAX_DISTANCE; + /** + * Minimum distance a player can damage an entity from; Type=double, +Leniency=Increase. + */ + public final double ENTITY_MAX_DISTANCE; + /** + * Maximum speed a player on a ladder can travel; Type=double, +Leniency=Increase. + */ + public final double LADDER_Y_MAX; + /** + * Minimum speed a player on a ladder can travel; Type=double, +Leniency=Decrease. + */ + public final double LADDER_Y_MIN; + /** + * Maximum speed a player can travel up; Type=double, +Leniency=Increase. + */ + public final double Y_SPEED_MAX; + /** + * Maximum difference between the player's last 2 Y values when traveling up; Type=double, +Leniency=Increase. + */ + public final double Y_MAXDIFF; + /** + * Time in between Y difference measures; Type=system, +Leniency=Decrease. + */ + public final long Y_TIME; + /** + * Maximum speed a player can travel forwards or backwards; Type=double, +Leniency=Increase. + */ + public final double XZ_SPEED_MAX; + /** + * Maximum speed a player can travel forwards or backwards while sprinting; Type=double, +Leniency=Increase. + */ + public final double XZ_SPEED_MAX_SPRINT; + /** + * Maximum speed a player can travel forwards or backwards while flying; Type=double, +Leniency=Increase. + */ + public final double XZ_SPEED_MAX_FLY; + /** + * Maximum speed a player can travel forwards or backwards while under the influence; Type=double, +Leniency=Increase. + */ + public final double XZ_SPEED_MAX_POTION; + /** + * Maximum speed a player can travel forwards or backwards while sneaking; Type=double, +Leniency=Increase. + */ + public final double XZ_SPEED_MAX_SNEAK; + /** + * Maximum speed a player can travel forwards or backwards in water; Type=double, +Leniency=Increase. + */ + public final double XZ_SPEED_MAX_WATER; + /** + * Maximum speed a player can travel forwards or backwards in water while sprinting; Type=double, +Leniency=Increase. + */ + public final double XZ_SPEED_MAX_WATER_SPRINT; + /** + * Maximum speed a player can travel forwards or backwards on soul sand; Type=double, +Leniency=Increase. + */ + public final double XZ_SPEED_MAX_SOULSAND; + /** + * Maximum speed a player can travel forwards or backwards on soul sand while sprinting; Type=double, +Leniency=Increase. + */ + public final double XZ_SPEED_MAX_SOULSAND_SPRINT; + /** + * Maximum times a player can fail the speed check before action is taken; Type=integer, +Leniency=Increase. + */ + public final int SPEED_MAX; + /** + * The number of clicks we should wait before checking if the player has used fast inventory; Type=integer; +Leniency=Increase. + */ + public final int INVENTORY_CHECK; + /** + * The minimum time it should have taken for the player to click X times; Type=integer; +Leniency=Increase. + */ + public final long INVENTORY_TIMEMIN; + /** + * The number of steps we should wait before checking if the player has used timer cheating; Type=integer; +Leniency=Increase. + */ + public final int TIMER_STEP_CHECK; + /** + * The minimum time it should have taken for the player to travel X steps; Type=system; +Leniency=Decrease. + */ + public final long TIMER_TIMEMIN; + + private FileConfiguration defaults; + private FileConfiguration magic; + private Configuration config; + + public Magic(FileConfiguration magic, Configuration config, FileConfiguration defaults) { + this.magic = magic; + this.config = config; + this.defaults = defaults; + + // + + ENTERED_EXITED_TIME = getInt("ENTERED_EXITED_TIME"); + SNEAK_TIME = getInt("SNEAK_TIME"); + TELEPORT_TIME = getInt("TELEPORT_TIME"); + EXIT_FLY_TIME = getInt("EXIT_FLY_TIME"); + JOIN_TIME = getInt("JOIN_TIME"); + INSTANT_BREAK_TIME = getInt("INSTANT_BREAK_TIME"); + DAMAGE_TIME = getLong("DAMAGE_TIME"); + KNOCKBACK_DAMAGE_TIME = getLong("KNOCKBACK_DAMAGE_TIME"); + EXPLOSION_DAMAGE_TIME = getLong("EXPLOSION_DAMAGE_TIME"); + PROJECTILE_TIME_MIN = getInt("PROJECTILE_TIME_MIN"); + PROJECTILE_CHECK = getInt("PROJECTILE_CHECK"); + DROP_TIME_MIN = getInt("DROP_TIME_MIN"); + DROP_CHECK = getInt("DROP_CHECK"); + FASTBREAK_LIMIT = getInt("FASTBREAK_LIMIT"); + FASTBREAK_TIMEMAX = getInt("FASTBREAK_TIMEMAX"); + FASTBREAK_TIMEMAX_CREATIVE = getInt("FASTBREAK_TIMEMAX_CREATIVE"); + FASTBREAK_MAXVIOLATIONS = getInt("FASTBREAK_MAXVIOLATIONS"); + FASTBREAK_MAXVIOLATIONS_CREATIVE = getInt("FASTBREAK_MAXVIOLATIONS_CREATIVE"); + FASTBREAK_MAXVIOLATIONTIME = getInt("FASTBREAK_MAXVIOLATIONTIME"); + FASTPLACE_ZEROLIMIT = getInt("FASTPLACE_ZEROLIMIT"); + FASTPLACE_TIMEMAX = getInt("FASTPLACE_TIMEMAX"); + FASTPLACE_MAXVIOLATIONS = getInt("FASTPLACE_MAXVIOLATIONS"); + FASTPLACE_MAXVIOLATIONS_CREATIVE = getInt("FASTPLACE_MAXVIOLATIONS_CREATIVE"); + FASTPLACE_MAXVIOLATIONTIME = getInt("FASTPLACE_MAXVIOLATIONTIME"); + BLOCK_PUNCH_MIN = getInt("BLOCK_PUNCH_MIN"); + CHAT_WARN_LEVEL = getInt("CHAT_WARN_LEVEL"); + CHAT_KICK_LEVEL = getInt("CHAT_KICK_LEVEL"); + CHAT_BAN_LEVEL = getInt("CHAT_BAN_LEVEL"); + FLIGHT_LIMIT = getInt("FLIGHT_LIMIT"); + FLIGHT_BLOCK_LIMIT = getDouble("FLIGHT_BLOCK_LIMIT"); + WATER_CLIMB_MAX = getDouble("WATER_CLIMB_MAX"); + Y_MAXVIOLATIONS = getInt("Y_MAXVIOLATIONS"); + Y_MAXVIOTIME = getInt("Y_MAXVIOTIME"); + VELOCITY_TIME = getInt("VELOCITY_TIME"); + VELOCITY_SCHETIME = getLong("VELOCITY_SCHETIME"); + VELOCITY_CHECKTIME = getLong("VELOCITY_CHECKTIME"); + VELOCITY_PREVENT = getLong("VELOCITY_PREVENT"); + VELOCITY_MAXTIMES = getInt("VELOCITY_MAXTIMES"); + NOFALL_LIMIT = getInt("NOFALL_LIMIT"); + ASCENSION_COUNT_MAX = getInt("ASCENSION_COUNT_MAX"); + WATER_ASCENSION_VIOLATION_MAX = getInt("WATER_ASCENSION_VIOLATION_MAX"); + WATER_SPEED_VIOLATION_MAX = getInt("WATER_SPEED_VIOLATION_MAX"); + SPRINT_FOOD_MIN = getInt("SPRINT_FOOD_MIN"); + ANIMATION_MIN = getInt("ANIMATION_MIN"); + CHAT_MIN = getInt("CHAT_MIN"); + CHAT_REPEAT_MIN = getInt("CHAT_REPEAT_MIN"); + SPRINT_MIN = getDouble("SPRINT_MIN"); + BLOCK_BREAK_MIN = getDouble("BLOCK_BREAK_MIN"); + BLOCK_PLACE_MIN = getDouble("BLOCK_PLACE_MIN"); + HEAL_TIME_MIN = getLong("HEAL_TIME_MIN"); + EAT_TIME_MIN = getLong("EAT_TIME_MIN"); + BOW_ERROR = getDouble("BOW_ERROR"); + BLOCK_MAX_DISTANCE = getDouble("BLOCK_MAX_DISTANCE"); + ENTITY_MAX_DISTANCE = getDouble("ENTITY_MAX_DISTANCE"); + LADDER_Y_MAX = getDouble("LADDER_Y_MAX"); + LADDER_Y_MIN = getDouble("LADDER_Y_MIN"); + Y_SPEED_MAX = getDouble("Y_SPEED_MAX"); + Y_MAXDIFF = getDouble("Y_MAXDIFF"); + Y_TIME = getLong("Y_TIME"); + XZ_SPEED_MAX = getDouble("XZ_SPEED_MAX"); + XZ_SPEED_MAX_SPRINT = getDouble("XZ_SPEED_MAX_SPRINT"); + XZ_SPEED_MAX_FLY = getDouble("XZ_SPEED_MAX_FLY"); + XZ_SPEED_MAX_POTION = getDouble("XZ_SPEED_MAX_POTION"); + XZ_SPEED_MAX_SNEAK = getDouble("XZ_SPEED_MAX_SNEAK"); + XZ_SPEED_MAX_WATER = getDouble("XZ_SPEED_MAX_WATER"); + XZ_SPEED_MAX_SOULSAND = getDouble("XZ_SPEED_MAX_SOULSAND"); + XZ_SPEED_MAX_SOULSAND_SPRINT = getDouble("XZ_SPEED_MAX_SOULSAND_SPRINT"); + XZ_SPEED_MAX_WATER_SPRINT = getDouble("XZ_SPEED_MAX_WATER_SPRINT"); + SPEED_MAX = getInt("SPEED_MAX"); + INVENTORY_CHECK = getInt("INVENTORY_CHECK"); + INVENTORY_TIMEMIN = getInt("INVENTORY_TIMEMIN"); + TIMER_STEP_CHECK = getInt("TIMER_STEP_CHECK"); + TIMER_TIMEMIN = getLong("TIMER_TIMEMIN"); + } + + private int getInt(String path) { + if (magic.contains(path)) { + return magic.getInt(path); + } else { + int i = defaults.getInt(path); + magic.set(path, i); + config.saveMagic(magic); + return i; + } + } + + private double getDouble(String path) { + if (magic.contains(path)) { + return magic.getDouble(path); + } else { + double i = defaults.getDouble(path); + magic.set(path, i); + config.saveMagic(magic); + return i; + } + } + + private long getLong(String path) { + if (magic.contains(path)) { + return magic.getLong(path); + } else { + long i = defaults.getLong(path); + magic.set(path, i); + config.saveMagic(magic); + return i; + } + } + + } diff --git a/src/main/java/net/h31ix/anticheat/util/PastebinReport.java b/src/main/java/net/h31ix/anticheat/util/PastebinReport.java index 3f93c54..691201f 100644 --- a/src/main/java/net/h31ix/anticheat/util/PastebinReport.java +++ b/src/main/java/net/h31ix/anticheat/util/PastebinReport.java @@ -30,145 +30,115 @@ import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -public class PastebinReport -{ - private StringBuilder report = new StringBuilder(); - private String url = ""; - private Date date = new Date(); - private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd kk:mm Z"); - - public PastebinReport(CommandSender cs) - { - Player player = null; - try - { - player = (Player) cs; - } - catch (Exception e) - { - cs.sendMessage(ChatColor.RED + "We were unable to detect a player when making this report. Skipping permstester"); - } - - createReport(player); - try - { - writeReport(); - } - catch (IOException e) - { - } - postReport(); - } - - public String getURL() - { - return url; - } - - private void appendPermissionsTester(Player player) - { - if (player == null) - { - return; - } - - // alrighty then noobs. - for(Permission node : Permission.values()) - { - report.append(player.getName() + ": " + node.toString() + " " + node.get(player) + '\n'); - } - - } - - private void createReport(Player player) - { - report.append("------------ AntiCheat Report - " + format.format(date) + " ------------" + '\n'); - report.append("Version: " + Anticheat.getVersion() + '\n'); - report.append("CraftBukkit: " + Bukkit.getVersion() + '\n'); - report.append("Plugin Count: " + Bukkit.getPluginManager().getPlugins().length + '\n'); - appendSystemInfo(); - report.append("------------Last 30 logs------------" + '\n'); - for (String log : Anticheat.getManager().getLastLogs()) - { - report.append("[AntiCheat] " + log + '\n'); - } - report.append("------------Permission Tester------------" + '\n'); - appendPermissionsTester(player); - report.append("-----------End Of Report------------"); - } - - private void appendSystemInfo() - { - Runtime runtime = Runtime.getRuntime(); - report.append("Java: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version") + '\n'); - report.append("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + '\n'); - report.append("Free Memory: " + runtime.freeMemory() / 1024 / 1024 + "MB" + '\n'); - report.append("Max Memory: " + runtime.maxMemory() / 1024 / 1024 + "MB" + '\n'); - report.append("Total Memory: " + runtime.totalMemory() / 1024 / 1024 + "MB" + '\n'); - report.append("Server ID + Name: " + Bukkit.getServerId() + " - " + Bukkit.getName() + '\n'); - report.append("Players: " + Bukkit.getOnlinePlayers().length + "/" + Bukkit.getMaxPlayers() + '\n'); - } - - private void writeReport() throws IOException - { - File f = new File(Anticheat.getPlugin().getDataFolder() + "/report.txt"); - FileWriter r = new FileWriter(f); - BufferedWriter writer = new BufferedWriter(r); - writer.write(report.toString()); - writer.close(); - } - - private void postReport() - { - try - { - URL urls = new URL("http://pastebin.com/api/api_post.php"); - HttpURLConnection conn = (HttpURLConnection) urls.openConnection(); - conn.setConnectTimeout(5000); - conn.setReadTimeout(5000); - conn.setRequestMethod("POST"); - conn.addRequestProperty("Content-type", "application/x-www-form-urlencoded"); - conn.setInstanceFollowRedirects(false); - conn.setDoOutput(true); - OutputStream out = conn.getOutputStream(); - - out.write(("api_option=paste" + "&api_dev_key=" + URLEncoder.encode("c0616def494dcb5b7632304f8c52c0f1", "utf-8") + "&api_paste_code=" + URLEncoder.encode(report.toString(), "utf-8") + "&api_paste_private=" + URLEncoder.encode("1", "utf-8") + "&api_paste_name=" + URLEncoder.encode("", "utf-8") + "&api_paste_expire_date=" + URLEncoder.encode("1M", "utf-8") + "&api_paste_format=" + URLEncoder.encode("text", "utf-8") + "&api_user_key=" + URLEncoder.encode("", "utf-8")).getBytes()); - out.flush(); - out.close(); - - if (conn.getResponseCode() == 200) - { - InputStream receive = conn.getInputStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(receive)); - String line; - StringBuffer response = new StringBuffer(); - while ((line = reader.readLine()) != null) - { - response.append(line); - response.append("\r\n"); - } - reader.close(); - - String result = response.toString().trim(); - - if (!result.contains("http://")) - { - url = "Failed to post. Check report.txt"; - } - else - { - url = result.trim(); - } - } - else - { - url = "Failed to post. Check report.txt"; - } - } - catch (Exception e) - { - url = "Failed to post. Check report.txt"; - } - } - +public class PastebinReport { + private StringBuilder report = new StringBuilder(); + private String url = ""; + private Date date = new Date(); + private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd kk:mm Z"); + + public PastebinReport(CommandSender cs) { + Player player = null; + try { + player = (Player) cs; + } catch (Exception e) { + cs.sendMessage(ChatColor.RED + "We were unable to detect a player when making this report. Skipping permstester"); + } + + createReport(player); + try { + writeReport(); + } catch (IOException e) {} + postReport(); + } + + public String getURL() { + return url; + } + + private void appendPermissionsTester(Player player) { + if (player == null) { return; } + + // alrighty then noobs. + for (Permission node : Permission.values()) { + report.append(player.getName() + ": " + node.toString() + " " + node.get(player) + '\n'); + } + + } + + private void createReport(Player player) { + report.append("------------ AntiCheat Report - " + format.format(date) + " ------------" + '\n'); + report.append("Version: " + Anticheat.getVersion() + '\n'); + report.append("CraftBukkit: " + Bukkit.getVersion() + '\n'); + report.append("Plugin Count: " + Bukkit.getPluginManager().getPlugins().length + '\n'); + appendSystemInfo(); + report.append("------------Last 30 logs------------" + '\n'); + for (String log : Anticheat.getManager().getLastLogs()) { + report.append("[AntiCheat] " + log + '\n'); + } + report.append("------------Permission Tester------------" + '\n'); + appendPermissionsTester(player); + report.append("-----------End Of Report------------"); + } + + private void appendSystemInfo() { + Runtime runtime = Runtime.getRuntime(); + report.append("Java: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version") + '\n'); + report.append("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + '\n'); + report.append("Free Memory: " + runtime.freeMemory() / 1024 / 1024 + "MB" + '\n'); + report.append("Max Memory: " + runtime.maxMemory() / 1024 / 1024 + "MB" + '\n'); + report.append("Total Memory: " + runtime.totalMemory() / 1024 / 1024 + "MB" + '\n'); + report.append("Server ID + Name: " + Bukkit.getServerId() + " - " + Bukkit.getName() + '\n'); + report.append("Players: " + Bukkit.getOnlinePlayers().length + "/" + Bukkit.getMaxPlayers() + '\n'); + } + + private void writeReport() throws IOException { + File f = new File(Anticheat.getPlugin().getDataFolder() + "/report.txt"); + FileWriter r = new FileWriter(f); + BufferedWriter writer = new BufferedWriter(r); + writer.write(report.toString()); + writer.close(); + } + + private void postReport() { + try { + URL urls = new URL("http://pastebin.com/api/api_post.php"); + HttpURLConnection conn = (HttpURLConnection) urls.openConnection(); + conn.setConnectTimeout(5000); + conn.setReadTimeout(5000); + conn.setRequestMethod("POST"); + conn.addRequestProperty("Content-type", "application/x-www-form-urlencoded"); + conn.setInstanceFollowRedirects(false); + conn.setDoOutput(true); + OutputStream out = conn.getOutputStream(); + + out.write(("api_option=paste" + "&api_dev_key=" + URLEncoder.encode("c0616def494dcb5b7632304f8c52c0f1", "utf-8") + "&api_paste_code=" + URLEncoder.encode(report.toString(), "utf-8") + "&api_paste_private=" + URLEncoder.encode("1", "utf-8") + "&api_paste_name=" + URLEncoder.encode("", "utf-8") + "&api_paste_expire_date=" + URLEncoder.encode("1M", "utf-8") + "&api_paste_format=" + URLEncoder.encode("text", "utf-8") + "&api_user_key=" + URLEncoder.encode("", "utf-8")).getBytes()); + out.flush(); + out.close(); + + if (conn.getResponseCode() == 200) { + InputStream receive = conn.getInputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(receive)); + String line; + StringBuffer response = new StringBuffer(); + while ((line = reader.readLine()) != null) { + response.append(line); + response.append("\r\n"); + } + reader.close(); + + String result = response.toString().trim(); + + if (!result.contains("http://")) { + url = "Failed to post. Check report.txt"; + } else { + url = result.trim(); + } + } else { + url = "Failed to post. Check report.txt"; + } + } catch (Exception e) { + url = "Failed to post. Check report.txt"; + } + } + } diff --git a/src/main/java/net/h31ix/anticheat/util/Permission.java b/src/main/java/net/h31ix/anticheat/util/Permission.java index 56eddfe..81ebd50 100644 --- a/src/main/java/net/h31ix/anticheat/util/Permission.java +++ b/src/main/java/net/h31ix/anticheat/util/Permission.java @@ -20,57 +20,54 @@ package net.h31ix.anticheat.util; import org.bukkit.command.CommandSender; -public enum Permission -{ - /* Check Nodes */ - CHECK_ZOMBE_FLY, - CHECK_ZOMBE_NOCLIP, - CHECK_ZOMBE_CHEAT, - CHECK_FLY, - CHECK_WATERWALK, - CHECK_NOSWING, - CHECK_FASTBREAK, - CHECK_FASTPLACE, - CHECK_SPAM, - CHECK_SPRINT, - CHECK_SNEAK, - CHECK_SPEED, - CHECK_VCLIP, - CHECK_SPIDER, - CHECK_NOFALL, - CHECK_FASTBOW, - CHECK_FASTEAT, - CHECK_FASTHEAL, - CHECK_FORCEFIELD, - CHECK_XRAY, - CHECK_LONGREACH, - CHECK_FASTPROJECTILE, - CHECK_ITEMSPAM, - CHECK_VISUAL, - CHECK_FASTINVENTORY, - CHECK_AUTOTOOL, - - /* System Nodes */ - SYSTEM_LOG, - SYSTEM_XRAY, - SYSTEM_RESET, - SYSTEM_SPY, - SYSTEM_HELP, - SYSTEM_UPDATE, - SYSTEM_REPORT, - SYSTEM_ALERT, - SYSTEM_CALIBRATE, - SYSTEM_RELOAD; - - public boolean get(CommandSender cs) - { - return cs.hasPermission(toString()); - } - - @Override - public String toString() - { - return "anticheat." + this.name().toLowerCase().replace("_", "."); - } - +public enum Permission { + /* Check Nodes */ + CHECK_ZOMBE_FLY, + CHECK_ZOMBE_NOCLIP, + CHECK_ZOMBE_CHEAT, + CHECK_FLY, + CHECK_WATERWALK, + CHECK_NOSWING, + CHECK_FASTBREAK, + CHECK_FASTPLACE, + CHECK_SPAM, + CHECK_SPRINT, + CHECK_SNEAK, + CHECK_SPEED, + CHECK_VCLIP, + CHECK_SPIDER, + CHECK_NOFALL, + CHECK_FASTBOW, + CHECK_FASTEAT, + CHECK_FASTHEAL, + CHECK_FORCEFIELD, + CHECK_XRAY, + CHECK_LONGREACH, + CHECK_FASTPROJECTILE, + CHECK_ITEMSPAM, + CHECK_VISUAL, + CHECK_FASTINVENTORY, + CHECK_AUTOTOOL, + + /* System Nodes */ + SYSTEM_LOG, + SYSTEM_XRAY, + SYSTEM_RESET, + SYSTEM_SPY, + SYSTEM_HELP, + SYSTEM_UPDATE, + SYSTEM_REPORT, + SYSTEM_ALERT, + SYSTEM_CALIBRATE, + SYSTEM_RELOAD; + + public boolean get(CommandSender cs) { + return cs.hasPermission(toString()); + } + + @Override + public String toString() { + return "anticheat." + this.name().toLowerCase().replace("_", "."); + } + } diff --git a/src/main/java/net/h31ix/anticheat/util/SpyState.java b/src/main/java/net/h31ix/anticheat/util/SpyState.java index cb62aca..983edad 100644 --- a/src/main/java/net/h31ix/anticheat/util/SpyState.java +++ b/src/main/java/net/h31ix/anticheat/util/SpyState.java @@ -20,31 +20,26 @@ package net.h31ix.anticheat.util; import org.bukkit.Location; -public class SpyState -{ - private boolean allowFlight; - private boolean flying; - private Location location; - - public SpyState(boolean allowFlight, boolean flying, Location location) - { - this.allowFlight = allowFlight; - this.flying = flying; - this.location = location; - } - - public boolean getAllowFlight() - { - return this.allowFlight; - } - - public boolean getFlying() - { - return this.flying; - } - - public Location getLocation() - { - return this.location; - } +public class SpyState { + private boolean allowFlight; + private boolean flying; + private Location location; + + public SpyState(boolean allowFlight, boolean flying, Location location) { + this.allowFlight = allowFlight; + this.flying = flying; + this.location = location; + } + + public boolean getAllowFlight() { + return this.allowFlight; + } + + public boolean getFlying() { + return this.flying; + } + + public Location getLocation() { + return this.location; + } } diff --git a/src/main/java/net/h31ix/anticheat/util/ToolHardness.java b/src/main/java/net/h31ix/anticheat/util/ToolHardness.java index d7ee324..722470b 100644 --- a/src/main/java/net/h31ix/anticheat/util/ToolHardness.java +++ b/src/main/java/net/h31ix/anticheat/util/ToolHardness.java @@ -2,34 +2,27 @@ package net.h31ix.anticheat.util; import org.bukkit.Material; -public enum ToolHardness -{ - - //NOTHING(null, 1.5) - WOOD(0.75D), - STONE(0.40D), - IRON(0.25D), - DIAMOND(0.20D), - SHEARS(0.55D), - GOLD(0.15D); - - double hardness; - - ToolHardness(double hard) - { - hardness = hard; - } - - public static double getToolHardness(Material tool) - { - for (ToolHardness e : ToolHardness.values()) - { - if (tool.name().contains(e.name())) - { - return e.hardness; - } - } - - return 1.50D; - } +public enum ToolHardness { + + // NOTHING(null, 1.5) + WOOD(0.75D), + STONE(0.40D), + IRON(0.25D), + DIAMOND(0.20D), + SHEARS(0.55D), + GOLD(0.15D); + + double hardness; + + ToolHardness(double hard) { + hardness = hard; + } + + public static double getToolHardness(Material tool) { + for (ToolHardness e : ToolHardness.values()) { + if (tool.name().contains(e.name())) { return e.hardness; } + } + + return 1.50D; + } } diff --git a/src/main/java/net/h31ix/anticheat/util/Utilities.java b/src/main/java/net/h31ix/anticheat/util/Utilities.java index b9deb3d..ee45247 100644 --- a/src/main/java/net/h31ix/anticheat/util/Utilities.java +++ b/src/main/java/net/h31ix/anticheat/util/Utilities.java @@ -31,248 +31,205 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.util.NumberConversions; -public final class Utilities -{ - private static final List INSTANT_BREAK = new ArrayList(); - private static final List FOOD = new ArrayList(); - private static final List INTERACTABLE = new ArrayList(); - private static final List AXES = new ArrayList(); - private static final List PICKAXES = new ArrayList(); - private static final List SHEARS = new ArrayList(); - private static final List SHOVELS = new ArrayList(); - private static final List ANY = new ArrayList(); - - public static void alert(List message) - { - for (Player player : Bukkit.getOnlinePlayers()) - { - if (Permission.SYSTEM_ALERT.get(player)) - { - for (String msg : message) - { - player.sendMessage(msg); - } - } - } - if (Anticheat.getManager().getConfiguration().logConsole()) - { - for (String msg : message) - { - Anticheat.getManager().log(msg); - } - } - if (Anticheat.getManager().getConfiguration().getFileLogLevel() != 0) - { - for (String msg : message) - { - Anticheat.getManager().log(msg, 1); - } - } - } - - public static boolean cantStandAt(Block block) - { - return !canStand(block) && cantStandClose(block) && cantStandFar(block); - } - - public static boolean cantStandAtExp(Location block) - { - // This is a experimental check for checking whether you can't stand at or whatever. - Block nblock = new Location(block.getWorld(), fixXAxis(block.getX()), block.getY() - 0.01D, block.getBlockZ()).getBlock(); - return cantStandAt(nblock); - } - - public static boolean cantStandClose(Block block) - { - return !canStand(block.getRelative(BlockFace.NORTH)) && !canStand(block.getRelative(BlockFace.EAST)) && !canStand(block.getRelative(BlockFace.SOUTH)) && !canStand(block.getRelative(BlockFace.WEST)); - } - - public static boolean cantStandFar(Block block) - { - return !canStand(block.getRelative(BlockFace.NORTH_WEST)) && !canStand(block.getRelative(BlockFace.NORTH_EAST)) && !canStand(block.getRelative(BlockFace.SOUTH_WEST)) && !canStand(block.getRelative(BlockFace.SOUTH_EAST)); - } - - public static boolean canStand(Block block) - { - return !(block.isLiquid() || block.getType() == Material.AIR); - } - - public static boolean isFullyInWater(Location player) - { - double touchedX = fixXAxis(player.getX()); - - // Yes, this doesn't make sense, but it's supposed to fix some false positives in water walk. - // Think of it as 2 negatives = a positive :) - if(!(new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() && !(new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()).getBlock()).isLiquid()) - { - return true; - } - - return (new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() && (new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()).getBlock()).isLiquid(); - } - - public static double fixXAxis(double x) - { - /* Really really really useful function for those who are on the edges of blocks */ - /* For Z axis, just use Math.round(xaxis); */ - double touchedX = x; - double rem = touchedX - Math.round(touchedX) + 0.01D; - if (rem < 0.30D) - { - touchedX = NumberConversions.floor(x) - 1; - } - return touchedX; - } - - public static boolean isHoveringOverWater(Location player, int blocks) - { - for(int i = player.getBlockY(); i > player.getBlockY() - blocks; i--) - { - Block newloc = (new Location(player.getWorld(), player.getBlockX(), i, player.getBlockZ())).getBlock(); - if(newloc.getTypeId() != 0 && newloc.isLiquid()) - return true; - else if (newloc.getTypeId() != 0) - return false; - } - - return false; - } - - public static boolean isHoveringOverWater(Location player) - { - return isHoveringOverWater(player, 25); - } - - public static boolean isInstantBreak(Material m) - { - return INSTANT_BREAK.contains(m); - } - - public static boolean isFood(Material m) - { - return FOOD.contains(m); - } - - public static boolean isSlab(Block block) - { - int id = block.getTypeId(); - return id == 43 || id == 44 || id == 125 || id == 126; - } - - public static boolean isStair(Block block) - { - int id = block.getTypeId(); - return id == 53 || id == 67 || id == 108 || id == 109 || id == 114 || id == 128 || id == 134 || id == 135 || id == 136; - } - - public static boolean isInteractable(Material m) - { - return INTERACTABLE.contains(m); - } - - public static boolean sprintFly(Player player) - { - return player.isSprinting() || player.isFlying(); - } - - public static boolean isOnLilyPad(Player player) - { - Block block = player.getLocation().getBlock(); - Material lily = Material.WATER_LILY; - return block.getType() == lily || block.getRelative(BlockFace.NORTH).getType() == lily || block.getRelative(BlockFace.SOUTH).getType() == lily || block.getRelative(BlockFace.EAST).getType() == lily || block.getRelative(BlockFace.WEST).getType() == lily; - } - - public static boolean isSubmersed(Player player) - { - return player.getLocation().getBlock().isLiquid() && player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); - } - - public static boolean isInWater(Player player) - { - return player.getLocation().getBlock().isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.DOWN).isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); - } - - public static boolean isClimbableBlock(Block block) - { - return block.getType() == Material.VINE || block.getType() == Material.LADDER; - } - - public static boolean isOnVine(Player player) - { - return player.getLocation().getBlock().getType() == Material.VINE; - } - - public static boolean isInt(String string) - { - boolean x = false; - try - { - Integer.parseInt(string); - x = true; - } - catch (Exception ex) - { - } - return x; - } - - public static long calcSurvivalFastBreak(ItemStack tool, Material block) - { - double bhardness = BlockHardness.getBlockHardness(block); - double thardness = ToolHardness.getToolHardness(tool.getType()); - - long result = (long) ((long) Math.round((bhardness * thardness) * 0.10 * 10000)); - result += 150; - - if (result > 25000) - result = 25000; - else if (result < 0) - result = 0; - - return result; - } - - static - { - INSTANT_BREAK.add(Material.RED_MUSHROOM); - INSTANT_BREAK.add(Material.RED_ROSE); - INSTANT_BREAK.add(Material.BROWN_MUSHROOM); - INSTANT_BREAK.add(Material.YELLOW_FLOWER); - INSTANT_BREAK.add(Material.REDSTONE); - INSTANT_BREAK.add(Material.REDSTONE_TORCH_OFF); - INSTANT_BREAK.add(Material.REDSTONE_TORCH_ON); - INSTANT_BREAK.add(Material.REDSTONE_WIRE); - INSTANT_BREAK.add(Material.LONG_GRASS); - INSTANT_BREAK.add(Material.PAINTING); - INSTANT_BREAK.add(Material.WHEAT); - INSTANT_BREAK.add(Material.SUGAR_CANE); - INSTANT_BREAK.add(Material.SUGAR_CANE_BLOCK); - INSTANT_BREAK.add(Material.DIODE); - INSTANT_BREAK.add(Material.DIODE_BLOCK_OFF); - INSTANT_BREAK.add(Material.DIODE_BLOCK_ON); - INSTANT_BREAK.add(Material.SAPLING); - INSTANT_BREAK.add(Material.TORCH); - INSTANT_BREAK.add(Material.CROPS); - INSTANT_BREAK.add(Material.SNOW); - INSTANT_BREAK.add(Material.TNT); - INTERACTABLE.add(Material.STONE_BUTTON); - INTERACTABLE.add(Material.LEVER); - INTERACTABLE.add(Material.CHEST); - FOOD.add(Material.COOKED_BEEF); - FOOD.add(Material.COOKED_CHICKEN); - FOOD.add(Material.COOKED_FISH); - FOOD.add(Material.GRILLED_PORK); - FOOD.add(Material.PORK); - FOOD.add(Material.MUSHROOM_SOUP); - FOOD.add(Material.RAW_BEEF); - FOOD.add(Material.RAW_CHICKEN); - FOOD.add(Material.RAW_FISH); - FOOD.add(Material.APPLE); - FOOD.add(Material.GOLDEN_APPLE); - FOOD.add(Material.MELON); - FOOD.add(Material.COOKIE); - FOOD.add(Material.BREAD); - FOOD.add(Material.SPIDER_EYE); - FOOD.add(Material.ROTTEN_FLESH); - } +public final class Utilities { + private static final List INSTANT_BREAK = new ArrayList(); + private static final List FOOD = new ArrayList(); + private static final List INTERACTABLE = new ArrayList(); + private static final List AXES = new ArrayList(); + private static final List PICKAXES = new ArrayList(); + private static final List SHEARS = new ArrayList(); + private static final List SHOVELS = new ArrayList(); + private static final List ANY = new ArrayList(); + + public static void alert(List message) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (Permission.SYSTEM_ALERT.get(player)) { + for (String msg : message) { + player.sendMessage(msg); + } + } + } + if (Anticheat.getManager().getConfiguration().logConsole()) { + for (String msg : message) { + Anticheat.getManager().log(msg); + } + } + if (Anticheat.getManager().getConfiguration().getFileLogLevel() != 0) { + for (String msg : message) { + Anticheat.getManager().log(msg, 1); + } + } + } + + public static boolean cantStandAt(Block block) { + return !canStand(block) && cantStandClose(block) && cantStandFar(block); + } + + public static boolean cantStandAtExp(Location block) { + // This is a experimental check for checking whether you can't stand at or whatever. + Block nblock = new Location(block.getWorld(), fixXAxis(block.getX()), block.getY() - 0.01D, block.getBlockZ()).getBlock(); + return cantStandAt(nblock); + } + + public static boolean cantStandClose(Block block) { + return !canStand(block.getRelative(BlockFace.NORTH)) && !canStand(block.getRelative(BlockFace.EAST)) && !canStand(block.getRelative(BlockFace.SOUTH)) && !canStand(block.getRelative(BlockFace.WEST)); + } + + public static boolean cantStandFar(Block block) { + return !canStand(block.getRelative(BlockFace.NORTH_WEST)) && !canStand(block.getRelative(BlockFace.NORTH_EAST)) && !canStand(block.getRelative(BlockFace.SOUTH_WEST)) && !canStand(block.getRelative(BlockFace.SOUTH_EAST)); + } + + public static boolean canStand(Block block) { + return !(block.isLiquid() || block.getType() == Material.AIR); + } + + public static boolean isFullyInWater(Location player) { + double touchedX = fixXAxis(player.getX()); + + // Yes, this doesn't make sense, but it's supposed to fix some false positives in water walk. + // Think of it as 2 negatives = a positive :) + if (!(new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() && !(new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()).getBlock()).isLiquid()) { return true; } + + return (new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() && (new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()).getBlock()).isLiquid(); + } + + public static double fixXAxis(double x) { + /* Really really really useful function for those who are on the edges of blocks */ + /* For Z axis, just use Math.round(xaxis); */ + double touchedX = x; + double rem = touchedX - Math.round(touchedX) + 0.01D; + if (rem < 0.30D) { + touchedX = NumberConversions.floor(x) - 1; + } + return touchedX; + } + + public static boolean isHoveringOverWater(Location player, int blocks) { + for (int i = player.getBlockY(); i > player.getBlockY() - blocks; i--) { + Block newloc = (new Location(player.getWorld(), player.getBlockX(), i, player.getBlockZ())).getBlock(); + if (newloc.getTypeId() != 0 && newloc.isLiquid()) + return true; + else if (newloc.getTypeId() != 0) return false; + } + + return false; + } + + public static boolean isHoveringOverWater(Location player) { + return isHoveringOverWater(player, 25); + } + + public static boolean isInstantBreak(Material m) { + return INSTANT_BREAK.contains(m); + } + + public static boolean isFood(Material m) { + return FOOD.contains(m); + } + + public static boolean isSlab(Block block) { + int id = block.getTypeId(); + return id == 43 || id == 44 || id == 125 || id == 126; + } + + public static boolean isStair(Block block) { + int id = block.getTypeId(); + return id == 53 || id == 67 || id == 108 || id == 109 || id == 114 || id == 128 || id == 134 || id == 135 || id == 136; + } + + public static boolean isInteractable(Material m) { + return INTERACTABLE.contains(m); + } + + public static boolean sprintFly(Player player) { + return player.isSprinting() || player.isFlying(); + } + + public static boolean isOnLilyPad(Player player) { + Block block = player.getLocation().getBlock(); + Material lily = Material.WATER_LILY; + return block.getType() == lily || block.getRelative(BlockFace.NORTH).getType() == lily || block.getRelative(BlockFace.SOUTH).getType() == lily || block.getRelative(BlockFace.EAST).getType() == lily || block.getRelative(BlockFace.WEST).getType() == lily; + } + + public static boolean isSubmersed(Player player) { + return player.getLocation().getBlock().isLiquid() && player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); + } + + public static boolean isInWater(Player player) { + return player.getLocation().getBlock().isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.DOWN).isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); + } + + public static boolean isClimbableBlock(Block block) { + return block.getType() == Material.VINE || block.getType() == Material.LADDER; + } + + public static boolean isOnVine(Player player) { + return player.getLocation().getBlock().getType() == Material.VINE; + } + + public static boolean isInt(String string) { + boolean x = false; + try { + Integer.parseInt(string); + x = true; + } catch (Exception ex) {} + return x; + } + + public static long calcSurvivalFastBreak(ItemStack tool, Material block) { + double bhardness = BlockHardness.getBlockHardness(block); + double thardness = ToolHardness.getToolHardness(tool.getType()); + + long result = (long) ((long) Math.round((bhardness * thardness) * 0.10 * 10000)); + result += 150; + + if (result > 25000) + result = 25000; + else if (result < 0) result = 0; + + return result; + } + + static { + INSTANT_BREAK.add(Material.RED_MUSHROOM); + INSTANT_BREAK.add(Material.RED_ROSE); + INSTANT_BREAK.add(Material.BROWN_MUSHROOM); + INSTANT_BREAK.add(Material.YELLOW_FLOWER); + INSTANT_BREAK.add(Material.REDSTONE); + INSTANT_BREAK.add(Material.REDSTONE_TORCH_OFF); + INSTANT_BREAK.add(Material.REDSTONE_TORCH_ON); + INSTANT_BREAK.add(Material.REDSTONE_WIRE); + INSTANT_BREAK.add(Material.LONG_GRASS); + INSTANT_BREAK.add(Material.PAINTING); + INSTANT_BREAK.add(Material.WHEAT); + INSTANT_BREAK.add(Material.SUGAR_CANE); + INSTANT_BREAK.add(Material.SUGAR_CANE_BLOCK); + INSTANT_BREAK.add(Material.DIODE); + INSTANT_BREAK.add(Material.DIODE_BLOCK_OFF); + INSTANT_BREAK.add(Material.DIODE_BLOCK_ON); + INSTANT_BREAK.add(Material.SAPLING); + INSTANT_BREAK.add(Material.TORCH); + INSTANT_BREAK.add(Material.CROPS); + INSTANT_BREAK.add(Material.SNOW); + INSTANT_BREAK.add(Material.TNT); + INTERACTABLE.add(Material.STONE_BUTTON); + INTERACTABLE.add(Material.LEVER); + INTERACTABLE.add(Material.CHEST); + FOOD.add(Material.COOKED_BEEF); + FOOD.add(Material.COOKED_CHICKEN); + FOOD.add(Material.COOKED_FISH); + FOOD.add(Material.GRILLED_PORK); + FOOD.add(Material.PORK); + FOOD.add(Material.MUSHROOM_SOUP); + FOOD.add(Material.RAW_BEEF); + FOOD.add(Material.RAW_CHICKEN); + FOOD.add(Material.RAW_FISH); + FOOD.add(Material.APPLE); + FOOD.add(Material.GOLDEN_APPLE); + FOOD.add(Material.MELON); + FOOD.add(Material.COOKIE); + FOOD.add(Material.BREAD); + FOOD.add(Material.SPIDER_EYE); + FOOD.add(Material.ROTTEN_FLESH); + } } diff --git a/src/main/java/net/h31ix/anticheat/util/yaml/CommentedConfiguration.java b/src/main/java/net/h31ix/anticheat/util/yaml/CommentedConfiguration.java index 4df0657..e2c898e 100644 --- a/src/main/java/net/h31ix/anticheat/util/yaml/CommentedConfiguration.java +++ b/src/main/java/net/h31ix/anticheat/util/yaml/CommentedConfiguration.java @@ -33,115 +33,105 @@ import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.representer.Representer; -public class CommentedConfiguration extends YamlConfiguration -{ - private Map comments = new HashMap(); - - private final DumperOptions yamlOptions = new DumperOptions(); - private final Representer yamlRepresenter = new YamlRepresenter(); - private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); - private String lastLine = null; - - public CommentedConfiguration() - { - // Val 1 = line comment should be under - // Val 2 = comment - comments.put("XRay:", " # Should AntiCheat use calculations to try and find xrayers?"); - comments.put("Log xray stats:", " # Should a warning be sent to admins when a person is found that could be xraying?"); - comments.put("Alert when xray is found:", " # Should players in creative mode be tracked for possible xray usage?"); - comments.put("Chat:", " # Should AntiCheat block players spamming messages in chat?"); - comments.put("Block chat spam:", " # Should AntiCheat block players spamming commands in chat?"); - comments.put("Block command spam:", " # Valid actions = NONE,KICK,BAN,COMMAND[command]"); - comments.put("Ban Action:", "# Events occur when a player's hack level changes. You may configure reactions to these events here."); - comments.put("# Events occur when a player's hack level changes. You may configure reactions to these events here.", "# Valid events = NONE,WARN,KICK,BAN,COMMAND[command]"); - comments.put("# Valid events = NONE,WARN,KICK,BAN,COMMAND[command]", "# Use commands like so: COMMAND[ban &player 30] or COMMAND[kick &player hacking] or COMMAND[jail &player 10]"); - comments.put("# Use commands like so: COMMAND[ban &player 30] or COMMAND[kick &player hacking] or COMMAND[jail &player 10]", "# &player will be replaced with player's name, and &world will be replaced with the player's world"); - comments.put("Level High:", " # How many warnings should the player get before entering medium?"); - comments.put("Medium threshold:", " # How many warnings should the player get before entering high?"); - comments.put("System:", " # Turning auto-update off is a _BAD_ idea. You will no longer be protected by the latest hacks/cheats if you do so, and will have to update manually."); - comments.put("# Turning auto-update off is a _BAD_ idea. You will no longer be protected by the latest hacks/cheats if you do so, and will have to update manually.", " # Should AntiCheat log ALL failed checks to console?"); - comments.put("Log to console:", " # Should AntiCheat log to files?"); - comments.put("# Should AntiCheat log to files?", " # 0 = off, 1 = log only when an event takes place, 2 = more detailed logs, 3 = most detailed logs"); - comments.put("File log level:", " # Should AntiCheat display extra debug information when starting?"); - comments.put("Verbose startup:", " # If silent mode is on, players will not be stopped when they try to hack, and AntiCheat will do everything possible to keep them unaware of their rising hack level."); - comments.put("# If silent mode is on, players will not be stopped when they try to hack, and AntiCheat will do everything possible to keep them unaware of their rising hack level.", " # However, alerts will still be sent to console and to admins online, and events will still take place."); - comments.put("Silent mode:", " # Should ops be exempt from all checks?"); - } - - @Override - public String saveToString() { - yamlOptions.setIndent(options().indent()); - yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - - String dump = yaml.dump(getValues(false)); - - if (dump.equals(BLANK_CONFIG)) { - dump = ""; - } else { - StringBuilder builder = new StringBuilder(); - String [] lines = dump.split("\n"); - int i =0; - - while(i < lines.length) { - if(containsLine(lines[i])) { - builder.append(lines[i]); - builder.append("\n"); - builder.append(getComment(lines[i])); - builder.append("\n"); - lastLine = getComment(getComment(lines[i])); - i++; - } else if(containsLine(lastLine)) { - builder.append(getComment(lastLine)); - builder.append("\n"); - lastLine = getComment(lastLine); - } else { - builder.append(lines[i]); - builder.append("\n"); - i++; - } - } - dump = "# AntiCheat configuration file\n# Please report any bugs: http://dev.bukkit.org/server-mods/anticheat/\n"+builder.toString(); - } - - return dump; - } - - private boolean containsLine(String line) - { - if(line != null) - { - for(String string : comments.keySet()) { - if(string.replaceAll(" ", "").split(":")[0].equalsIgnoreCase(line.replaceAll(" ", "").split(":")[0])) { - return true; - } - } - } - return false; - } - - private String getComment(String line) - { - for(String string : comments.keySet()) { - if(string.replaceAll(" ", "").split(":")[0].equalsIgnoreCase(line.replaceAll(" ", "").split(":")[0])) { - return comments.get(string); - } - } - return null; - } - - public static CommentedConfiguration loadConfig(File file) { - - CommentedConfiguration config = new CommentedConfiguration(); - try { - config.load(file); - } catch (FileNotFoundException ex) { - } catch (IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); - } catch (InvalidConfigurationException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file , ex); - } - - return config; - } +public class CommentedConfiguration extends YamlConfiguration { + private Map comments = new HashMap(); + + private final DumperOptions yamlOptions = new DumperOptions(); + private final Representer yamlRepresenter = new YamlRepresenter(); + private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); + private String lastLine = null; + + public CommentedConfiguration() { + // Val 1 = line comment should be under + // Val 2 = comment + comments.put("XRay:", " # Should AntiCheat use calculations to try and find xrayers?"); + comments.put("Log xray stats:", " # Should a warning be sent to admins when a person is found that could be xraying?"); + comments.put("Alert when xray is found:", " # Should players in creative mode be tracked for possible xray usage?"); + comments.put("Chat:", " # Should AntiCheat block players spamming messages in chat?"); + comments.put("Block chat spam:", " # Should AntiCheat block players spamming commands in chat?"); + comments.put("Block command spam:", " # Valid actions = NONE,KICK,BAN,COMMAND[command]"); + comments.put("Ban Action:", "# Events occur when a player's hack level changes. You may configure reactions to these events here."); + comments.put("# Events occur when a player's hack level changes. You may configure reactions to these events here.", "# Valid events = NONE,WARN,KICK,BAN,COMMAND[command]"); + comments.put("# Valid events = NONE,WARN,KICK,BAN,COMMAND[command]", "# Use commands like so: COMMAND[ban &player 30] or COMMAND[kick &player hacking] or COMMAND[jail &player 10]"); + comments.put("# Use commands like so: COMMAND[ban &player 30] or COMMAND[kick &player hacking] or COMMAND[jail &player 10]", "# &player will be replaced with player's name, and &world will be replaced with the player's world"); + comments.put("Level High:", " # How many warnings should the player get before entering medium?"); + comments.put("Medium threshold:", " # How many warnings should the player get before entering high?"); + comments.put("System:", " # Turning auto-update off is a _BAD_ idea. You will no longer be protected by the latest hacks/cheats if you do so, and will have to update manually."); + comments.put("# Turning auto-update off is a _BAD_ idea. You will no longer be protected by the latest hacks/cheats if you do so, and will have to update manually.", " # Should AntiCheat log ALL failed checks to console?"); + comments.put("Log to console:", " # Should AntiCheat log to files?"); + comments.put("# Should AntiCheat log to files?", " # 0 = off, 1 = log only when an event takes place, 2 = more detailed logs, 3 = most detailed logs"); + comments.put("File log level:", " # Should AntiCheat display extra debug information when starting?"); + comments.put("Verbose startup:", " # If silent mode is on, players will not be stopped when they try to hack, and AntiCheat will do everything possible to keep them unaware of their rising hack level."); + comments.put("# If silent mode is on, players will not be stopped when they try to hack, and AntiCheat will do everything possible to keep them unaware of their rising hack level.", " # However, alerts will still be sent to console and to admins online, and events will still take place."); + comments.put("Silent mode:", " # Should ops be exempt from all checks?"); + } + + @Override + public String saveToString() { + yamlOptions.setIndent(options().indent()); + yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + + String dump = yaml.dump(getValues(false)); + + if (dump.equals(BLANK_CONFIG)) { + dump = ""; + } else { + StringBuilder builder = new StringBuilder(); + String[] lines = dump.split("\n"); + int i = 0; + + while (i < lines.length) { + if (containsLine(lines[i])) { + builder.append(lines[i]); + builder.append("\n"); + builder.append(getComment(lines[i])); + builder.append("\n"); + lastLine = getComment(getComment(lines[i])); + i++; + } else if (containsLine(lastLine)) { + builder.append(getComment(lastLine)); + builder.append("\n"); + lastLine = getComment(lastLine); + } else { + builder.append(lines[i]); + builder.append("\n"); + i++; + } + } + dump = "# AntiCheat configuration file\n# Please report any bugs: http://dev.bukkit.org/server-mods/anticheat/\n" + builder.toString(); + } + + return dump; + } + + private boolean containsLine(String line) { + if (line != null) { + for (String string : comments.keySet()) { + if (string.replaceAll(" ", "").split(":")[0].equalsIgnoreCase(line.replaceAll(" ", "").split(":")[0])) { return true; } + } + } + return false; + } + + private String getComment(String line) { + for (String string : comments.keySet()) { + if (string.replaceAll(" ", "").split(":")[0].equalsIgnoreCase(line.replaceAll(" ", "").split(":")[0])) { return comments.get(string); } + } + return null; + } + + public static CommentedConfiguration loadConfig(File file) { + + CommentedConfiguration config = new CommentedConfiguration(); + try { + config.load(file); + } catch (FileNotFoundException ex) {} catch (IOException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); + } catch (InvalidConfigurationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); + } + + return config; + } } diff --git a/src/main/java/net/h31ix/anticheat/xray/XRayListener.java b/src/main/java/net/h31ix/anticheat/xray/XRayListener.java index 53e1360..267aa84 100644 --- a/src/main/java/net/h31ix/anticheat/xray/XRayListener.java +++ b/src/main/java/net/h31ix/anticheat/xray/XRayListener.java @@ -29,56 +29,36 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; -public class XRayListener implements Listener -{ - private XRayTracker tracker = Anticheat.getManager().getXRayTracker(); - private Configuration config = Anticheat.getManager().getConfiguration(); - private CheckManager checkManager = Anticheat.getManager().getCheckManager(); - - @EventHandler - public void onBlockBreak(BlockBreakEvent event) - { - if (config.logXRay()) - { - Player p = event.getPlayer(); - if(p.getGameMode() == GameMode.CREATIVE && !config.trackCreativeXRay()) - { - return; - } - String player = p.getName(); - if (checkManager.willCheck(p, CheckType.XRAY)) - { - Material m = event.getBlock().getType(); - if (m == Material.DIAMOND_ORE) - { - tracker.addDiamond(player); - } - else if (m == Material.IRON_ORE) - { - tracker.addIron(player); - } - else if (m == Material.GOLD_ORE) - { - tracker.addGold(player); - } - else if (m == Material.LAPIS_ORE) - { - tracker.addLapis(player); - } - else if (m == Material.REDSTONE_ORE) - { - tracker.addRedstone(player); - } - else if (m == Material.GOLD_ORE) - { - tracker.addGold(player); - } - else - { - tracker.addBlock(player); - } - tracker.addTotal(player); - } - } - } +public class XRayListener implements Listener { + private XRayTracker tracker = Anticheat.getManager().getXRayTracker(); + private Configuration config = Anticheat.getManager().getConfiguration(); + private CheckManager checkManager = Anticheat.getManager().getCheckManager(); + + @EventHandler + public void onBlockBreak(BlockBreakEvent event) { + if (config.logXRay()) { + Player p = event.getPlayer(); + if (p.getGameMode() == GameMode.CREATIVE && !config.trackCreativeXRay()) { return; } + String player = p.getName(); + if (checkManager.willCheck(p, CheckType.XRAY)) { + Material m = event.getBlock().getType(); + if (m == Material.DIAMOND_ORE) { + tracker.addDiamond(player); + } else if (m == Material.IRON_ORE) { + tracker.addIron(player); + } else if (m == Material.GOLD_ORE) { + tracker.addGold(player); + } else if (m == Material.LAPIS_ORE) { + tracker.addLapis(player); + } else if (m == Material.REDSTONE_ORE) { + tracker.addRedstone(player); + } else if (m == Material.GOLD_ORE) { + tracker.addGold(player); + } else { + tracker.addBlock(player); + } + tracker.addTotal(player); + } + } + } } diff --git a/src/main/java/net/h31ix/anticheat/xray/XRayStats.java b/src/main/java/net/h31ix/anticheat/xray/XRayStats.java index fe0ea1e..47f26e9 100644 --- a/src/main/java/net/h31ix/anticheat/xray/XRayStats.java +++ b/src/main/java/net/h31ix/anticheat/xray/XRayStats.java @@ -20,81 +20,65 @@ package net.h31ix.anticheat.xray; import java.util.Map; -public class XRayStats -{ - private static final int DIVISOR = 100; - private double t = 1; - private double d = 0; - private double g = 0; - private double i = 0; - private double l = 0; - private double r = 0; - private double o = 0; - - public XRayStats(String player, Map diamond, Map gold, Map iron, Map lapis, Map redstone, Map other, Map total) - { - if (total.get(player) != null) - { - t = total.get(player); - } - if (diamond.get(player) != null) - { - d = (diamond.get(player) / t) * DIVISOR; - } - if (gold.get(player) != null) - { - g = (gold.get(player) / t) * DIVISOR; - } - if (iron.get(player) != null) - { - i = (iron.get(player) / t) * DIVISOR; - } - if (lapis.get(player) != null) - { - l = (lapis.get(player) / t) * DIVISOR; - } - if (redstone.get(player) != null) - { - r = (redstone.get(player) / t) * DIVISOR; - } - if (other.get(player) != null) - { - o = (other.get(player) / t) * DIVISOR; - } - } - - public double getTotal() - { - return t; - } - - public double getDiamond() - { - return d; - } - - public double getGold() - { - return g; - } - - public double getIron() - { - return i; - } - - public double getLapis() - { - return l; - } - - public double getRedstone() - { - return r; - } - - public double getOther() - { - return o; - } +public class XRayStats { + private static final int DIVISOR = 100; + private double t = 1; + private double d = 0; + private double g = 0; + private double i = 0; + private double l = 0; + private double r = 0; + private double o = 0; + + public XRayStats(String player, Map diamond, Map gold, Map iron, Map lapis, Map redstone, Map other, Map total) { + if (total.get(player) != null) { + t = total.get(player); + } + if (diamond.get(player) != null) { + d = (diamond.get(player) / t) * DIVISOR; + } + if (gold.get(player) != null) { + g = (gold.get(player) / t) * DIVISOR; + } + if (iron.get(player) != null) { + i = (iron.get(player) / t) * DIVISOR; + } + if (lapis.get(player) != null) { + l = (lapis.get(player) / t) * DIVISOR; + } + if (redstone.get(player) != null) { + r = (redstone.get(player) / t) * DIVISOR; + } + if (other.get(player) != null) { + o = (other.get(player) / t) * DIVISOR; + } + } + + public double getTotal() { + return t; + } + + public double getDiamond() { + return d; + } + + public double getGold() { + return g; + } + + public double getIron() { + return i; + } + + public double getLapis() { + return l; + } + + public double getRedstone() { + return r; + } + + public double getOther() { + return o; + } } diff --git a/src/main/java/net/h31ix/anticheat/xray/XRayTracker.java b/src/main/java/net/h31ix/anticheat/xray/XRayTracker.java index c33984f..a820215 100644 --- a/src/main/java/net/h31ix/anticheat/xray/XRayTracker.java +++ b/src/main/java/net/h31ix/anticheat/xray/XRayTracker.java @@ -25,151 +25,127 @@ import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; -public class XRayTracker -{ - private Map diamond = new HashMap(); - private Map gold = new HashMap(); - private Map iron = new HashMap(); - private Map lapis = new HashMap(); - private Map redstone = new HashMap(); - private Map block = new HashMap(); - private Map totalblock = new HashMap(); - private List alerted = new ArrayList(); - private static final ChatColor GREEN = ChatColor.GREEN; - private static final ChatColor WHITE = ChatColor.WHITE; - private static final ChatColor RED = ChatColor.RED; - private static final ChatColor GRAY = ChatColor.GRAY; - private static final int RATIO_DIVISOR = 3; - private static final int POWER = 10; - private static final int MIN_BLOCK_COUNT = 100; - - public XRayTracker() - { - } - - public boolean sufficientData(String player) - { - return totalblock.get(player) != null && totalblock.get(player) >= MIN_BLOCK_COUNT; - } - - public void calculate(CommandSender cs, String player, double x, double b, String type) - { - ChatColor color = WHITE; - if (x >= b / RATIO_DIVISOR) - { - color = RED; - } - cs.sendMessage(GRAY + "Percent " + type + " ore: " + color + round(x) + "%"); - } - - public boolean calculate(String player, double x, double b) - { - return x >= b / RATIO_DIVISOR; - } - - public boolean hasAbnormal(String player) - { - XRayStats stats = new XRayStats(player, diamond, gold, iron, lapis, redstone, block, totalblock); - double total = stats.getOther(); - return calculate(player, stats.getDiamond(), total) || calculate(player, stats.getGold(), total) || calculate(player, stats.getIron(), total) || calculate(player, stats.getLapis(), total) || calculate(player, stats.getRedstone(), total); - } - - public boolean hasAlerted(String player) - { - return alerted.contains(player); - } - - public void logAlert(String player) - { - alerted.add(player); - } - - public void sendStats(CommandSender cs, String player) - { - getStats(cs, player); - } - - public void getStats(CommandSender cs, String player) - { - XRayStats stats = new XRayStats(player, diamond, gold, iron, lapis, redstone, block, totalblock); - double total = stats.getOther(); - cs.sendMessage("--------------------[" + GREEN + "X-Ray Stats" + WHITE + "]---------------------"); - cs.sendMessage(GRAY + "Player: " + WHITE + player); - cs.sendMessage(GRAY + "Total blocks broken: " + WHITE + stats.getTotal()); - calculate(cs, player, stats.getDiamond(), total, "diamond"); - calculate(cs, player, stats.getGold(), total, "gold"); - calculate(cs, player, stats.getIron(), total, "iron"); - calculate(cs, player, stats.getLapis(), total, "lapis"); - calculate(cs, player, stats.getRedstone(), total, "redstone"); - cs.sendMessage(GRAY + "Percent all other blocks: " + WHITE + round(stats.getOther()) + "%"); - cs.sendMessage("-----------------------------------------------------"); - } - - public void addDiamond(String player) - { - addOre(player, diamond); - } - - public void addGold(String player) - { - addOre(player, gold); - } - - public void addIron(String player) - { - addOre(player, iron); - } - - public void addLapis(String player) - { - addOre(player, lapis); - } - - public void addRedstone(String player) - { - addOre(player, redstone); - } - - public void addBlock(String player) - { - addOre(player, block); - } - - public void addTotal(String player) - { - addOre(player, totalblock); - } - - private void addOre(String player, Map map) - { - if (map.get(player) == null || map.get(player) == 0) - { - map.put(player, 1); - } - else - { - int playerLevel = map.get(player); - map.put(player, playerLevel + 1); - } - } - - private float round(double num) - { - double number = num; - float p = (float) Math.pow(POWER, 1); - number *= p; - float tmp = Math.round(number); - return (float) tmp / p; - } - - public void reset(String player) - { - totalblock.put(player, 1); - diamond.put(player, 0); - iron.put(player, 0); - gold.put(player, 0); - redstone.put(player, 0); - lapis.put(player, 0); - totalblock.put(player, 0); - } +public class XRayTracker { + private Map diamond = new HashMap(); + private Map gold = new HashMap(); + private Map iron = new HashMap(); + private Map lapis = new HashMap(); + private Map redstone = new HashMap(); + private Map block = new HashMap(); + private Map totalblock = new HashMap(); + private List alerted = new ArrayList(); + private static final ChatColor GREEN = ChatColor.GREEN; + private static final ChatColor WHITE = ChatColor.WHITE; + private static final ChatColor RED = ChatColor.RED; + private static final ChatColor GRAY = ChatColor.GRAY; + private static final int RATIO_DIVISOR = 3; + private static final int POWER = 10; + private static final int MIN_BLOCK_COUNT = 100; + + public XRayTracker() { + } + + public boolean sufficientData(String player) { + return totalblock.get(player) != null && totalblock.get(player) >= MIN_BLOCK_COUNT; + } + + public void calculate(CommandSender cs, String player, double x, double b, String type) { + ChatColor color = WHITE; + if (x >= b / RATIO_DIVISOR) { + color = RED; + } + cs.sendMessage(GRAY + "Percent " + type + " ore: " + color + round(x) + "%"); + } + + public boolean calculate(String player, double x, double b) { + return x >= b / RATIO_DIVISOR; + } + + public boolean hasAbnormal(String player) { + XRayStats stats = new XRayStats(player, diamond, gold, iron, lapis, redstone, block, totalblock); + double total = stats.getOther(); + return calculate(player, stats.getDiamond(), total) || calculate(player, stats.getGold(), total) || calculate(player, stats.getIron(), total) || calculate(player, stats.getLapis(), total) || calculate(player, stats.getRedstone(), total); + } + + public boolean hasAlerted(String player) { + return alerted.contains(player); + } + + public void logAlert(String player) { + alerted.add(player); + } + + public void sendStats(CommandSender cs, String player) { + getStats(cs, player); + } + + public void getStats(CommandSender cs, String player) { + XRayStats stats = new XRayStats(player, diamond, gold, iron, lapis, redstone, block, totalblock); + double total = stats.getOther(); + cs.sendMessage("--------------------[" + GREEN + "X-Ray Stats" + WHITE + "]---------------------"); + cs.sendMessage(GRAY + "Player: " + WHITE + player); + cs.sendMessage(GRAY + "Total blocks broken: " + WHITE + stats.getTotal()); + calculate(cs, player, stats.getDiamond(), total, "diamond"); + calculate(cs, player, stats.getGold(), total, "gold"); + calculate(cs, player, stats.getIron(), total, "iron"); + calculate(cs, player, stats.getLapis(), total, "lapis"); + calculate(cs, player, stats.getRedstone(), total, "redstone"); + cs.sendMessage(GRAY + "Percent all other blocks: " + WHITE + round(stats.getOther()) + "%"); + cs.sendMessage("-----------------------------------------------------"); + } + + public void addDiamond(String player) { + addOre(player, diamond); + } + + public void addGold(String player) { + addOre(player, gold); + } + + public void addIron(String player) { + addOre(player, iron); + } + + public void addLapis(String player) { + addOre(player, lapis); + } + + public void addRedstone(String player) { + addOre(player, redstone); + } + + public void addBlock(String player) { + addOre(player, block); + } + + public void addTotal(String player) { + addOre(player, totalblock); + } + + private void addOre(String player, Map map) { + if (map.get(player) == null || map.get(player) == 0) { + map.put(player, 1); + } else { + int playerLevel = map.get(player); + map.put(player, playerLevel + 1); + } + } + + private float round(double num) { + double number = num; + float p = (float) Math.pow(POWER, 1); + number *= p; + float tmp = Math.round(number); + return (float) tmp / p; + } + + public void reset(String player) { + totalblock.put(player, 1); + diamond.put(player, 0); + iron.put(player, 0); + gold.put(player, 0); + redstone.put(player, 0); + lapis.put(player, 0); + totalblock.put(player, 0); + } }