diff --git a/pom.xml b/pom.xml index 84ead7b..f864b6c 100644 --- a/pom.xml +++ b/pom.xml @@ -1,18 +1,21 @@ 4.0.0 - net.h31ix.anticheat + net.gravitydevelopment.anticheat AntiCheat - 1.5.9-DEV + 2.0-DEV AntiCheat http://gravitydevelopment.net + + ${project.version} + bukkit-repo http://repo.bukkit.org/content/repositories/public/ - comphenix-rep + comphenix-repo Comphenix Repository http://repo.comphenix.net/content/groups/public @@ -31,21 +34,6 @@ AntiCheat - - - . - true - ${basedir}/src/main/resources - - plugin.yml - config.yml - lang.yml - magic.yml - events.yml - enterprise.yml - - - org.apache.maven.wagon @@ -53,7 +41,26 @@ 2.2 + + + src/main/resources + true + + + + + jenkins + + + env.BUILD_NUMBER + + + + {project.version}-b${env.BUILD_NUMBER} + + + org.bukkit @@ -81,4 +88,5 @@ file:///var/lib/jenkins/repo + diff --git a/src/main/java/net/h31ix/anticheat/AntiCheat.java b/src/main/java/net/gravitydevelopment/anticheat/AntiCheat.java similarity index 93% rename from src/main/java/net/h31ix/anticheat/AntiCheat.java rename to src/main/java/net/gravitydevelopment/anticheat/AntiCheat.java index cb462a0..1ace007 100644 --- a/src/main/java/net/h31ix/anticheat/AntiCheat.java +++ b/src/main/java/net/gravitydevelopment/anticheat/AntiCheat.java @@ -16,18 +16,18 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat; +package net.gravitydevelopment.anticheat; import com.comphenix.protocol.ProtocolLibrary; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.event.*; -import net.h31ix.anticheat.manage.AnticheatManager; -import net.h31ix.anticheat.manage.PacketManager; -import net.h31ix.anticheat.manage.User; -import net.h31ix.anticheat.update.Updater; -import net.h31ix.anticheat.util.Utilities; -import net.h31ix.anticheat.xray.XRayListener; -import net.h31ix.anticheat.xray.XRayTracker; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.event.*; +import net.gravitydevelopment.anticheat.manage.AnticheatManager; +import net.gravitydevelopment.anticheat.manage.PacketManager; +import net.gravitydevelopment.anticheat.manage.User; +import net.gravitydevelopment.anticheat.update.Updater; +import net.gravitydevelopment.anticheat.util.Utilities; +import net.gravitydevelopment.anticheat.xray.XRayListener; +import net.gravitydevelopment.anticheat.xray.XRayTracker; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; diff --git a/src/main/java/net/h31ix/anticheat/CommandHandler.java b/src/main/java/net/gravitydevelopment/anticheat/CommandHandler.java similarity index 96% rename from src/main/java/net/h31ix/anticheat/CommandHandler.java rename to src/main/java/net/gravitydevelopment/anticheat/CommandHandler.java index 8efc0f1..dcc6c4d 100644 --- a/src/main/java/net/h31ix/anticheat/CommandHandler.java +++ b/src/main/java/net/gravitydevelopment/anticheat/CommandHandler.java @@ -1,489 +1,489 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat; - -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.manage.CheckType; -import net.h31ix.anticheat.manage.User; -import net.h31ix.anticheat.manage.UserManager; -import net.h31ix.anticheat.util.*; -import net.h31ix.anticheat.xray.XRayTracker; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Server; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.metadata.FixedMetadataValue; - -import java.util.ArrayList; -import java.util.List; - -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 (hasPermission(cs, Permission.SYSTEM_LOG)) { - if (args[1].equalsIgnoreCase("enable")) { - if (!CONFIG.getConfig().logToConsole.getValue()) { - CONFIG.getConfig().logToConsole.setValue(true); - cs.sendMessage(GREEN + "Console logging enabled."); - CONFIG.getConfig().reload(); - } else { - cs.sendMessage(GREEN + "Console logging is already enabled!"); - } - } else if (args[1].equalsIgnoreCase("disable")) { - if (CONFIG.getConfig().logToConsole.getValue()) { - CONFIG.getConfig().logToConsole.setValue(false); - cs.sendMessage(GREEN + "Console logging disabled."); - CONFIG.getConfig().reload(); - } else { - cs.sendMessage(GREEN + "Console logging is already disabled!"); - } - } else { - cs.sendMessage(RED + "Usage: /anticheat log [enable/disable]"); - } - } - } - - public void handleDebug(CommandSender cs) { - if (hasPermission(cs, Permission.SYSTEM_DEBUG)) { - cs.sendMessage(GRAY + "Please wait while I collect some data..."); - 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."); - } - } - - public void handleDebug(CommandSender cs, Player tp) { - if (hasPermission(cs, Permission.SYSTEM_REPORT)) { - cs.sendMessage(GRAY + "Please wait while I collect some data..."); - PastebinReport report = new PastebinReport(cs, tp); - cs.sendMessage(GREEN + "Debug information posted to: " + WHITE + report.getURL()); - cs.sendMessage(GREEN + "Please include this link when making bug reports."); - } - } - - public void handleXRay(CommandSender cs, String[] args) { - if (hasPermission(cs, Permission.SYSTEM_XRAY)) { - if (CONFIG.getConfig().logXRayStats.getValue()) { - 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."); - } - } - } - - public void handleReset(CommandSender cs, String[] args) { - if (hasPermission(cs, Permission.SYSTEM_RESET)) { - List list = SERVER.matchPlayer(args[1]); - if (list.size() == 1) { - Player player = list.get(0); - User user = USER_MANAGER.getUser(player.getName()); - if (user != null) { - user.resetLevel(); - XRAY_TRACKER.reset(player.getName()); - user.clearMessages(); - AntiCheat.getManager().getBackend().resetChatLevel(player); - cs.sendMessage(player.getName() + GREEN + " has been reset."); - } else { - - } - } 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."); - } - } - } - - public void handleSpy(CommandSender cs, String[] args) { - if (cs instanceof Player) { - if (hasPermission(cs, Permission.SYSTEM_SPY)) { - 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(Utilities.SPY_METADATA)) // Maintain ORIGINAL location and other data - { - SpyState state = new SpyState(sender.getAllowFlight(), sender.isFlying(), sender.getLocation()); - sender.setMetadata(Utilities.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(Utilities.SPY_METADATA)) { - SpyState state = ((SpyState) sender.getMetadata(Utilities.SPY_METADATA).get(0).value()); - sender.setAllowFlight(state.getAllowFlight()); - sender.setFlying(state.getFlying()); - sender.teleport(state.getLocation()); - sender.removeMetadata(Utilities.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(RED + "Sorry, but you can't spy on a player from the console."); - } - } - - public void handleHelp(CommandSender cs) { - if (hasPermission(cs, Permission.SYSTEM_HELP)) { - String base = "/AntiCheat "; - String[] lines = { - "log [Enable/Disable]" + WHITE + " - toggle logging", - "report [low/medium/high]" + WHITE + " - show users in groups", - "report [user]" + WHITE + " - get a player's cheat report", - "reload" + WHITE + " - reload AntiCheat configuration", - "reset [user]" + WHITE + " - reset user's hack level", - "xray [user]" + WHITE + " - check user's xray levels", - "spy [user]" + WHITE + " - spy on a user in secret", - "help" + WHITE + " - access this page", - "debug" + WHITE + " - post debug information", - "update" + WHITE + " - check update status", - }; - - cs.sendMessage("----------------------[" + GREEN + "AntiCheat" + WHITE + "]----------------------"); - for (String s : lines) { - cs.sendMessage(base + GREEN + s); - } - } - } - - public void handleUpdate(CommandSender cs) { - if (hasPermission(cs, Permission.SYSTEM_UPDATE)) { - 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.getConfig().autoUpdate.getValue()) { - 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!"); - } - } - } - - public void handleCalibrate(CommandSender cs) { - if (cs instanceof Player) { - if (hasPermission(cs, Permission.SYSTEM_CALIBRATE)) { - Calibrator c = new Calibrator((Player) cs); - SERVER.getPluginManager().registerEvents(c, AntiCheat.getPlugin()); - c.calibrate(); - } - } - } - - public void handleReport(CommandSender cs, String[] args) { - if (hasPermission(cs, Permission.SYSTEM_REPORT)) { - 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]); - } - } - } - } - } - - 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 (hasPermission(cs, Permission.SYSTEM_REPORT)) { - User user = AntiCheat.getManager().getUserManager().getUser(args[1]); - boolean cont = false; - if (user == null) { - if ((user = AntiCheat.getManager().getUserManager().getUser(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]); - } - } - } - } - - public void handleDeveloper(CommandSender cs) { - AntiCheat.setDeveloperMode(!AntiCheat.developerMode()); - cs.sendMessage(ChatColor.GREEN + "Developer mode " + (AntiCheat.developerMode() ? "ON" : "OFF")); - } - - public void sendPlayerReport(CommandSender cs, List types, User user, int page) { - String name = user.getName(); - int pages = (int) Math.ceil(((float) types.size()) / 6); - - Level level = user.getNamedLevel(); - String levelString = ChatColor.GREEN + "Low"; - - if (level != null) { - levelString = level.getColor() + level.getName(); - } - levelString += " (" + user.getLevel() + ")"; - - 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))); - 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 (hasPermission(cs, Permission.SYSTEM_RELOAD)) { - CONFIG.load(); - cs.sendMessage(GREEN + "AntiCheat configuration reloaded."); - } - } - - @Override - public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) { - if (args.length == 3) { - if (args[0].equalsIgnoreCase("report")) { - for (Level level : CONFIG.getEvents().getLevels()) { - if (args[1].equalsIgnoreCase(level.getName())) { - handleReport(cs, args); - return true; - } - } - 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("debug")) { - handleDebug(cs, Bukkit.getPlayer(args[1])); - } 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("developer")) { - handleDeveloper(cs); - } - /** - * else if (args[0].equalsIgnoreCase("calibrate")) { handleCalibrate(cs); } - */ - else { - cs.sendMessage(RED + "Unrecognized command."); - } - } else { - handleHelp(cs); // Handle no args as alias of 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 boolean hasPermission(CommandSender cs, Permission perm) { - if (perm.get(cs)) { - return true; - } else { - cs.sendMessage(PERMISSIONS_ERROR + " (" + WHITE + perm.toString() + RED + ")"); - return false; - } - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat; + +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.manage.CheckType; +import net.gravitydevelopment.anticheat.manage.User; +import net.gravitydevelopment.anticheat.manage.UserManager; +import net.gravitydevelopment.anticheat.util.*; +import net.gravitydevelopment.anticheat.xray.XRayTracker; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Server; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.metadata.FixedMetadataValue; + +import java.util.ArrayList; +import java.util.List; + +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 (hasPermission(cs, Permission.SYSTEM_LOG)) { + if (args[1].equalsIgnoreCase("enable")) { + if (!CONFIG.getConfig().logToConsole.getValue()) { + CONFIG.getConfig().logToConsole.setValue(true); + cs.sendMessage(GREEN + "Console logging enabled."); + CONFIG.getConfig().reload(); + } else { + cs.sendMessage(GREEN + "Console logging is already enabled!"); + } + } else if (args[1].equalsIgnoreCase("disable")) { + if (CONFIG.getConfig().logToConsole.getValue()) { + CONFIG.getConfig().logToConsole.setValue(false); + cs.sendMessage(GREEN + "Console logging disabled."); + CONFIG.getConfig().reload(); + } else { + cs.sendMessage(GREEN + "Console logging is already disabled!"); + } + } else { + cs.sendMessage(RED + "Usage: /anticheat log [enable/disable]"); + } + } + } + + public void handleDebug(CommandSender cs) { + if (hasPermission(cs, Permission.SYSTEM_DEBUG)) { + cs.sendMessage(GRAY + "Please wait while I collect some data..."); + 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."); + } + } + + public void handleDebug(CommandSender cs, Player tp) { + if (hasPermission(cs, Permission.SYSTEM_REPORT)) { + cs.sendMessage(GRAY + "Please wait while I collect some data..."); + PastebinReport report = new PastebinReport(cs, tp); + cs.sendMessage(GREEN + "Debug information posted to: " + WHITE + report.getURL()); + cs.sendMessage(GREEN + "Please include this link when making bug reports."); + } + } + + public void handleXRay(CommandSender cs, String[] args) { + if (hasPermission(cs, Permission.SYSTEM_XRAY)) { + if (CONFIG.getConfig().logXRayStats.getValue()) { + 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."); + } + } + } + + public void handleReset(CommandSender cs, String[] args) { + if (hasPermission(cs, Permission.SYSTEM_RESET)) { + List list = SERVER.matchPlayer(args[1]); + if (list.size() == 1) { + Player player = list.get(0); + User user = USER_MANAGER.getUser(player.getName()); + if (user != null) { + user.resetLevel(); + XRAY_TRACKER.reset(player.getName()); + user.clearMessages(); + AntiCheat.getManager().getBackend().resetChatLevel(player); + cs.sendMessage(player.getName() + GREEN + " has been reset."); + } else { + + } + } 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."); + } + } + } + + public void handleSpy(CommandSender cs, String[] args) { + if (cs instanceof Player) { + if (hasPermission(cs, Permission.SYSTEM_SPY)) { + 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(Utilities.SPY_METADATA)) // Maintain ORIGINAL location and other data + { + SpyState state = new SpyState(sender.getAllowFlight(), sender.isFlying(), sender.getLocation()); + sender.setMetadata(Utilities.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(Utilities.SPY_METADATA)) { + SpyState state = ((SpyState) sender.getMetadata(Utilities.SPY_METADATA).get(0).value()); + sender.setAllowFlight(state.getAllowFlight()); + sender.setFlying(state.getFlying()); + sender.teleport(state.getLocation()); + sender.removeMetadata(Utilities.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(RED + "Sorry, but you can't spy on a player from the console."); + } + } + + public void handleHelp(CommandSender cs) { + if (hasPermission(cs, Permission.SYSTEM_HELP)) { + String base = "/AntiCheat "; + String[] lines = { + "log [Enable/Disable]" + WHITE + " - toggle logging", + "report [low/medium/high]" + WHITE + " - show users in groups", + "report [user]" + WHITE + " - get a player's cheat report", + "reload" + WHITE + " - reload AntiCheat configuration", + "reset [user]" + WHITE + " - reset user's hack level", + "xray [user]" + WHITE + " - check user's xray levels", + "spy [user]" + WHITE + " - spy on a user in secret", + "help" + WHITE + " - access this page", + "debug" + WHITE + " - post debug information", + "update" + WHITE + " - check update status", + }; + + cs.sendMessage("----------------------[" + GREEN + "AntiCheat" + WHITE + "]----------------------"); + for (String s : lines) { + cs.sendMessage(base + GREEN + s); + } + } + } + + public void handleUpdate(CommandSender cs) { + if (hasPermission(cs, Permission.SYSTEM_UPDATE)) { + 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.getConfig().autoUpdate.getValue()) { + 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!"); + } + } + } + + public void handleCalibrate(CommandSender cs) { + if (cs instanceof Player) { + if (hasPermission(cs, Permission.SYSTEM_CALIBRATE)) { + Calibrator c = new Calibrator((Player) cs); + SERVER.getPluginManager().registerEvents(c, AntiCheat.getPlugin()); + c.calibrate(); + } + } + } + + public void handleReport(CommandSender cs, String[] args) { + if (hasPermission(cs, Permission.SYSTEM_REPORT)) { + 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]); + } + } + } + } + } + + 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 (hasPermission(cs, Permission.SYSTEM_REPORT)) { + User user = AntiCheat.getManager().getUserManager().getUser(args[1]); + boolean cont = false; + if (user == null) { + if ((user = AntiCheat.getManager().getUserManager().getUser(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]); + } + } + } + } + + public void handleDeveloper(CommandSender cs) { + AntiCheat.setDeveloperMode(!AntiCheat.developerMode()); + cs.sendMessage(ChatColor.GREEN + "Developer mode " + (AntiCheat.developerMode() ? "ON" : "OFF")); + } + + public void sendPlayerReport(CommandSender cs, List types, User user, int page) { + String name = user.getName(); + int pages = (int) Math.ceil(((float) types.size()) / 6); + + Level level = user.getNamedLevel(); + String levelString = ChatColor.GREEN + "Low"; + + if (level != null) { + levelString = level.getColor() + level.getName(); + } + levelString += " (" + user.getLevel() + ")"; + + 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))); + 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 (hasPermission(cs, Permission.SYSTEM_RELOAD)) { + CONFIG.load(); + cs.sendMessage(GREEN + "AntiCheat configuration reloaded."); + } + } + + @Override + public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) { + if (args.length == 3) { + if (args[0].equalsIgnoreCase("report")) { + for (Level level : CONFIG.getEvents().getLevels()) { + if (args[1].equalsIgnoreCase(level.getName())) { + handleReport(cs, args); + return true; + } + } + 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("debug")) { + handleDebug(cs, Bukkit.getPlayer(args[1])); + } 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("developer")) { + handleDeveloper(cs); + } + /** + * else if (args[0].equalsIgnoreCase("calibrate")) { handleCalibrate(cs); } + */ + else { + cs.sendMessage(RED + "Unrecognized command."); + } + } else { + handleHelp(cs); // Handle no args as alias of 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 boolean hasPermission(CommandSender cs, Permission perm) { + if (perm.get(cs)) { + return true; + } else { + cs.sendMessage(PERMISSIONS_ERROR + " (" + WHITE + perm.toString() + RED + ")"); + return false; + } + } +} diff --git a/src/main/java/net/h31ix/anticheat/api/AnticheatAPI.java b/src/main/java/net/gravitydevelopment/anticheat/api/AnticheatAPI.java similarity index 90% rename from src/main/java/net/h31ix/anticheat/api/AnticheatAPI.java rename to src/main/java/net/gravitydevelopment/anticheat/api/AnticheatAPI.java index cb142e6..0201eb8 100644 --- a/src/main/java/net/h31ix/anticheat/api/AnticheatAPI.java +++ b/src/main/java/net/gravitydevelopment/anticheat/api/AnticheatAPI.java @@ -1,156 +1,156 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.api; - -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.manage.AnticheatManager; -import net.h31ix.anticheat.manage.CheckManager; -import net.h31ix.anticheat.manage.CheckType; -import net.h31ix.anticheat.manage.UserManager; -import net.h31ix.anticheat.xray.XRayTracker; -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(); - return xtracker.sufficientData(name) && xtracker.hasAbnormal(name); - } - - // 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(); - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.api; + +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.manage.AnticheatManager; +import net.gravitydevelopment.anticheat.manage.CheckManager; +import net.gravitydevelopment.anticheat.manage.CheckType; +import net.gravitydevelopment.anticheat.manage.UserManager; +import net.gravitydevelopment.anticheat.xray.XRayTracker; +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(); + return xtracker.sufficientData(name) && xtracker.hasAbnormal(name); + } + + // 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/api/CheckFailEvent.java b/src/main/java/net/gravitydevelopment/anticheat/api/CheckFailEvent.java similarity index 74% rename from src/main/java/net/h31ix/anticheat/api/CheckFailEvent.java rename to src/main/java/net/gravitydevelopment/anticheat/api/CheckFailEvent.java index a51a035..22a0d41 100644 --- a/src/main/java/net/h31ix/anticheat/api/CheckFailEvent.java +++ b/src/main/java/net/gravitydevelopment/anticheat/api/CheckFailEvent.java @@ -16,10 +16,10 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.api; +package net.gravitydevelopment.anticheat.api; -import net.h31ix.anticheat.manage.CheckType; -import net.h31ix.anticheat.manage.User; +import net.gravitydevelopment.anticheat.manage.CheckType; +import net.gravitydevelopment.anticheat.manage.User; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; @@ -40,18 +40,18 @@ public class CheckFailEvent extends Event { } /** - * Get the {@link net.h31ix.anticheat.manage.User} who failed the check + * Get the {@link net.gravitydevelopment.anticheat.manage.User} who failed the check * - * @return a {@link net.h31ix.anticheat.manage.User} + * @return a {@link net.gravitydevelopment.anticheat.manage.User} */ public User getUser() { return user; } /** - * Get the {@link net.h31ix.anticheat.manage.CheckType} failed + * Get the {@link net.gravitydevelopment.anticheat.manage.CheckType} failed * - * @return a {@link net.h31ix.anticheat.manage.CheckType} + * @return a {@link net.gravitydevelopment.anticheat.manage.CheckType} */ public CheckType getCheck() { return type; diff --git a/src/main/java/net/h31ix/anticheat/config/Configuration.java b/src/main/java/net/gravitydevelopment/anticheat/config/Configuration.java similarity index 78% rename from src/main/java/net/h31ix/anticheat/config/Configuration.java rename to src/main/java/net/gravitydevelopment/anticheat/config/Configuration.java index 0bca6b4..461ddbb 100644 --- a/src/main/java/net/h31ix/anticheat/config/Configuration.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/Configuration.java @@ -16,22 +16,22 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config; +package net.gravitydevelopment.anticheat.config; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.files.Config; -import net.h31ix.anticheat.config.files.Enterprise; -import net.h31ix.anticheat.config.files.Lang; -import net.h31ix.anticheat.config.files.Magic; -import net.h31ix.anticheat.config.holders.mysql.MySQLEventsHolder; -import net.h31ix.anticheat.config.holders.mysql.MySQLLevelsHolder; -import net.h31ix.anticheat.config.holders.mysql.MySQLRulesHolder; -import net.h31ix.anticheat.config.holders.yaml.YamlEventsHolder; -import net.h31ix.anticheat.config.holders.yaml.YamlLevelsHolder; -import net.h31ix.anticheat.config.holders.yaml.YamlRulesHolder; -import net.h31ix.anticheat.config.providers.Events; -import net.h31ix.anticheat.config.providers.Levels; -import net.h31ix.anticheat.config.providers.Rules; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.files.Config; +import net.gravitydevelopment.anticheat.config.files.Enterprise; +import net.gravitydevelopment.anticheat.config.files.Lang; +import net.gravitydevelopment.anticheat.config.files.Magic; +import net.gravitydevelopment.anticheat.config.holders.mysql.MySQLEventsHolder; +import net.gravitydevelopment.anticheat.config.holders.mysql.MySQLLevelsHolder; +import net.gravitydevelopment.anticheat.config.holders.mysql.MySQLRulesHolder; +import net.gravitydevelopment.anticheat.config.holders.yaml.YamlEventsHolder; +import net.gravitydevelopment.anticheat.config.holders.yaml.YamlLevelsHolder; +import net.gravitydevelopment.anticheat.config.holders.yaml.YamlRulesHolder; +import net.gravitydevelopment.anticheat.config.providers.Events; +import net.gravitydevelopment.anticheat.config.providers.Levels; +import net.gravitydevelopment.anticheat.config.providers.Rules; import java.util.ArrayList; diff --git a/src/main/java/net/h31ix/anticheat/config/ConfigurationFile.java b/src/main/java/net/gravitydevelopment/anticheat/config/ConfigurationFile.java similarity index 96% rename from src/main/java/net/h31ix/anticheat/config/ConfigurationFile.java rename to src/main/java/net/gravitydevelopment/anticheat/config/ConfigurationFile.java index 42749ad..9a763c7 100644 --- a/src/main/java/net/h31ix/anticheat/config/ConfigurationFile.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/ConfigurationFile.java @@ -16,10 +16,10 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config; +package net.gravitydevelopment.anticheat.config; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.yaml.CommentedConfiguration; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.yaml.CommentedConfiguration; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; diff --git a/src/main/java/net/h31ix/anticheat/config/ConfigurationTable.java b/src/main/java/net/gravitydevelopment/anticheat/config/ConfigurationTable.java similarity index 93% rename from src/main/java/net/h31ix/anticheat/config/ConfigurationTable.java rename to src/main/java/net/gravitydevelopment/anticheat/config/ConfigurationTable.java index 3973be9..d4b722c 100644 --- a/src/main/java/net/h31ix/anticheat/config/ConfigurationTable.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/ConfigurationTable.java @@ -16,9 +16,9 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config; +package net.gravitydevelopment.anticheat.config; -import net.h31ix.anticheat.util.enterprise.Database; +import net.gravitydevelopment.anticheat.util.enterprise.Database; import java.sql.Connection; diff --git a/src/main/java/net/h31ix/anticheat/config/files/Config.java b/src/main/java/net/gravitydevelopment/anticheat/config/files/Config.java similarity index 92% rename from src/main/java/net/h31ix/anticheat/config/files/Config.java rename to src/main/java/net/gravitydevelopment/anticheat/config/files/Config.java index 6d15701..dfed563 100644 --- a/src/main/java/net/h31ix/anticheat/config/files/Config.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/files/Config.java @@ -16,11 +16,11 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.files; +package net.gravitydevelopment.anticheat.config.files; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.config.ConfigurationFile; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.config.ConfigurationFile; import java.util.List; diff --git a/src/main/java/net/h31ix/anticheat/config/files/Enterprise.java b/src/main/java/net/gravitydevelopment/anticheat/config/files/Enterprise.java similarity index 91% rename from src/main/java/net/h31ix/anticheat/config/files/Enterprise.java rename to src/main/java/net/gravitydevelopment/anticheat/config/files/Enterprise.java index f7e8914..58d878d 100644 --- a/src/main/java/net/h31ix/anticheat/config/files/Enterprise.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/files/Enterprise.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.files; +package net.gravitydevelopment.anticheat.config.files; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.config.ConfigurationFile; -import net.h31ix.anticheat.util.enterprise.Database; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.config.ConfigurationFile; +import net.gravitydevelopment.anticheat.util.enterprise.Database; public class Enterprise extends ConfigurationFile { diff --git a/src/main/java/net/h31ix/anticheat/config/files/Lang.java b/src/main/java/net/gravitydevelopment/anticheat/config/files/Lang.java similarity index 90% rename from src/main/java/net/h31ix/anticheat/config/files/Lang.java rename to src/main/java/net/gravitydevelopment/anticheat/config/files/Lang.java index 7633a12..7795937 100644 --- a/src/main/java/net/h31ix/anticheat/config/files/Lang.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/files/Lang.java @@ -16,11 +16,11 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.files; +package net.gravitydevelopment.anticheat.config.files; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.config.ConfigurationFile; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.config.ConfigurationFile; import java.util.List; diff --git a/src/main/java/net/h31ix/anticheat/config/files/Magic.java b/src/main/java/net/gravitydevelopment/anticheat/config/files/Magic.java similarity index 98% rename from src/main/java/net/h31ix/anticheat/config/files/Magic.java rename to src/main/java/net/gravitydevelopment/anticheat/config/files/Magic.java index 80886d4..5705e4a 100644 --- a/src/main/java/net/h31ix/anticheat/config/files/Magic.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/files/Magic.java @@ -16,11 +16,11 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.files; +package net.gravitydevelopment.anticheat.config.files; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.config.ConfigurationFile; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.config.ConfigurationFile; /** * Magic number class. Modifications to values in magic.yml will be accepted here. diff --git a/src/main/java/net/h31ix/anticheat/config/holders/mysql/MySQLEventsHolder.java b/src/main/java/net/gravitydevelopment/anticheat/config/holders/mysql/MySQLEventsHolder.java similarity index 89% rename from src/main/java/net/h31ix/anticheat/config/holders/mysql/MySQLEventsHolder.java rename to src/main/java/net/gravitydevelopment/anticheat/config/holders/mysql/MySQLEventsHolder.java index 4d559d3..054f150 100644 --- a/src/main/java/net/h31ix/anticheat/config/holders/mysql/MySQLEventsHolder.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/holders/mysql/MySQLEventsHolder.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.holders.mysql; +package net.gravitydevelopment.anticheat.config.holders.mysql; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.config.ConfigurationTable; -import net.h31ix.anticheat.config.providers.Events; -import net.h31ix.anticheat.util.Level; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.config.ConfigurationTable; +import net.gravitydevelopment.anticheat.config.providers.Events; +import net.gravitydevelopment.anticheat.util.Level; import java.sql.ResultSet; import java.sql.SQLException; diff --git a/src/main/java/net/h31ix/anticheat/config/holders/mysql/MySQLLevelsHolder.java b/src/main/java/net/gravitydevelopment/anticheat/config/holders/mysql/MySQLLevelsHolder.java similarity index 93% rename from src/main/java/net/h31ix/anticheat/config/holders/mysql/MySQLLevelsHolder.java rename to src/main/java/net/gravitydevelopment/anticheat/config/holders/mysql/MySQLLevelsHolder.java index a810f08..c32c598 100644 --- a/src/main/java/net/h31ix/anticheat/config/holders/mysql/MySQLLevelsHolder.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/holders/mysql/MySQLLevelsHolder.java @@ -16,13 +16,13 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.holders.mysql; +package net.gravitydevelopment.anticheat.config.holders.mysql; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.config.ConfigurationTable; -import net.h31ix.anticheat.config.providers.Levels; -import net.h31ix.anticheat.manage.User; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.config.ConfigurationTable; +import net.gravitydevelopment.anticheat.config.providers.Levels; +import net.gravitydevelopment.anticheat.manage.User; import org.bukkit.Bukkit; import java.sql.PreparedStatement; diff --git a/src/main/java/net/h31ix/anticheat/config/holders/mysql/MySQLRulesHolder.java b/src/main/java/net/gravitydevelopment/anticheat/config/holders/mysql/MySQLRulesHolder.java similarity index 86% rename from src/main/java/net/h31ix/anticheat/config/holders/mysql/MySQLRulesHolder.java rename to src/main/java/net/gravitydevelopment/anticheat/config/holders/mysql/MySQLRulesHolder.java index 06b6e71..bfa6d41 100644 --- a/src/main/java/net/h31ix/anticheat/config/holders/mysql/MySQLRulesHolder.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/holders/mysql/MySQLRulesHolder.java @@ -16,13 +16,13 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.holders.mysql; +package net.gravitydevelopment.anticheat.config.holders.mysql; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.config.ConfigurationTable; -import net.h31ix.anticheat.config.providers.Rules; -import net.h31ix.anticheat.util.rule.Rule; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.config.ConfigurationTable; +import net.gravitydevelopment.anticheat.config.providers.Rules; +import net.gravitydevelopment.anticheat.util.rule.Rule; import java.sql.ResultSet; import java.sql.SQLException; diff --git a/src/main/java/net/h31ix/anticheat/config/holders/yaml/YamlEventsHolder.java b/src/main/java/net/gravitydevelopment/anticheat/config/holders/yaml/YamlEventsHolder.java similarity index 87% rename from src/main/java/net/h31ix/anticheat/config/holders/yaml/YamlEventsHolder.java rename to src/main/java/net/gravitydevelopment/anticheat/config/holders/yaml/YamlEventsHolder.java index 388814f..1070108 100644 --- a/src/main/java/net/h31ix/anticheat/config/holders/yaml/YamlEventsHolder.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/holders/yaml/YamlEventsHolder.java @@ -16,13 +16,13 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.holders.yaml; +package net.gravitydevelopment.anticheat.config.holders.yaml; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.config.ConfigurationFile; -import net.h31ix.anticheat.config.providers.Events; -import net.h31ix.anticheat.util.Level; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.config.ConfigurationFile; +import net.gravitydevelopment.anticheat.config.providers.Events; +import net.gravitydevelopment.anticheat.util.Level; import java.util.*; diff --git a/src/main/java/net/h31ix/anticheat/config/holders/yaml/YamlLevelsHolder.java b/src/main/java/net/gravitydevelopment/anticheat/config/holders/yaml/YamlLevelsHolder.java similarity index 84% rename from src/main/java/net/h31ix/anticheat/config/holders/yaml/YamlLevelsHolder.java rename to src/main/java/net/gravitydevelopment/anticheat/config/holders/yaml/YamlLevelsHolder.java index 3a155c2..e91949a 100644 --- a/src/main/java/net/h31ix/anticheat/config/holders/yaml/YamlLevelsHolder.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/holders/yaml/YamlLevelsHolder.java @@ -16,13 +16,13 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.holders.yaml; +package net.gravitydevelopment.anticheat.config.holders.yaml; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.config.ConfigurationFile; -import net.h31ix.anticheat.config.providers.Levels; -import net.h31ix.anticheat.manage.User; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.config.ConfigurationFile; +import net.gravitydevelopment.anticheat.config.providers.Levels; +import net.gravitydevelopment.anticheat.manage.User; import java.util.List; diff --git a/src/main/java/net/h31ix/anticheat/config/holders/yaml/YamlRulesHolder.java b/src/main/java/net/gravitydevelopment/anticheat/config/holders/yaml/YamlRulesHolder.java similarity index 84% rename from src/main/java/net/h31ix/anticheat/config/holders/yaml/YamlRulesHolder.java rename to src/main/java/net/gravitydevelopment/anticheat/config/holders/yaml/YamlRulesHolder.java index 5f000bf..136013a 100644 --- a/src/main/java/net/h31ix/anticheat/config/holders/yaml/YamlRulesHolder.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/holders/yaml/YamlRulesHolder.java @@ -16,13 +16,13 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.holders.yaml; +package net.gravitydevelopment.anticheat.config.holders.yaml; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.config.ConfigurationFile; -import net.h31ix.anticheat.config.providers.Rules; -import net.h31ix.anticheat.util.rule.Rule; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.config.ConfigurationFile; +import net.gravitydevelopment.anticheat.config.providers.Rules; +import net.gravitydevelopment.anticheat.util.rule.Rule; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/net/h31ix/anticheat/config/providers/Events.java b/src/main/java/net/gravitydevelopment/anticheat/config/providers/Events.java similarity index 88% rename from src/main/java/net/h31ix/anticheat/config/providers/Events.java rename to src/main/java/net/gravitydevelopment/anticheat/config/providers/Events.java index bd9ad0b..554333e 100644 --- a/src/main/java/net/h31ix/anticheat/config/providers/Events.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/providers/Events.java @@ -16,9 +16,9 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.providers; +package net.gravitydevelopment.anticheat.config.providers; -import net.h31ix.anticheat.util.Level; +import net.gravitydevelopment.anticheat.util.Level; import java.util.List; diff --git a/src/main/java/net/h31ix/anticheat/config/providers/Levels.java b/src/main/java/net/gravitydevelopment/anticheat/config/providers/Levels.java similarity index 89% rename from src/main/java/net/h31ix/anticheat/config/providers/Levels.java rename to src/main/java/net/gravitydevelopment/anticheat/config/providers/Levels.java index 6401151..cb9da53 100644 --- a/src/main/java/net/h31ix/anticheat/config/providers/Levels.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/providers/Levels.java @@ -16,9 +16,9 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.providers; +package net.gravitydevelopment.anticheat.config.providers; -import net.h31ix.anticheat.manage.User; +import net.gravitydevelopment.anticheat.manage.User; import java.util.List; diff --git a/src/main/java/net/h31ix/anticheat/config/providers/Rules.java b/src/main/java/net/gravitydevelopment/anticheat/config/providers/Rules.java similarity index 87% rename from src/main/java/net/h31ix/anticheat/config/providers/Rules.java rename to src/main/java/net/gravitydevelopment/anticheat/config/providers/Rules.java index 6ec8f15..3ae9274 100644 --- a/src/main/java/net/h31ix/anticheat/config/providers/Rules.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/providers/Rules.java @@ -17,9 +17,9 @@ */ -package net.h31ix.anticheat.config.providers; +package net.gravitydevelopment.anticheat.config.providers; -import net.h31ix.anticheat.util.rule.Rule; +import net.gravitydevelopment.anticheat.util.rule.Rule; import java.util.List; diff --git a/src/main/java/net/h31ix/anticheat/config/yaml/CommentedConfiguration.java b/src/main/java/net/gravitydevelopment/anticheat/config/yaml/CommentedConfiguration.java similarity index 99% rename from src/main/java/net/h31ix/anticheat/config/yaml/CommentedConfiguration.java rename to src/main/java/net/gravitydevelopment/anticheat/config/yaml/CommentedConfiguration.java index f66b3fb..68f1e26 100644 --- a/src/main/java/net/h31ix/anticheat/config/yaml/CommentedConfiguration.java +++ b/src/main/java/net/gravitydevelopment/anticheat/config/yaml/CommentedConfiguration.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.config.yaml; +package net.gravitydevelopment.anticheat.config.yaml; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; diff --git a/src/main/java/net/h31ix/anticheat/event/BlockListener.java b/src/main/java/net/gravitydevelopment/anticheat/event/BlockListener.java similarity index 92% rename from src/main/java/net/h31ix/anticheat/event/BlockListener.java rename to src/main/java/net/gravitydevelopment/anticheat/event/BlockListener.java index 99879e7..6ba5b07 100644 --- a/src/main/java/net/h31ix/anticheat/event/BlockListener.java +++ b/src/main/java/net/gravitydevelopment/anticheat/event/BlockListener.java @@ -1,108 +1,108 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.event; - -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.manage.CheckType; -import net.h31ix.anticheat.util.CheckResult; -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; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockDamageEvent; -import org.bukkit.event.block.BlockPlaceEvent; - -public class BlockListener extends EventListener { - - @EventHandler(priority = EventPriority.MONITOR) - public void onBlockDamage(BlockDamageEvent event) { - Player player = event.getPlayer(); - if (event.getInstaBreak() || Utilities.isInstantBreak(event.getBlock().getType())) { - getBackend().logInstantBreak(player); - } - if (getCheckManager().willCheck(player, CheckType.AUTOTOOL)) { - CheckResult result = getBackend().checkAutoTool(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.AUTOTOOL); - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - final Player player = event.getPlayer(); - if (player != null && getCheckManager().willCheck(player, CheckType.FAST_PLACE)) { - CheckResult result = getBackend().checkFastPlace(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_PLACE); - } else { - decrease(player); - getBackend().logBlockPlace(player); - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - final Player player = event.getPlayer(); - final Block block = event.getBlock(); - boolean noHack = true; - if (player != null) { - CheckResult result; - if (getCheckManager().willCheck(player, CheckType.FAST_BREAK)) { - result = getBackend().checkFastBreak(player, block); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_BREAK); - noHack = false; - } - } - if (getCheckManager().willCheck(player, CheckType.NO_SWING)) { - result = getBackend().checkSwing(player, block); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.NO_SWING); - noHack = false; - } - } - if (getCheckManager().willCheck(player, CheckType.LONG_REACH)) { - Distance distance = new Distance(player.getLocation(), block.getLocation()); - result = getBackend().checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference()); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.LONG_REACH); - noHack = false; - } - } - } - if (noHack) { - decrease(player); - } - getBackend().logBlockBreak(player); - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.event; + +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.manage.CheckType; +import net.gravitydevelopment.anticheat.util.CheckResult; +import net.gravitydevelopment.anticheat.util.Distance; +import net.gravitydevelopment.anticheat.util.Utilities; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockPlaceEvent; + +public class BlockListener extends EventListener { + + @EventHandler(priority = EventPriority.MONITOR) + public void onBlockDamage(BlockDamageEvent event) { + Player player = event.getPlayer(); + if (event.getInstaBreak() || Utilities.isInstantBreak(event.getBlock().getType())) { + getBackend().logInstantBreak(player); + } + if (getCheckManager().willCheck(player, CheckType.AUTOTOOL)) { + CheckResult result = getBackend().checkAutoTool(player); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.AUTOTOOL); + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler(ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + final Player player = event.getPlayer(); + if (player != null && getCheckManager().willCheck(player, CheckType.FAST_PLACE)) { + CheckResult result = getBackend().checkFastPlace(player); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.FAST_PLACE); + } else { + decrease(player); + getBackend().logBlockPlace(player); + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler(ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + final Player player = event.getPlayer(); + final Block block = event.getBlock(); + boolean noHack = true; + if (player != null) { + CheckResult result; + if (getCheckManager().willCheck(player, CheckType.FAST_BREAK)) { + result = getBackend().checkFastBreak(player, block); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.FAST_BREAK); + noHack = false; + } + } + if (getCheckManager().willCheck(player, CheckType.NO_SWING)) { + result = getBackend().checkSwing(player, block); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.NO_SWING); + noHack = false; + } + } + if (getCheckManager().willCheck(player, CheckType.LONG_REACH)) { + Distance distance = new Distance(player.getLocation(), block.getLocation()); + result = getBackend().checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference()); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.LONG_REACH); + noHack = false; + } + } + } + if (noHack) { + decrease(player); + } + getBackend().logBlockBreak(player); + } +} diff --git a/src/main/java/net/h31ix/anticheat/event/EntityListener.java b/src/main/java/net/gravitydevelopment/anticheat/event/EntityListener.java similarity index 94% rename from src/main/java/net/h31ix/anticheat/event/EntityListener.java rename to src/main/java/net/gravitydevelopment/anticheat/event/EntityListener.java index c14c860..04356cf 100644 --- a/src/main/java/net/h31ix/anticheat/event/EntityListener.java +++ b/src/main/java/net/gravitydevelopment/anticheat/event/EntityListener.java @@ -1,175 +1,175 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.event; - -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.manage.CheckType; -import net.h31ix.anticheat.util.CheckResult; -import net.h31ix.anticheat.util.Distance; -import net.h31ix.anticheat.util.Utilities; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Creeper; -import org.bukkit.entity.Player; -import org.bukkit.entity.TNTPrimed; -import org.bukkit.event.EventHandler; -import org.bukkit.event.entity.*; -import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; - -public class EntityListener extends EventListener { - - @EventHandler - public void onEntityShootBow(EntityShootBowEvent event) { - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (getCheckManager().willCheck(player, CheckType.FAST_BOW)) { - CheckResult result = getBackend().checkFastBow(player, event.getForce()); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_BOW); - } else { - decrease(player); - } - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onEntityRegainHealth(EntityRegainHealthEvent event) { - if (event.getEntity() instanceof Player && event.getRegainReason() == RegainReason.SATIATED) { - Player player = (Player) event.getEntity(); - if (getCheckManager().willCheck(player, CheckType.FAST_HEAL)) { - CheckResult result = getBackend().checkFastHeal(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_HEAL); - } else { - decrease(player); - getBackend().logHeal(player); - } - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onFoodLevelChange(FoodLevelChangeEvent event) { - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (player.getFoodLevel() < event.getFoodLevel() && getCheckManager().willCheck(player, CheckType.FAST_EAT)) // Make sure it's them actually gaining a food level - { - CheckResult result = getBackend().checkFastEat(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_EAT); - } else { - decrease(player); - } - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @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 (Utilities.hasArmorEnchantment(player, Enchantment.THORNS)) { - getBackend().logAnimation(player); - } - if (e.getDamager() instanceof Player) { - Player p = (Player) e.getDamager(); - getBackend().logDamage(p, 1); - int value = p.getInventory().getItemInHand().containsEnchantment(Enchantment.KNOCKBACK) ? 2 : 1; - getBackend().logDamage(player, value); - if (getCheckManager().willCheck(p, CheckType.LONG_REACH)) { - Distance distance = new Distance(player.getLocation(), p.getLocation()); - CheckResult result = getBackend().checkLongReachDamage(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference()); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), p, CheckType.LONG_REACH); - noHack = false; - } - } - } else { - if (e.getDamager() instanceof TNTPrimed || e.getDamager() instanceof Creeper) { - getBackend().logDamage(player, 3); - } else { - getBackend().logDamage(player, 1); - } - } - } - if (e.getDamager() instanceof Player) { - Player player = (Player) e.getDamager(); - getBackend().logDamage(player, 1); - if (getCheckManager().willCheck(player, CheckType.AUTOTOOL)) { - CheckResult result = getBackend().checkAutoTool(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.AUTOTOOL); - noHack = false; - } - } - if (getCheckManager().willCheck(player, CheckType.FORCEFIELD)) { - CheckResult result = getBackend().checkSprintDamage(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FORCEFIELD); - noHack = false; - } - } - if (getCheckManager().willCheck(player, CheckType.NO_SWING)) { - CheckResult result = getBackend().checkAnimation(player, event.getEntity()); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.NO_SWING); - noHack = false; - } - } - if (getCheckManager().willCheck(player, CheckType.FORCEFIELD)) { - CheckResult result = getBackend().checkSight(player, e.getEntity()); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FORCEFIELD); - noHack = false; - } - } - if (noHack) { - decrease(player); - } - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.event; + +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.manage.CheckType; +import net.gravitydevelopment.anticheat.util.CheckResult; +import net.gravitydevelopment.anticheat.util.Distance; +import net.gravitydevelopment.anticheat.util.Utilities; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Creeper; +import org.bukkit.entity.Player; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.*; +import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; + +public class EntityListener extends EventListener { + + @EventHandler + public void onEntityShootBow(EntityShootBowEvent event) { + if (event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + if (getCheckManager().willCheck(player, CheckType.FAST_BOW)) { + CheckResult result = getBackend().checkFastBow(player, event.getForce()); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.FAST_BOW); + } else { + decrease(player); + } + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onEntityRegainHealth(EntityRegainHealthEvent event) { + if (event.getEntity() instanceof Player && event.getRegainReason() == RegainReason.SATIATED) { + Player player = (Player) event.getEntity(); + if (getCheckManager().willCheck(player, CheckType.FAST_HEAL)) { + CheckResult result = getBackend().checkFastHeal(player); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.FAST_HEAL); + } else { + decrease(player); + getBackend().logHeal(player); + } + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onFoodLevelChange(FoodLevelChangeEvent event) { + if (event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + if (player.getFoodLevel() < event.getFoodLevel() && getCheckManager().willCheck(player, CheckType.FAST_EAT)) // Make sure it's them actually gaining a food level + { + CheckResult result = getBackend().checkFastEat(player); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.FAST_EAT); + } else { + decrease(player); + } + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @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 (Utilities.hasArmorEnchantment(player, Enchantment.THORNS)) { + getBackend().logAnimation(player); + } + if (e.getDamager() instanceof Player) { + Player p = (Player) e.getDamager(); + getBackend().logDamage(p, 1); + int value = p.getInventory().getItemInHand().containsEnchantment(Enchantment.KNOCKBACK) ? 2 : 1; + getBackend().logDamage(player, value); + if (getCheckManager().willCheck(p, CheckType.LONG_REACH)) { + Distance distance = new Distance(player.getLocation(), p.getLocation()); + CheckResult result = getBackend().checkLongReachDamage(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference()); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), p, CheckType.LONG_REACH); + noHack = false; + } + } + } else { + if (e.getDamager() instanceof TNTPrimed || e.getDamager() instanceof Creeper) { + getBackend().logDamage(player, 3); + } else { + getBackend().logDamage(player, 1); + } + } + } + if (e.getDamager() instanceof Player) { + Player player = (Player) e.getDamager(); + getBackend().logDamage(player, 1); + if (getCheckManager().willCheck(player, CheckType.AUTOTOOL)) { + CheckResult result = getBackend().checkAutoTool(player); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.AUTOTOOL); + noHack = false; + } + } + if (getCheckManager().willCheck(player, CheckType.FORCEFIELD)) { + CheckResult result = getBackend().checkSprintDamage(player); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.FORCEFIELD); + noHack = false; + } + } + if (getCheckManager().willCheck(player, CheckType.NO_SWING)) { + CheckResult result = getBackend().checkAnimation(player, event.getEntity()); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.NO_SWING); + noHack = false; + } + } + if (getCheckManager().willCheck(player, CheckType.FORCEFIELD)) { + CheckResult result = getBackend().checkSight(player, e.getEntity()); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.FORCEFIELD); + noHack = false; + } + } + if (noHack) { + decrease(player); + } + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } +} diff --git a/src/main/java/net/h31ix/anticheat/event/EventListener.java b/src/main/java/net/gravitydevelopment/anticheat/event/EventListener.java similarity index 93% rename from src/main/java/net/h31ix/anticheat/event/EventListener.java rename to src/main/java/net/gravitydevelopment/anticheat/event/EventListener.java index ab464c4..26f3c96 100644 --- a/src/main/java/net/h31ix/anticheat/event/EventListener.java +++ b/src/main/java/net/gravitydevelopment/anticheat/event/EventListener.java @@ -1,139 +1,139 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.event; - -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.manage.*; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; - -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -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(); - private static final Configuration CONFIG = AntiCheat.getManager().getConfiguration(); - - public static void log(String message, Player player, CheckType type) { - User user = getUserManager().getUser(player.getName()); - if (user != null) { // npc - logCheat(type, user); - if (user.increaseLevel(type) && message != null) { - AntiCheat.getManager().log(message); - } - removeDecrease(user); - } - } - - private static void logCheat(CheckType type, User user) { - USAGE_LIST.put(type, getCheats(type) + 1); - // Ignore plugins that are creating NPCs with no names (why the hell) - if (user != null && user.getName() != null) { - type.logUse(user); - if (CONFIG.getConfig().enterprise.getValue() && CONFIG.getEnterprise().loggingEnabled.getValue()) { - CONFIG.getEnterprise().database.logEvent(user, type); - } - if (CONFIG.getConfig().fileLogLevel.getValue() == 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 static Configuration getConfig() { - return CONFIG; - } - - public static boolean silentMode() { - return CONFIG.getConfig().silentMode.getValue(); - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.event; + +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.manage.*; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; + +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; + +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(); + private static final Configuration CONFIG = AntiCheat.getManager().getConfiguration(); + + public static void log(String message, Player player, CheckType type) { + User user = getUserManager().getUser(player.getName()); + if (user != null) { // npc + logCheat(type, user); + if (user.increaseLevel(type) && message != null) { + AntiCheat.getManager().log(message); + } + removeDecrease(user); + } + } + + private static void logCheat(CheckType type, User user) { + USAGE_LIST.put(type, getCheats(type) + 1); + // Ignore plugins that are creating NPCs with no names (why the hell) + if (user != null && user.getName() != null) { + type.logUse(user); + if (CONFIG.getConfig().enterprise.getValue() && CONFIG.getEnterprise().loggingEnabled.getValue()) { + CONFIG.getEnterprise().database.logEvent(user, type); + } + if (CONFIG.getConfig().fileLogLevel.getValue() == 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 static Configuration getConfig() { + return CONFIG; + } + + public static boolean silentMode() { + return CONFIG.getConfig().silentMode.getValue(); + } +} diff --git a/src/main/java/net/h31ix/anticheat/event/InventoryListener.java b/src/main/java/net/gravitydevelopment/anticheat/event/InventoryListener.java similarity index 90% rename from src/main/java/net/h31ix/anticheat/event/InventoryListener.java rename to src/main/java/net/gravitydevelopment/anticheat/event/InventoryListener.java index 1124cf3..64f9ee7 100644 --- a/src/main/java/net/h31ix/anticheat/event/InventoryListener.java +++ b/src/main/java/net/gravitydevelopment/anticheat/event/InventoryListener.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.event; +package net.gravitydevelopment.anticheat.event; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.manage.CheckType; -import net.h31ix.anticheat.manage.User; -import net.h31ix.anticheat.util.CheckResult; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.manage.CheckType; +import net.gravitydevelopment.anticheat.manage.User; +import net.gravitydevelopment.anticheat.util.CheckResult; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.inventory.InventoryClickEvent; diff --git a/src/main/java/net/h31ix/anticheat/event/PlayerListener.java b/src/main/java/net/gravitydevelopment/anticheat/event/PlayerListener.java similarity index 96% rename from src/main/java/net/h31ix/anticheat/event/PlayerListener.java rename to src/main/java/net/gravitydevelopment/anticheat/event/PlayerListener.java index 980e008..9382aa7 100644 --- a/src/main/java/net/h31ix/anticheat/event/PlayerListener.java +++ b/src/main/java/net/gravitydevelopment/anticheat/event/PlayerListener.java @@ -1,459 +1,459 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.event; - -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.manage.CheckType; -import net.h31ix.anticheat.manage.User; -import net.h31ix.anticheat.util.CheckResult; -import net.h31ix.anticheat.util.Distance; -import net.h31ix.anticheat.util.Permission; -import net.h31ix.anticheat.util.Utilities; -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.Action; -import org.bukkit.event.entity.ProjectileLaunchEvent; -import org.bukkit.event.player.*; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -import org.bukkit.inventory.PlayerInventory; - -public class PlayerListener extends EventListener { - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { - Player player = event.getPlayer(); - if (getCheckManager().willCheck(player, CheckType.SPAM) && getConfig().getConfig().blockCommandSpam.getValue()) { - CheckResult result = getBackend().checkSpam(player, event.getMessage()); - if (result.failed()) { - event.setCancelled(!silentMode()); - player.sendMessage(ChatColor.RED + result.getMessage()); - getBackend().processChatSpammer(player); - log(null, player, CheckType.SPAM); - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerToggleFlight(PlayerToggleFlightEvent event) { - if (!event.isFlying()) { - getBackend().logEnterExit(event.getPlayer()); - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) { - if (event.getNewGameMode() != GameMode.CREATIVE) { - getBackend().logEnterExit(event.getPlayer()); - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @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 (getCheckManager().willCheck(player, CheckType.FAST_PROJECTILE)) { - CheckResult result = getBackend().checkProjectile(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_PROJECTILE); - } - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerTeleport(PlayerTeleportEvent event) { - if (event.getCause() == TeleportCause.ENDER_PEARL || event.getCause() == TeleportCause.PLUGIN) { - getBackend().logTeleport(event.getPlayer()); - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerChangeWorlds(PlayerChangedWorldEvent event) { - getBackend().logTeleport(event.getPlayer()); - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerToggleSneak(PlayerToggleSneakEvent event) { - if (event.isSneaking()) { - getBackend().logToggleSneak(event.getPlayer()); - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerVelocity(PlayerVelocityEvent event) { - Player player = event.getPlayer(); - if (getCheckManager().willCheck(player, CheckType.FLY)) { - if (getBackend().justVelocity(player) && getBackend().extendVelocityTime(player)) { - event.setCancelled(!silentMode()); - return; // don't log it lol. - } - getBackend().logVelocity(player); - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerChat(AsyncPlayerChatEvent event) { - Player player = event.getPlayer(); - - if (getCheckManager().willCheck(player, CheckType.SPAM) && getConfig().getConfig().blockChatSpam.getValue()) { - CheckResult result = getBackend().checkSpam(player, event.getMessage()); - if (result.failed()) { - event.setCancelled(!silentMode()); - if (!result.getMessage().equals("")) { - player.sendMessage(ChatColor.RED + result.getMessage()); - } - getBackend().processChatSpammer(player); - log(null, player, CheckType.SPAM); - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerKick(PlayerKickEvent event) { - getBackend().clearChatLevel(event.getPlayer()); - getBackend().garbageClean(event.getPlayer()); - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { - getBackend().garbageClean(event.getPlayer()); - - User user = getUserManager().getUser(event.getPlayer().getName()); - - getConfig().getLevels().saveLevelFromUser(user); - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerToggleSprint(PlayerToggleSprintEvent event) { - Player player = event.getPlayer(); - if (!event.isSprinting()) { - getBackend().logEnterExit(player); - } - if (getCheckManager().willCheck(player, CheckType.SPRINT)) { - CheckResult result = getBackend().checkSprintHungry(event); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.SPRINT); - } else { - decrease(player); - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @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) { - getBackend().logBowWindUp(player); - } else if (Utilities.isFood(m)) { - getBackend().logEatingStart(player); - } - } - Block block = event.getClickedBlock(); - - if (block != null) { - Distance distance = new Distance(player.getLocation(), block.getLocation()); - getBackend().checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference()); - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerDropItem(PlayerDropItemEvent event) { - Player player = event.getPlayer(); - if (getCheckManager().willCheck(player, CheckType.ITEM_SPAM)) { - CheckResult result = getBackend().checkFastDrop(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.ITEM_SPAM); - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerEnterBed(PlayerBedEnterEvent event) { - if (event.getBed().getType() != Material.BED) return; - getBackend().logEnterExit(event.getPlayer()); - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerExitBed(PlayerBedLeaveEvent event) { - if (event.getBed().getType() != Material.BED) return; - getBackend().logEnterExit(event.getPlayer()); - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerAnimation(PlayerAnimationEvent event) { - Player player = event.getPlayer(); - if (getCheckManager().willCheck(player, CheckType.FAST_ANIMATION)) { - CheckResult result = getBackend().checkFastAnimation(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_ANIMATION); - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) { - Player player = event.getPlayer(); - String section = "\u00a7"; - if (getCheckManager().willCheck(player, CheckType.ZOMBE_FLY)) { - player.sendMessage(section + "f " + section + "f " + section + "1 " + section + "0 " + section + "2 " + section + "4"); - } - if (getCheckManager().willCheck(player, CheckType.ZOMBE_CHEAT)) { - player.sendMessage(section + "f " + section + "f " + section + "2 " + section + "0 " + section + "4 " + section + "8"); - } - if (getCheckManager().willCheck(player, CheckType.ZOMBE_NOCLIP)) { - player.sendMessage(section + "f " + section + "f " + section + "4 " + section + "0 " + section + "9 " + section + "6"); - } - - getBackend().logJoin(player); - - User user = new User(player.getName()); - user.setIsWaitingOnLevelSync(true); - getConfig().getLevels().loadLevelToUser(user); - getUserManager().addUser(user); - - if (player.hasMetadata(Utilities.SPY_METADATA)) { - for (Player p : player.getServer().getOnlinePlayers()) { - if (!Permission.SYSTEM_SPY.get(p)) { - p.hidePlayer(player); - } - } - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onPlayerMove(PlayerMoveEvent event) { - final Player player = event.getPlayer(); - if (getCheckManager().checkInWorld(player) && !getCheckManager().isOpExempt(player)) { - final Location from = event.getFrom(); - final Location to = event.getTo(); - - final Distance distance = new Distance(from, to); - final double y = distance.getYDifference(); - getBackend().logAscension(player, from.getY(), to.getY()); - - final User user = getUserManager().getUser(player.getName()); - user.setTo(to.getX(), to.getY(), to.getZ()); - - if (getCheckManager().willCheckQuick(player, CheckType.SPEED)) { - CheckResult result = getBackend().checkFreeze(player, from.getY(), to.getY()); - if (result.failed()) { - log(result.getMessage(), player, CheckType.SPEED); - if (!silentMode()) { - player.kickPlayer("Freezing client"); - } - } - } - if (getCheckManager().willCheckQuick(player, CheckType.SPRINT)) { - CheckResult result = getBackend().checkSprintStill(player, from, to); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.SPRINT); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.FLY) && !player.isFlying()) { - CheckResult result = getBackend().checkFlight(player, distance); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log(result.getMessage(), player, CheckType.FLY); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.VCLIP) && event.getFrom().getY() > event.getTo().getY()) { - CheckResult result = getBackend().checkVClip(player, new Distance(event.getFrom(), event.getTo())); - if (result.failed()) { - if (!silentMode()) { - int data = result.getData() > 3 ? 3 : result.getData(); - Location newloc = new Location(player.getWorld(), event.getFrom().getX(), event.getFrom().getY() + data, event.getFrom().getZ()); - if (newloc.getBlock().getTypeId() == 0) { - event.setTo(newloc); - } else { - event.setTo(user.getGoodLocation(from.clone())); - } - player.damage(3); - } - log(result.getMessage(), player, CheckType.VCLIP); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.NOFALL) && getCheckManager().willCheck(player, CheckType.FLY) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && event.getFrom().getY() > event.getTo().getY()) { - CheckResult result = getBackend().checkNoFall(player, y); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - player.damage(1); // I added this in here so the player would still receive damage. - } - log(result.getMessage(), player, CheckType.NOFALL); - } - } - - boolean changed = false; - if (event.getTo() != event.getFrom()) { - double x = distance.getXDifference(); - double z = distance.getZDifference(); - if (getCheckManager().willCheckQuick(player, CheckType.SPEED) && getCheckManager().willCheck(player, CheckType.FLY)) { - if (event.getFrom().getY() < event.getTo().getY()) { - CheckResult result = getBackend().checkYSpeed(player, y); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log(result.getMessage(), player, CheckType.SPEED); - changed = true; - } - } - CheckResult result = getBackend().checkXZSpeed(player, x, z); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log(result.getMessage(), player, CheckType.SPEED); - changed = true; - } - /*if ((event.getFrom().getX() != event.getTo().getX() || event.getFrom().getZ() != event.getTo().getZ())) { - result = backend.checkTimer(player); - if(result.failed()) { - if (!config.silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log("tried to alter their timer.", player, CheckType.SPEED); - changed = true; - } - } - */ - } - if (getCheckManager().willCheckQuick(player, CheckType.WATER_WALK)) { - CheckResult result = getBackend().checkWaterWalk(player, x, y, z); - if (result.failed()) { - if (!silentMode()) { - player.teleport(user.getGoodLocation(player.getLocation().add(0, -1, 0))); - } - log(result.getMessage(), player, CheckType.WATER_WALK); - changed = true; - } - } - if (getCheckManager().willCheckQuick(player, CheckType.SNEAK)) { - CheckResult result = getBackend().checkSneak(player, x, z); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - player.setSneaking(false); - } - log(result.getMessage(), player, CheckType.SNEAK); - changed = true; - } - } - if (getCheckManager().willCheckQuick(player, CheckType.SPIDER)) { - CheckResult result = getBackend().checkSpider(player, y); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log(result.getMessage(), player, CheckType.SPIDER); - changed = true; - } - } - if (!changed) { - user.setGoodLocation(event.getFrom()); - } - } - } - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void checkFly(PlayerMoveEvent event) { - // Check flight on highest to make sure other plugins have a chance to change the values first. - final Player player = event.getPlayer(); - final User user = getUserManager().getUser(player.getName()); - final Location from = event.getFrom(); - final Location to = event.getTo(); - - if (!user.checkTo(to.getX(), to.getY(), to.getZ())) { - // The to value has been modified by another plugin - return; - } - - if (getCheckManager().willCheck(player, CheckType.FLY) && !player.isFlying()) { - CheckResult result1 = getBackend().checkYAxis(player, new Distance(from, to)); - CheckResult result2 = getBackend().checkAscension(player, from.getY(), to.getY()); - String log = result1.failed() ? result1.getMessage() : result2.failed() ? result2.getMessage() : ""; - if (!log.equals("")) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log(log, player, CheckType.FLY); - } - } - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.event; + +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.manage.CheckType; +import net.gravitydevelopment.anticheat.manage.User; +import net.gravitydevelopment.anticheat.util.CheckResult; +import net.gravitydevelopment.anticheat.util.Distance; +import net.gravitydevelopment.anticheat.util.Permission; +import net.gravitydevelopment.anticheat.util.Utilities; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.ProjectileLaunchEvent; +import org.bukkit.event.player.*; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.inventory.PlayerInventory; + +public class PlayerListener extends EventListener { + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { + Player player = event.getPlayer(); + if (getCheckManager().willCheck(player, CheckType.SPAM) && getConfig().getConfig().blockCommandSpam.getValue()) { + CheckResult result = getBackend().checkSpam(player, event.getMessage()); + if (result.failed()) { + event.setCancelled(!silentMode()); + player.sendMessage(ChatColor.RED + result.getMessage()); + getBackend().processChatSpammer(player); + log(null, player, CheckType.SPAM); + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onPlayerToggleFlight(PlayerToggleFlightEvent event) { + if (!event.isFlying()) { + getBackend().logEnterExit(event.getPlayer()); + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) { + if (event.getNewGameMode() != GameMode.CREATIVE) { + getBackend().logEnterExit(event.getPlayer()); + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @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 (getCheckManager().willCheck(player, CheckType.FAST_PROJECTILE)) { + CheckResult result = getBackend().checkProjectile(player); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.FAST_PROJECTILE); + } + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onPlayerTeleport(PlayerTeleportEvent event) { + if (event.getCause() == TeleportCause.ENDER_PEARL || event.getCause() == TeleportCause.PLUGIN) { + getBackend().logTeleport(event.getPlayer()); + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onPlayerChangeWorlds(PlayerChangedWorldEvent event) { + getBackend().logTeleport(event.getPlayer()); + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onPlayerToggleSneak(PlayerToggleSneakEvent event) { + if (event.isSneaking()) { + getBackend().logToggleSneak(event.getPlayer()); + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onPlayerVelocity(PlayerVelocityEvent event) { + Player player = event.getPlayer(); + if (getCheckManager().willCheck(player, CheckType.FLY)) { + if (getBackend().justVelocity(player) && getBackend().extendVelocityTime(player)) { + event.setCancelled(!silentMode()); + return; // don't log it lol. + } + getBackend().logVelocity(player); + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerChat(AsyncPlayerChatEvent event) { + Player player = event.getPlayer(); + + if (getCheckManager().willCheck(player, CheckType.SPAM) && getConfig().getConfig().blockChatSpam.getValue()) { + CheckResult result = getBackend().checkSpam(player, event.getMessage()); + if (result.failed()) { + event.setCancelled(!silentMode()); + if (!result.getMessage().equals("")) { + player.sendMessage(ChatColor.RED + result.getMessage()); + } + getBackend().processChatSpammer(player); + log(null, player, CheckType.SPAM); + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onPlayerKick(PlayerKickEvent event) { + getBackend().clearChatLevel(event.getPlayer()); + getBackend().garbageClean(event.getPlayer()); + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent event) { + getBackend().garbageClean(event.getPlayer()); + + User user = getUserManager().getUser(event.getPlayer().getName()); + + getConfig().getLevels().saveLevelFromUser(user); + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onPlayerToggleSprint(PlayerToggleSprintEvent event) { + Player player = event.getPlayer(); + if (!event.isSprinting()) { + getBackend().logEnterExit(player); + } + if (getCheckManager().willCheck(player, CheckType.SPRINT)) { + CheckResult result = getBackend().checkSprintHungry(event); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.SPRINT); + } else { + decrease(player); + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @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) { + getBackend().logBowWindUp(player); + } else if (Utilities.isFood(m)) { + getBackend().logEatingStart(player); + } + } + Block block = event.getClickedBlock(); + + if (block != null) { + Distance distance = new Distance(player.getLocation(), block.getLocation()); + getBackend().checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference()); + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerDropItem(PlayerDropItemEvent event) { + Player player = event.getPlayer(); + if (getCheckManager().willCheck(player, CheckType.ITEM_SPAM)) { + CheckResult result = getBackend().checkFastDrop(player); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.ITEM_SPAM); + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerEnterBed(PlayerBedEnterEvent event) { + if (event.getBed().getType() != Material.BED) return; + getBackend().logEnterExit(event.getPlayer()); + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerExitBed(PlayerBedLeaveEvent event) { + if (event.getBed().getType() != Material.BED) return; + getBackend().logEnterExit(event.getPlayer()); + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onPlayerAnimation(PlayerAnimationEvent event) { + Player player = event.getPlayer(); + if (getCheckManager().willCheck(player, CheckType.FAST_ANIMATION)) { + CheckResult result = getBackend().checkFastAnimation(player); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.FAST_ANIMATION); + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + String section = "\u00a7"; + if (getCheckManager().willCheck(player, CheckType.ZOMBE_FLY)) { + player.sendMessage(section + "f " + section + "f " + section + "1 " + section + "0 " + section + "2 " + section + "4"); + } + if (getCheckManager().willCheck(player, CheckType.ZOMBE_CHEAT)) { + player.sendMessage(section + "f " + section + "f " + section + "2 " + section + "0 " + section + "4 " + section + "8"); + } + if (getCheckManager().willCheck(player, CheckType.ZOMBE_NOCLIP)) { + player.sendMessage(section + "f " + section + "f " + section + "4 " + section + "0 " + section + "9 " + section + "6"); + } + + getBackend().logJoin(player); + + User user = new User(player.getName()); + user.setIsWaitingOnLevelSync(true); + getConfig().getLevels().loadLevelToUser(user); + getUserManager().addUser(user); + + if (player.hasMetadata(Utilities.SPY_METADATA)) { + for (Player p : player.getServer().getOnlinePlayers()) { + if (!Permission.SYSTEM_SPY.get(p)) { + p.hidePlayer(player); + } + } + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onPlayerMove(PlayerMoveEvent event) { + final Player player = event.getPlayer(); + if (getCheckManager().checkInWorld(player) && !getCheckManager().isOpExempt(player)) { + final Location from = event.getFrom(); + final Location to = event.getTo(); + + final Distance distance = new Distance(from, to); + final double y = distance.getYDifference(); + getBackend().logAscension(player, from.getY(), to.getY()); + + final User user = getUserManager().getUser(player.getName()); + user.setTo(to.getX(), to.getY(), to.getZ()); + + if (getCheckManager().willCheckQuick(player, CheckType.SPEED)) { + CheckResult result = getBackend().checkFreeze(player, from.getY(), to.getY()); + if (result.failed()) { + log(result.getMessage(), player, CheckType.SPEED); + if (!silentMode()) { + player.kickPlayer("Freezing client"); + } + } + } + if (getCheckManager().willCheckQuick(player, CheckType.SPRINT)) { + CheckResult result = getBackend().checkSprintStill(player, from, to); + if (result.failed()) { + event.setCancelled(!silentMode()); + log(result.getMessage(), player, CheckType.SPRINT); + } + } + if (getCheckManager().willCheckQuick(player, CheckType.FLY) && !player.isFlying()) { + CheckResult result = getBackend().checkFlight(player, distance); + if (result.failed()) { + if (!silentMode()) { + event.setTo(user.getGoodLocation(from.clone())); + } + log(result.getMessage(), player, CheckType.FLY); + } + } + if (getCheckManager().willCheckQuick(player, CheckType.VCLIP) && event.getFrom().getY() > event.getTo().getY()) { + CheckResult result = getBackend().checkVClip(player, new Distance(event.getFrom(), event.getTo())); + if (result.failed()) { + if (!silentMode()) { + int data = result.getData() > 3 ? 3 : result.getData(); + Location newloc = new Location(player.getWorld(), event.getFrom().getX(), event.getFrom().getY() + data, event.getFrom().getZ()); + if (newloc.getBlock().getTypeId() == 0) { + event.setTo(newloc); + } else { + event.setTo(user.getGoodLocation(from.clone())); + } + player.damage(3); + } + log(result.getMessage(), player, CheckType.VCLIP); + } + } + if (getCheckManager().willCheckQuick(player, CheckType.NOFALL) && getCheckManager().willCheck(player, CheckType.FLY) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && event.getFrom().getY() > event.getTo().getY()) { + CheckResult result = getBackend().checkNoFall(player, y); + if (result.failed()) { + if (!silentMode()) { + event.setTo(user.getGoodLocation(from.clone())); + player.damage(1); // I added this in here so the player would still receive damage. + } + log(result.getMessage(), player, CheckType.NOFALL); + } + } + + boolean changed = false; + if (event.getTo() != event.getFrom()) { + double x = distance.getXDifference(); + double z = distance.getZDifference(); + if (getCheckManager().willCheckQuick(player, CheckType.SPEED) && getCheckManager().willCheck(player, CheckType.FLY)) { + if (event.getFrom().getY() < event.getTo().getY()) { + CheckResult result = getBackend().checkYSpeed(player, y); + if (result.failed()) { + if (!silentMode()) { + event.setTo(user.getGoodLocation(from.clone())); + } + log(result.getMessage(), player, CheckType.SPEED); + changed = true; + } + } + CheckResult result = getBackend().checkXZSpeed(player, x, z); + if (result.failed()) { + if (!silentMode()) { + event.setTo(user.getGoodLocation(from.clone())); + } + log(result.getMessage(), player, CheckType.SPEED); + changed = true; + } + /*if ((event.getFrom().getX() != event.getTo().getX() || event.getFrom().getZ() != event.getTo().getZ())) { + result = backend.checkTimer(player); + if(result.failed()) { + if (!config.silentMode()) { + event.setTo(user.getGoodLocation(from.clone())); + } + log("tried to alter their timer.", player, CheckType.SPEED); + changed = true; + } + } + */ + } + if (getCheckManager().willCheckQuick(player, CheckType.WATER_WALK)) { + CheckResult result = getBackend().checkWaterWalk(player, x, y, z); + if (result.failed()) { + if (!silentMode()) { + player.teleport(user.getGoodLocation(player.getLocation().add(0, -1, 0))); + } + log(result.getMessage(), player, CheckType.WATER_WALK); + changed = true; + } + } + if (getCheckManager().willCheckQuick(player, CheckType.SNEAK)) { + CheckResult result = getBackend().checkSneak(player, x, z); + if (result.failed()) { + if (!silentMode()) { + event.setTo(user.getGoodLocation(from.clone())); + player.setSneaking(false); + } + log(result.getMessage(), player, CheckType.SNEAK); + changed = true; + } + } + if (getCheckManager().willCheckQuick(player, CheckType.SPIDER)) { + CheckResult result = getBackend().checkSpider(player, y); + if (result.failed()) { + if (!silentMode()) { + event.setTo(user.getGoodLocation(from.clone())); + } + log(result.getMessage(), player, CheckType.SPIDER); + changed = true; + } + } + if (!changed) { + user.setGoodLocation(event.getFrom()); + } + } + } + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void checkFly(PlayerMoveEvent event) { + // Check flight on highest to make sure other plugins have a chance to change the values first. + final Player player = event.getPlayer(); + final User user = getUserManager().getUser(player.getName()); + final Location from = event.getFrom(); + final Location to = event.getTo(); + + if (!user.checkTo(to.getX(), to.getY(), to.getZ())) { + // The to value has been modified by another plugin + return; + } + + if (getCheckManager().willCheck(player, CheckType.FLY) && !player.isFlying()) { + CheckResult result1 = getBackend().checkYAxis(player, new Distance(from, to)); + CheckResult result2 = getBackend().checkAscension(player, from.getY(), to.getY()); + String log = result1.failed() ? result1.getMessage() : result2.failed() ? result2.getMessage() : ""; + if (!log.equals("")) { + if (!silentMode()) { + event.setTo(user.getGoodLocation(from.clone())); + } + log(log, player, CheckType.FLY); + } + } + } +} diff --git a/src/main/java/net/h31ix/anticheat/event/VehicleListener.java b/src/main/java/net/gravitydevelopment/anticheat/event/VehicleListener.java similarity index 94% rename from src/main/java/net/h31ix/anticheat/event/VehicleListener.java rename to src/main/java/net/gravitydevelopment/anticheat/event/VehicleListener.java index 81ad1d1..0110f2c 100644 --- a/src/main/java/net/h31ix/anticheat/event/VehicleListener.java +++ b/src/main/java/net/gravitydevelopment/anticheat/event/VehicleListener.java @@ -1,57 +1,57 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.event; - -import net.h31ix.anticheat.AntiCheat; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.vehicle.VehicleDestroyEvent; -import org.bukkit.event.vehicle.VehicleEnterEvent; -import org.bukkit.event.vehicle.VehicleExitEvent; - -public class VehicleListener extends EventListener { - - @EventHandler(ignoreCancelled = true) - public void onVehicleEnter(VehicleEnterEvent event) { - if (event.getEntered() instanceof Player) { - getBackend().logEnterExit((Player) event.getEntered()); - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onVehicleExit(VehicleExitEvent event) { - if (event.getExited() instanceof Player) { - getBackend().logEnterExit((Player) event.getExited()); - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - - @EventHandler(ignoreCancelled = true) - public void onVehicleDestroy(VehicleDestroyEvent event) { - if (event.getVehicle().getPassenger() != null && event.getVehicle().getPassenger() instanceof Player) { - getBackend().logEnterExit((Player) event.getVehicle().getPassenger()); - } - - AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.event; + +import net.gravitydevelopment.anticheat.AntiCheat; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.vehicle.VehicleDestroyEvent; +import org.bukkit.event.vehicle.VehicleEnterEvent; +import org.bukkit.event.vehicle.VehicleExitEvent; + +public class VehicleListener extends EventListener { + + @EventHandler(ignoreCancelled = true) + public void onVehicleEnter(VehicleEnterEvent event) { + if (event.getEntered() instanceof Player) { + getBackend().logEnterExit((Player) event.getEntered()); + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + @EventHandler(ignoreCancelled = true) + public void onVehicleExit(VehicleExitEvent event) { + if (event.getExited() instanceof Player) { + getBackend().logEnterExit((Player) event.getExited()); + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } + + + @EventHandler(ignoreCancelled = true) + public void onVehicleDestroy(VehicleDestroyEvent event) { + if (event.getVehicle().getPassenger() != null && event.getVehicle().getPassenger() instanceof Player) { + getBackend().logEnterExit((Player) event.getVehicle().getPassenger()); + } + + AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + } +} diff --git a/src/main/java/net/h31ix/anticheat/manage/AnticheatManager.java b/src/main/java/net/gravitydevelopment/anticheat/manage/AnticheatManager.java similarity index 92% rename from src/main/java/net/h31ix/anticheat/manage/AnticheatManager.java rename to src/main/java/net/gravitydevelopment/anticheat/manage/AnticheatManager.java index 92d1a98..2bbc82e 100644 --- a/src/main/java/net/h31ix/anticheat/manage/AnticheatManager.java +++ b/src/main/java/net/gravitydevelopment/anticheat/manage/AnticheatManager.java @@ -1,185 +1,185 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.manage; - -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.util.FileFormatter; -import net.h31ix.anticheat.xray.XRayTracker; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.plugin.RegisteredListener; - -import java.io.File; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.logging.FileHandler; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * The internal hub for all managers. - */ - -public class AnticheatManager { - private static AntiCheat plugin = null; - private static Configuration configuration; - private static XRayTracker xrayTracker = null; - private static UserManager userManager = null; - private static CheckManager checkManager = null; - private static Backend backend = null; - private final Logger fileLogger; - private static Map eventchains = new ConcurrentHashMap(); - private static Map eventcache = new ConcurrentHashMap(); - 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(plugin); - xrayTracker = new XRayTracker(); - userManager = new UserManager(configuration); - checkManager = new CheckManager(this, configuration); - 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 (i != 1 && getConfiguration().getConfig().logToConsole.getValue()) { - Bukkit.getConsoleSender().sendMessage("[AntiCheat] " + ChatColor.RED + message); - } - if (i == 0 && getConfiguration().getConfig().fileLogLevel.getValue() == LOG_LEVEL_HIGH) // Not an alert, normal log message - { - fileLog(message); - } else if (getConfiguration().getConfig().fileLogLevel.getValue() != 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 void addEvent(String e, RegisteredListener[] arr) { - if (!configuration.getConfig().eventChains.getValue()) - return; - if (!eventcache.containsKey(e) || eventcache.get(e) > 30000L) { - eventchains.put(e, arr); - eventcache.put(e, System.currentTimeMillis()); - } - } - - public String getEventChainReport() { - String gen = ""; - if (!configuration.getConfig().eventChains.getValue()) { - return "Event Chains is disabled by the configuration." + '\n'; - } - - if (eventchains.entrySet().size() == 0) { - return "No event chains found." + '\n'; - } - - for (Entry e : eventchains.entrySet()) { - String toadd = ""; - String ename = e.getKey(); - - toadd += ename + ":" + '\n'; - - RegisteredListener[] reg = e.getValue(); - for (RegisteredListener plug : reg) { - String pluginname = plug.getPlugin().getName(); - if (pluginname.equals("AntiCheat")) - pluginname = "self"; - - toadd += "- " + pluginname + '\n'; - } - - gen += toadd + '\n'; - } - - return gen; - } - - 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(); - - if (configuration.getConfig().enterprise.getValue()) { - configuration.getEnterprise().database.shutdown(); - } - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.manage; + +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.util.FileFormatter; +import net.gravitydevelopment.anticheat.xray.XRayTracker; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.plugin.RegisteredListener; + +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.logging.FileHandler; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * The internal hub for all managers. + */ + +public class AnticheatManager { + private static AntiCheat plugin = null; + private static Configuration configuration; + private static XRayTracker xrayTracker = null; + private static UserManager userManager = null; + private static CheckManager checkManager = null; + private static Backend backend = null; + private final Logger fileLogger; + private static Map eventchains = new ConcurrentHashMap(); + private static Map eventcache = new ConcurrentHashMap(); + 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.gravitydevelopment.anticheat.AntiCheat"); + configuration = new Configuration(plugin); + xrayTracker = new XRayTracker(); + userManager = new UserManager(configuration); + checkManager = new CheckManager(this, configuration); + 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 (i != 1 && getConfiguration().getConfig().logToConsole.getValue()) { + Bukkit.getConsoleSender().sendMessage("[AntiCheat] " + ChatColor.RED + message); + } + if (i == 0 && getConfiguration().getConfig().fileLogLevel.getValue() == LOG_LEVEL_HIGH) // Not an alert, normal log message + { + fileLog(message); + } else if (getConfiguration().getConfig().fileLogLevel.getValue() != 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 void addEvent(String e, RegisteredListener[] arr) { + if (!configuration.getConfig().eventChains.getValue()) + return; + if (!eventcache.containsKey(e) || eventcache.get(e) > 30000L) { + eventchains.put(e, arr); + eventcache.put(e, System.currentTimeMillis()); + } + } + + public String getEventChainReport() { + String gen = ""; + if (!configuration.getConfig().eventChains.getValue()) { + return "Event Chains is disabled by the configuration." + '\n'; + } + + if (eventchains.entrySet().size() == 0) { + return "No event chains found." + '\n'; + } + + for (Entry e : eventchains.entrySet()) { + String toadd = ""; + String ename = e.getKey(); + + toadd += ename + ":" + '\n'; + + RegisteredListener[] reg = e.getValue(); + for (RegisteredListener plug : reg) { + String pluginname = plug.getPlugin().getName(); + if (pluginname.equals("AntiCheat")) + pluginname = "self"; + + toadd += "- " + pluginname + '\n'; + } + + gen += toadd + '\n'; + } + + return gen; + } + + 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(); + + if (configuration.getConfig().enterprise.getValue()) { + configuration.getEnterprise().database.shutdown(); + } + } +} diff --git a/src/main/java/net/h31ix/anticheat/manage/Backend.java b/src/main/java/net/gravitydevelopment/anticheat/manage/Backend.java similarity index 97% rename from src/main/java/net/h31ix/anticheat/manage/Backend.java rename to src/main/java/net/gravitydevelopment/anticheat/manage/Backend.java index 12860cb..75817a0 100644 --- a/src/main/java/net/h31ix/anticheat/manage/Backend.java +++ b/src/main/java/net/gravitydevelopment/anticheat/manage/Backend.java @@ -1,1079 +1,1079 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.manage; - -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.files.Lang; -import net.h31ix.anticheat.config.files.Magic; -import net.h31ix.anticheat.util.CheckResult; -import net.h31ix.anticheat.util.CheckResult.Result; -import net.h31ix.anticheat.util.Distance; -import net.h31ix.anticheat.util.Utilities; -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerToggleSprintEvent; -import org.bukkit.potion.PotionEffectType; - -import java.util.*; - -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 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 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 Map animationTime = new HashMap(); - private Map animations = new HashMap(); - - private Magic magic; - private AnticheatManager manager = null; - private Lang lang = null; - private static final CheckResult PASS = new CheckResult(Result.PASSED); - - public Backend(AnticheatManager instance) { - magic = instance.getConfiguration().getMagic(); - manager = instance; - lang = manager.getConfiguration().getLang(); - transparent.add((byte) -1); - } - - public void updateMagic(Magic magic) { - this.magic = magic; - } - - public void resetChatLevel(Player player) { - chatLevel.put(player.getName(), 0); - } - - public void garbageClean(Player player) { - String pN = player.getName(); - - 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); - 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); - 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 CheckResult 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 PASS; - } - - public CheckResult 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; - if (Math.abs(force - f) > magic.BOW_ERROR) { - return new CheckResult(Result.FAILED, player.getName() + " fired their bow too fast (actual force=" + force + ", calculated force=" + f + ")"); - } else { - return PASS; - } - } - - public CheckResult checkProjectile(Player player) { - increment(player, projectilesShot, 10); - if (!projectileTime.containsKey(player.getName())) { - projectileTime.put(player.getName(), System.currentTimeMillis()); - return new CheckResult(Result.PASSED); - } 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()); - if (time < magic.PROJECTILE_TIME_MIN) { - return new CheckResult(Result.FAILED, player.getName() + " wound up a bow too fast (actual time=" + time + ", min time=" + magic.PROJECTILE_TIME_MIN + ")"); - } - } - return PASS; - } - - public CheckResult checkFastDrop(Player player) { - increment(player, blocksDropped, 10); - if (!blockTime.containsKey(player.getName())) { - blockTime.put(player.getName(), System.currentTimeMillis()); - return new CheckResult(Result.PASSED); - } 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()); - if (time < magic.DROP_TIME_MIN) { - return new CheckResult(Result.FAILED, player.getName() + " dropped an item too fast (actual time=" + time + ", min time=" + magic.DROP_TIME_MIN + ")"); - } - } - return PASS; - } - - public CheckResult checkLongReachBlock(Player player, double x, double y, double z) { - if (isInstantBreakExempt(player)) { - return new CheckResult(Result.PASSED); - } else { - String string = player.getName() + " reached too far for a block"; - double distance = - player.getGameMode() == GameMode.CREATIVE ? magic.BLOCK_MAX_DISTANCE_CREATIVE - : player.getLocation().getDirection().getY() > 0.9 ? magic.BLOCK_MAX_DISTANCE_CREATIVE - : magic.BLOCK_MAX_DISTANCE; - double i = x >= distance ? x : y > distance ? y : z > distance ? z : -1; - if (i != -1) { - return new CheckResult(Result.FAILED, string + " (distance=" + i + ", max=" + magic.BLOCK_MAX_DISTANCE + ")"); - } else { - return PASS; - } - } - } - - public CheckResult checkLongReachDamage(Player player, double x, double y, double z) { - String string = player.getName() + " reached too far for an entity"; - double i = x >= magic.ENTITY_MAX_DISTANCE ? x : y > magic.ENTITY_MAX_DISTANCE ? y : z > magic.ENTITY_MAX_DISTANCE ? z : -1; - if (i != -1) { - return new CheckResult(Result.FAILED, string + " (distance=" + i + ", max=" + magic.ENTITY_MAX_DISTANCE + ")"); - } else { - return PASS; - } - } - - public CheckResult checkSpider(Player player, double y) { - if (y <= magic.LADDER_Y_MAX && y >= magic.LADDER_Y_MIN && !Utilities.isClimbableBlock(player.getLocation().getBlock())) { - return new CheckResult(Result.FAILED, player.getName() + " tried to climb a non-ladder (" + player.getLocation().getBlock().getType() + ")"); - } else { - return PASS; - } - } - - public CheckResult checkYSpeed(Player player, double y) { - if (!isMovingExempt(player) && !player.isInsideVehicle() && !player.isSleeping() && y > magic.Y_SPEED_MAX && !isDoing(player, velocitized, magic.VELOCITY_TIME) && !player.hasPotionEffect(PotionEffectType.JUMP)) { - return new CheckResult(Result.FAILED, player.getName() + "'s y speed was too high (speed=" + y + ", max=" + magic.Y_SPEED_MAX + ")"); - } else { - return PASS; - } - } - - public CheckResult 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) && !Utilities.isInWeb(player)) { - if (player.getFallDistance() == 0) { - if (nofallViolation.get(name) == null) { - nofallViolation.put(name, 1); - } else { - nofallViolation.put(name, nofallViolation.get(player.getName()) + 1); - } - - int i = nofallViolation.get(name); - if (i >= magic.NOFALL_LIMIT) { - nofallViolation.put(player.getName(), 1); - return new CheckResult(Result.FAILED, player.getName() + " tried to avoid fall damage (fall distance = 0 " + i + " times in a row, max=" + magic.NOFALL_LIMIT + ")"); - } else { - return PASS; - } - } else { - nofallViolation.put(name, 0); - return PASS; - } - } - return PASS; - } - - public CheckResult checkXZSpeed(Player player, double x, double z) { - if (!isSpeedExempt(player) && player.getVehicle() == null) { - String reason = ""; - double max = magic.XZ_SPEED_MAX; - if (player.getLocation().getBlock().getType() == Material.SOUL_SAND) { - if (player.isSprinting()) { - reason = "on soulsand while sprinting "; - max = magic.XZ_SPEED_MAX_SOULSAND_SPRINT; - } else if (player.hasPotionEffect(PotionEffectType.SPEED)) { - reason = "on soulsand with speed potion "; - max = magic.XZ_SPEED_MAX_SOULSAND_POTION; - } else { - reason = "on soulsand "; - max = magic.XZ_SPEED_MAX_SOULSAND; - } - } else if (player.isFlying()) { - reason = "while flying "; - max = magic.XZ_SPEED_MAX_FLY; - } else if (player.hasPotionEffect(PotionEffectType.SPEED)) { - reason = "with speed potion "; - max = magic.XZ_SPEED_MAX_POTION; - } else if (player.isSprinting()) { - reason = "while sprinting "; - max = magic.XZ_SPEED_MAX_SPRINT; - } - - float speed = player.getWalkSpeed(); - max += speed > 0 ? player.getWalkSpeed() - 0.2f : 0; - - if (x > max || z > max) { - int num = this.increment(player, speedViolation, magic.SPEED_MAX); - if (num >= magic.SPEED_MAX) { - return new CheckResult(Result.FAILED, player.getName() + "'s speed was too high " + reason + num + " times in a row (max=" + magic.SPEED_MAX + ", speed=" + (x > z ? x : z) + ", max speed=" + max + ")"); - } else { - return PASS; - } - } else { - speedViolation.put(player.getName(), 0); - return PASS; - } - } else { - return PASS; - } - } - - public CheckResult checkSneak(Player player, double x, double z) { - if (player.isSneaking() && !player.isFlying() && !isMovingExempt(player) && !player.isInsideVehicle()) { - double i = x > magic.XZ_SPEED_MAX_SNEAK ? x : z > magic.XZ_SPEED_MAX_SNEAK ? z : -1; - if (i != -1) { - return new CheckResult(Result.FAILED, player.getName() + " was sneaking too fast (speed=" + i + ", max=" + magic.XZ_SPEED_MAX_SNEAK + ")"); - } else { - return PASS; - } - } else { - return PASS; - } - } - - public CheckResult checkSprintHungry(PlayerToggleSprintEvent event) { - Player player = event.getPlayer(); - if (event.isSprinting() && player.getGameMode() != GameMode.CREATIVE && player.getFoodLevel() <= magic.SPRINT_FOOD_MIN) { - return new CheckResult(Result.FAILED, player.getName() + " sprinted while hungry (food=" + player.getFoodLevel() + ", min=" + magic.SPRINT_FOOD_MIN + ")"); - } else { - return PASS; - } - } - - public CheckResult checkSprintStill(Player player, Location from, Location to) { - /*if(!isMovingExempt(player) && player.isSprinting() && from.getX() == to.getX() && from.getZ() == to.getZ()) { - return new CheckResult(Result.FAILED, player.getName()+" sprinted while standing still (xyz = "+(int)from.getX()+","+(int)from.getY()+","+(int)from.getZ()+")"); - }*/ - return PASS; - } - - public CheckResult 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)) { - b = x > magic.XZ_SPEED_MAX_WATER || z > magic.XZ_SPEED_MAX_WATER; - } else { - b = x > magic.XZ_SPEED_MAX_WATER_SPRINT || z > magic.XZ_SPEED_MAX_WATER_SPRINT; - } - if (!b && !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 new CheckResult(Result.FAILED, player.getName() + " stood on water " + v + " times (can't stand on " + block.getType() + " or " + block.getRelative(BlockFace.DOWN).getType() + ")"); - } else { - waterSpeedViolation.put(player.getName(), v + 1); - } - } else { - waterSpeedViolation.put(player.getName(), 1); - } - } - } - } else { - isInWaterCache.add(player.getName()); - return PASS; - } - } else { - isInWater.add(player.getName()); - return PASS; - } - } 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); - } else { - waterAscensionViolation.put(player.getName(), v + 1); - } - return new CheckResult(Result.FAILED, player.getName() + " stood on water " + v + " times (can't stand on " + block.getType() + " or " + block.getRelative(BlockFace.DOWN).getType() + ")"); - } else { - waterAscensionViolation.put(player.getName(), 1); - } - } else { - isInWater.remove(player.getName()); - isInWaterCache.remove(player.getName()); - } - } - return PASS; - } - - public CheckResult checkVClip(Player player, Distance distance) { - double from = Math.round(distance.fromY()); - double to = Math.round(distance.toY()); - - if (player.isInsideVehicle() || (from == to || from < to) || Math.round(distance.getYDifference()) < 2) { - return PASS; - } - - 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()) { - return new CheckResult(Result.FAILED, player.getName() + " tried to move through a solid block", (int) from + 3); - } - } - - return PASS; - } - - public CheckResult checkYAxis(Player player, Distance distance) { - if (distance.getYDifference() > magic.TELEPORT_MIN || distance.getYDifference() < 0) { - return PASS; - } - 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(); - yAxisViolations.put(name, yAxisViolations.get(name) + 1); - yAxisLastViolation.put(name, System.currentTimeMillis()); - if (!silentMode()) { - 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."); - if (g.getBlock().getTypeId() == 0) { - player.teleport(g); - } - } - return new CheckResult(Result.FAILED, player.getName() + " tried to fly on y-axis " + yAxisViolations.get(name) + " times (max =" + magic.Y_MAXVIOLATIONS + ")"); - } else { - if (yAxisViolations.get(name) > magic.Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) > magic.Y_MAXVIOTIME) { - yAxisViolations.put(name, 0); - yAxisLastViolation.put(name, 0L); - } - } - long i = System.currentTimeMillis() - lastYtime.get(name); - double diff = magic.Y_MAXDIFF + (Utilities.isStair(player.getLocation().add(0, -1, 0).getBlock()) ? 0.5 : 0.0); - if ((y1 - lastYcoord.get(name)) > diff && i < magic.Y_TIME) { - Location g = player.getLocation(); - yAxisViolations.put(name, yAxisViolations.get(name) + 1); - yAxisLastViolation.put(name, System.currentTimeMillis()); - if (!silentMode()) { - g.setY(lastYcoord.get(name)); - if (g.getBlock().getTypeId() == 0) { - player.teleport(g); - } - } - return new CheckResult(Result.FAILED, player.getName() + " tried to fly on y-axis in " + i + " ms (min =" + magic.Y_TIME + ")"); - } 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 PASS; - } - - public CheckResult 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); - if (time < magic.TIMER_TIMEMIN) { - return new CheckResult(Result.FAILED, player.getName() + " tried to alter their timer, took " + step + " steps in " + time + " ms (min = " + magic.TIMER_TIMEMIN + " ms)"); - } - } - return PASS; - } - - public CheckResult 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 PASS; - } - // 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 PASS; - } - } - return new CheckResult(Result.FAILED, player.getName()+" tried to damage an entity ("+le.getType()+") out of sight "); - }*/ - return PASS; - } - - public CheckResult checkFlight(Player player, Distance distance) { - if (distance.getYDifference() > magic.TELEPORT_MIN) { - // This was a teleport, so we don't care about it. - return PASS; - } - final String name = player.getName(); - final double y1 = distance.fromY(); - final double y2 = distance.toY(); - if (!isMovingExempt(player) && !Utilities.isHoveringOverWater(player.getLocation(), 1) && Utilities.cantStandAtExp(player.getLocation()) && Utilities.blockIsnt(player.getLocation().getBlock().getRelative(BlockFace.DOWN), new Material[]{Material.FENCE, Material.FENCE_GATE, Material.COBBLE_WALL})) { - - 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 new CheckResult(Result.FAILED, player.getName() + " flew over " + blocksOverFlight.get(name) + " blocks (max=" + magic.FLIGHT_BLOCK_LIMIT + ")"); - } - } else { - blocksOverFlight.put(name, 0D); - } - - return PASS; - } - - 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 CheckResult checkAscension(Player player, double y1, double y2) { - int max = magic.ASCENSION_COUNT_MAX; - String string = ""; - if (player.hasPotionEffect(PotionEffectType.JUMP)) { - max += 12; - string = " with jump potion"; - } - 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 new CheckResult(Result.FAILED, player.getName() + " ascended " + ascensionCount.get(name) + " times in a row (max = " + max + string + ")"); - } - } - } else { - ascensionCount.put(name, 0); - } - } - return PASS; - } - - public CheckResult 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 new CheckResult(Result.FAILED, player.getName() + " tried to break a block of " + block.getType() + " after only " + i + " punches (min=" + magic.BLOCK_PUNCH_MIN + ")"); - } else { - blockPunches.put(name, 0); // it should reset after EACH block break. - } - } - } - } - return PASS; - } - - public CheckResult checkFastBreak(Player player, Block block) { - int violations = magic.FASTBREAK_MAXVIOLATIONS; - long timemax = isInstantBreakExempt(player) ? 0 : 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); - int i = fastBreakViolation.get(name); - if (i > violations && math < magic.FASTBREAK_MAXVIOLATIONTIME) { - lastBlockBroken.put(name, System.currentTimeMillis()); - if (!silentMode()) { - player.sendMessage(ChatColor.RED + "[AntiCheat] Fastbreaking detected. Please wait 10 seconds before breaking blocks."); - } - return new CheckResult(Result.FAILED, player.getName() + " broke blocks too fast " + i + " times in a row (max=" + violations + ")"); - } 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 != 0L && timemax != 0L)) { - if (math < timemax) { - 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) { - int i = fastBreaks.get(name); - fastBreaks.put(name, 0); - fastBreakViolation.put(name, fastBreakViolation.get(name) + 1); - return new CheckResult(Result.FAILED, player.getName() + " tried to break " + i + " blocks in " + math + " ms (max=" + magic.FASTBREAK_LIMIT + " in " + timemax + " ms)"); - } 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 PASS; - } - - public CheckResult checkFastPlace(Player player) { - int violations = player.getGameMode() == GameMode.CREATIVE ? magic.FASTPLACE_MAXVIOLATIONS_CREATIVE : magic.FASTPLACE_MAXVIOLATIONS; - long time = System.currentTimeMillis(); - String name = player.getName(); - if (!lastBlockPlaceTime.containsKey(name) || !fastPlaceViolation.containsKey(name)) { - lastBlockPlaceTime.put(name, 0L); - if (!fastPlaceViolation.containsKey(name)) { - fastPlaceViolation.put(name, 0); - } - } else if (fastPlaceViolation.containsKey(name) && fastPlaceViolation.get(name) > violations) { - AntiCheat.debugLog("Noted that fastPlaceViolation contains key " + name + " with value " + fastPlaceViolation.get(name)); - Long math = System.currentTimeMillis() - lastBlockPlaced.get(name); - AntiCheat.debugLog("Player lastBlockPlaced value = " + lastBlockPlaced + ", diff=" + math); - if (lastBlockPlaced.get(name) > 0 && math < magic.FASTPLACE_MAXVIOLATIONTIME) { - lastBlockPlaced.put(name, time); - if (!silentMode()) { - player.sendMessage(ChatColor.RED + "[AntiCheat] Fastplacing detected. Please wait 10 seconds before placing blocks."); - } - return new CheckResult(Result.FAILED, player.getName() + " placed blocks too fast " + fastBreakViolation.get(name) + " times in a row (max=" + violations + ")"); - } else if (lastBlockPlaced.get(name) > 0 && math > magic.FASTPLACE_MAXVIOLATIONTIME) { - AntiCheat.debugLog("Reset facePlaceViolation for " + name); - fastPlaceViolation.put(name, 0); - } - } else if (lastBlockPlaced.containsKey(name)) { - long last = lastBlockPlaced.get(name); - long lastTime = lastBlockPlaceTime.get(name); - long thisTime = time - last; - - if (lastTime != 0 && thisTime < magic.FASTPLACE_TIMEMIN) { - lastBlockPlaceTime.put(name, (time - last)); - lastBlockPlaced.put(name, time); - fastPlaceViolation.put(name, fastPlaceViolation.get(name) + 1); - return new CheckResult(Result.FAILED, player.getName() + " tried to place a block " + thisTime + " ms after the last one (min=" + magic.FASTPLACE_TIMEMIN + " ms)"); - } - lastBlockPlaceTime.put(name, (time - last)); - } - lastBlockPlaced.put(name, time); - return PASS; - } - - public void logBowWindUp(Player player) { - bowWindUp.put(player.getName(), System.currentTimeMillis()); - } - - public void logEatingStart(Player player) { - startEat.put(player.getName(), System.currentTimeMillis()); - } - - public void logHeal(Player player) { - lastHeal.put(player.getName(), System.currentTimeMillis()); - } - - public CheckResult checkSpam(Player player, String msg) { - String name = player.getName(); - User user = manager.getUserManager().getUser(name); - if (user.getLastMessageTime() != -1) { - for (int i = 0; i < 2; i++) { - String m = user.getMessage(i); - if (m == null) { - break; - } - Long l = user.getMessageTime(i); - - if (System.currentTimeMillis() - l > magic.CHAT_REPEAT_MIN * 100) { - user.clearMessages(); - break; - } else if ((m.equalsIgnoreCase(msg) && i == 1) || System.currentTimeMillis() - user.getLastMessageTime() < magic.CHAT_MIN * 2) { - return new CheckResult(Result.FAILED, lang.spamWarning.getValue()); - } - } - } - user.addMessage(msg); - return PASS; - } - - public CheckResult checkInventoryClicks(Player player) { - if (player.getGameMode() == GameMode.CREATIVE) { - return PASS; - } - 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); - if (time < magic.INVENTORY_TIMEMIN) { - return new CheckResult(Result.FAILED, player.getName() + " clicked inventory slots " + clicks + " times in " + time + " ms (max=" + magic.INVENTORY_CHECK + " in " + magic.INVENTORY_TIMEMIN + " ms)"); - } - } - return PASS; - } - - public CheckResult checkAutoTool(Player player) { - if (itemInHand.containsKey(player.getName()) && itemInHand.get(player.getName()) != player.getItemInHand().getType()) { - return new CheckResult(Result.FAILED, player.getName() + " switched tools too fast (had " + itemInHand.get(player.getName()) + ", has " + player.getItemInHand().getType() + ")"); - } else { - return PASS; - } - } - - public CheckResult checkSprintDamage(Player player) { - if (isDoing(player, sprinted, magic.SPRINT_MIN)) { - return new CheckResult(Result.FAILED, player.getName() + " sprinted and damaged an entity too fast (min sprint=" + magic.SPRINT_MIN + " ms)"); - } else { - return PASS; - } - } - - public CheckResult checkAnimation(Player player, Entity e) { - if (!justAnimated(player)) { - return new CheckResult(Result.FAILED, player.getName() + " didn't animate before damaging a " + e.getType()); - } else { - return PASS; - } - } - - public CheckResult checkFastHeal(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()); - if ((System.currentTimeMillis() - l) < magic.HEAL_TIME_MIN) { - return new CheckResult(Result.FAILED, player.getName() + " healed too quickly (time=" + (System.currentTimeMillis() - l) + " ms, min=" + magic.HEAL_TIME_MIN + " ms)"); - } - } - return PASS; - } - - public CheckResult checkFastEat(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()); - if ((System.currentTimeMillis() - l) < magic.EAT_TIME_MIN) { - return new CheckResult(Result.FAILED, player.getName() + " ate too quickly (time=" + (System.currentTimeMillis() - l) + " ms, min=" + magic.EAT_TIME_MIN + " ms)"); - } - } - return PASS; - } - - public CheckResult checkFastAnimation(final Player player) { - logAnimation(player); - - String name = player.getName(); - int clicks = animations.containsKey(name) ? animations.get(name) + 1 : 1; - animations.put(name, clicks); - if (clicks == 1) { - animationTime.put(name, System.currentTimeMillis()); - } else if (clicks == magic.ANIMATION_CHECK) { - long time = System.currentTimeMillis() - animationTime.get(name); - animations.put(name, 0); - if (time < magic.ANIMATION_TIMEMIN) { - return new CheckResult(Result.FAILED, player.getName() + " clicked " + clicks + " times in " + time + " ms (max=" + magic.ANIMATION_CHECK + " in " + magic.ANIMATION_TIMEMIN + " ms)"); - } - } - return PASS; - } - - 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 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 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 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); - manager.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(manager.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 resetAnimation(final Player player) { - animated.remove(player.getName()); - blockPunches.put(player.getName(), 0); - } - - private boolean justAnimated(Player player) { - 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 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; - } - } - - public void processChatSpammer(Player player) { - if (chatLevel.get(player.getName()) != null && chatLevel.get(player.getName()) >= magic.CHAT_KICK_LEVEL) { - 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 ? manager.getConfiguration().getConfig().spamKickAction.getValue() : manager.getConfiguration().getConfig().spamBanAction.getValue(); - manager.getUserManager().execute(manager.getUserManager().getUser(player.getName()), Utilities.stringToList(event), CheckType.SPAM, lang.spamKickReason.getValue() + "(" + kick + "/3)", Utilities.stringToList(lang.spamWarning.getValue()), lang.spamBanReason.getValue()); - } - } else { - increment(player, chatLevel, magic.CHAT_KICK_LEVEL); - } - } - - 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 boolean silentMode() { - return manager.getConfiguration().getConfig().silentMode.getValue(); - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.manage; + +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.files.Lang; +import net.gravitydevelopment.anticheat.config.files.Magic; +import net.gravitydevelopment.anticheat.util.CheckResult; +import net.gravitydevelopment.anticheat.util.CheckResult.Result; +import net.gravitydevelopment.anticheat.util.Distance; +import net.gravitydevelopment.anticheat.util.Utilities; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerToggleSprintEvent; +import org.bukkit.potion.PotionEffectType; + +import java.util.*; + +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 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 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 Map animationTime = new HashMap(); + private Map animations = new HashMap(); + + private Magic magic; + private AnticheatManager manager = null; + private Lang lang = null; + private static final CheckResult PASS = new CheckResult(Result.PASSED); + + public Backend(AnticheatManager instance) { + magic = instance.getConfiguration().getMagic(); + manager = instance; + lang = manager.getConfiguration().getLang(); + transparent.add((byte) -1); + } + + public void updateMagic(Magic magic) { + this.magic = magic; + } + + public void resetChatLevel(Player player) { + chatLevel.put(player.getName(), 0); + } + + public void garbageClean(Player player) { + String pN = player.getName(); + + 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); + 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); + 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 CheckResult 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 PASS; + } + + public CheckResult 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; + if (Math.abs(force - f) > magic.BOW_ERROR) { + return new CheckResult(Result.FAILED, player.getName() + " fired their bow too fast (actual force=" + force + ", calculated force=" + f + ")"); + } else { + return PASS; + } + } + + public CheckResult checkProjectile(Player player) { + increment(player, projectilesShot, 10); + if (!projectileTime.containsKey(player.getName())) { + projectileTime.put(player.getName(), System.currentTimeMillis()); + return new CheckResult(Result.PASSED); + } 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()); + if (time < magic.PROJECTILE_TIME_MIN) { + return new CheckResult(Result.FAILED, player.getName() + " wound up a bow too fast (actual time=" + time + ", min time=" + magic.PROJECTILE_TIME_MIN + ")"); + } + } + return PASS; + } + + public CheckResult checkFastDrop(Player player) { + increment(player, blocksDropped, 10); + if (!blockTime.containsKey(player.getName())) { + blockTime.put(player.getName(), System.currentTimeMillis()); + return new CheckResult(Result.PASSED); + } 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()); + if (time < magic.DROP_TIME_MIN) { + return new CheckResult(Result.FAILED, player.getName() + " dropped an item too fast (actual time=" + time + ", min time=" + magic.DROP_TIME_MIN + ")"); + } + } + return PASS; + } + + public CheckResult checkLongReachBlock(Player player, double x, double y, double z) { + if (isInstantBreakExempt(player)) { + return new CheckResult(Result.PASSED); + } else { + String string = player.getName() + " reached too far for a block"; + double distance = + player.getGameMode() == GameMode.CREATIVE ? magic.BLOCK_MAX_DISTANCE_CREATIVE + : player.getLocation().getDirection().getY() > 0.9 ? magic.BLOCK_MAX_DISTANCE_CREATIVE + : magic.BLOCK_MAX_DISTANCE; + double i = x >= distance ? x : y > distance ? y : z > distance ? z : -1; + if (i != -1) { + return new CheckResult(Result.FAILED, string + " (distance=" + i + ", max=" + magic.BLOCK_MAX_DISTANCE + ")"); + } else { + return PASS; + } + } + } + + public CheckResult checkLongReachDamage(Player player, double x, double y, double z) { + String string = player.getName() + " reached too far for an entity"; + double i = x >= magic.ENTITY_MAX_DISTANCE ? x : y > magic.ENTITY_MAX_DISTANCE ? y : z > magic.ENTITY_MAX_DISTANCE ? z : -1; + if (i != -1) { + return new CheckResult(Result.FAILED, string + " (distance=" + i + ", max=" + magic.ENTITY_MAX_DISTANCE + ")"); + } else { + return PASS; + } + } + + public CheckResult checkSpider(Player player, double y) { + if (y <= magic.LADDER_Y_MAX && y >= magic.LADDER_Y_MIN && !Utilities.isClimbableBlock(player.getLocation().getBlock())) { + return new CheckResult(Result.FAILED, player.getName() + " tried to climb a non-ladder (" + player.getLocation().getBlock().getType() + ")"); + } else { + return PASS; + } + } + + public CheckResult checkYSpeed(Player player, double y) { + if (!isMovingExempt(player) && !player.isInsideVehicle() && !player.isSleeping() && y > magic.Y_SPEED_MAX && !isDoing(player, velocitized, magic.VELOCITY_TIME) && !player.hasPotionEffect(PotionEffectType.JUMP)) { + return new CheckResult(Result.FAILED, player.getName() + "'s y speed was too high (speed=" + y + ", max=" + magic.Y_SPEED_MAX + ")"); + } else { + return PASS; + } + } + + public CheckResult 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) && !Utilities.isInWeb(player)) { + if (player.getFallDistance() == 0) { + if (nofallViolation.get(name) == null) { + nofallViolation.put(name, 1); + } else { + nofallViolation.put(name, nofallViolation.get(player.getName()) + 1); + } + + int i = nofallViolation.get(name); + if (i >= magic.NOFALL_LIMIT) { + nofallViolation.put(player.getName(), 1); + return new CheckResult(Result.FAILED, player.getName() + " tried to avoid fall damage (fall distance = 0 " + i + " times in a row, max=" + magic.NOFALL_LIMIT + ")"); + } else { + return PASS; + } + } else { + nofallViolation.put(name, 0); + return PASS; + } + } + return PASS; + } + + public CheckResult checkXZSpeed(Player player, double x, double z) { + if (!isSpeedExempt(player) && player.getVehicle() == null) { + String reason = ""; + double max = magic.XZ_SPEED_MAX; + if (player.getLocation().getBlock().getType() == Material.SOUL_SAND) { + if (player.isSprinting()) { + reason = "on soulsand while sprinting "; + max = magic.XZ_SPEED_MAX_SOULSAND_SPRINT; + } else if (player.hasPotionEffect(PotionEffectType.SPEED)) { + reason = "on soulsand with speed potion "; + max = magic.XZ_SPEED_MAX_SOULSAND_POTION; + } else { + reason = "on soulsand "; + max = magic.XZ_SPEED_MAX_SOULSAND; + } + } else if (player.isFlying()) { + reason = "while flying "; + max = magic.XZ_SPEED_MAX_FLY; + } else if (player.hasPotionEffect(PotionEffectType.SPEED)) { + reason = "with speed potion "; + max = magic.XZ_SPEED_MAX_POTION; + } else if (player.isSprinting()) { + reason = "while sprinting "; + max = magic.XZ_SPEED_MAX_SPRINT; + } + + float speed = player.getWalkSpeed(); + max += speed > 0 ? player.getWalkSpeed() - 0.2f : 0; + + if (x > max || z > max) { + int num = this.increment(player, speedViolation, magic.SPEED_MAX); + if (num >= magic.SPEED_MAX) { + return new CheckResult(Result.FAILED, player.getName() + "'s speed was too high " + reason + num + " times in a row (max=" + magic.SPEED_MAX + ", speed=" + (x > z ? x : z) + ", max speed=" + max + ")"); + } else { + return PASS; + } + } else { + speedViolation.put(player.getName(), 0); + return PASS; + } + } else { + return PASS; + } + } + + public CheckResult checkSneak(Player player, double x, double z) { + if (player.isSneaking() && !player.isFlying() && !isMovingExempt(player) && !player.isInsideVehicle()) { + double i = x > magic.XZ_SPEED_MAX_SNEAK ? x : z > magic.XZ_SPEED_MAX_SNEAK ? z : -1; + if (i != -1) { + return new CheckResult(Result.FAILED, player.getName() + " was sneaking too fast (speed=" + i + ", max=" + magic.XZ_SPEED_MAX_SNEAK + ")"); + } else { + return PASS; + } + } else { + return PASS; + } + } + + public CheckResult checkSprintHungry(PlayerToggleSprintEvent event) { + Player player = event.getPlayer(); + if (event.isSprinting() && player.getGameMode() != GameMode.CREATIVE && player.getFoodLevel() <= magic.SPRINT_FOOD_MIN) { + return new CheckResult(Result.FAILED, player.getName() + " sprinted while hungry (food=" + player.getFoodLevel() + ", min=" + magic.SPRINT_FOOD_MIN + ")"); + } else { + return PASS; + } + } + + public CheckResult checkSprintStill(Player player, Location from, Location to) { + /*if(!isMovingExempt(player) && player.isSprinting() && from.getX() == to.getX() && from.getZ() == to.getZ()) { + return new CheckResult(Result.FAILED, player.getName()+" sprinted while standing still (xyz = "+(int)from.getX()+","+(int)from.getY()+","+(int)from.getZ()+")"); + }*/ + return PASS; + } + + public CheckResult 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)) { + b = x > magic.XZ_SPEED_MAX_WATER || z > magic.XZ_SPEED_MAX_WATER; + } else { + b = x > magic.XZ_SPEED_MAX_WATER_SPRINT || z > magic.XZ_SPEED_MAX_WATER_SPRINT; + } + if (!b && !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 new CheckResult(Result.FAILED, player.getName() + " stood on water " + v + " times (can't stand on " + block.getType() + " or " + block.getRelative(BlockFace.DOWN).getType() + ")"); + } else { + waterSpeedViolation.put(player.getName(), v + 1); + } + } else { + waterSpeedViolation.put(player.getName(), 1); + } + } + } + } else { + isInWaterCache.add(player.getName()); + return PASS; + } + } else { + isInWater.add(player.getName()); + return PASS; + } + } 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); + } else { + waterAscensionViolation.put(player.getName(), v + 1); + } + return new CheckResult(Result.FAILED, player.getName() + " stood on water " + v + " times (can't stand on " + block.getType() + " or " + block.getRelative(BlockFace.DOWN).getType() + ")"); + } else { + waterAscensionViolation.put(player.getName(), 1); + } + } else { + isInWater.remove(player.getName()); + isInWaterCache.remove(player.getName()); + } + } + return PASS; + } + + public CheckResult checkVClip(Player player, Distance distance) { + double from = Math.round(distance.fromY()); + double to = Math.round(distance.toY()); + + if (player.isInsideVehicle() || (from == to || from < to) || Math.round(distance.getYDifference()) < 2) { + return PASS; + } + + 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()) { + return new CheckResult(Result.FAILED, player.getName() + " tried to move through a solid block", (int) from + 3); + } + } + + return PASS; + } + + public CheckResult checkYAxis(Player player, Distance distance) { + if (distance.getYDifference() > magic.TELEPORT_MIN || distance.getYDifference() < 0) { + return PASS; + } + 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(); + yAxisViolations.put(name, yAxisViolations.get(name) + 1); + yAxisLastViolation.put(name, System.currentTimeMillis()); + if (!silentMode()) { + 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."); + if (g.getBlock().getTypeId() == 0) { + player.teleport(g); + } + } + return new CheckResult(Result.FAILED, player.getName() + " tried to fly on y-axis " + yAxisViolations.get(name) + " times (max =" + magic.Y_MAXVIOLATIONS + ")"); + } else { + if (yAxisViolations.get(name) > magic.Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) > magic.Y_MAXVIOTIME) { + yAxisViolations.put(name, 0); + yAxisLastViolation.put(name, 0L); + } + } + long i = System.currentTimeMillis() - lastYtime.get(name); + double diff = magic.Y_MAXDIFF + (Utilities.isStair(player.getLocation().add(0, -1, 0).getBlock()) ? 0.5 : 0.0); + if ((y1 - lastYcoord.get(name)) > diff && i < magic.Y_TIME) { + Location g = player.getLocation(); + yAxisViolations.put(name, yAxisViolations.get(name) + 1); + yAxisLastViolation.put(name, System.currentTimeMillis()); + if (!silentMode()) { + g.setY(lastYcoord.get(name)); + if (g.getBlock().getTypeId() == 0) { + player.teleport(g); + } + } + return new CheckResult(Result.FAILED, player.getName() + " tried to fly on y-axis in " + i + " ms (min =" + magic.Y_TIME + ")"); + } 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 PASS; + } + + public CheckResult 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); + if (time < magic.TIMER_TIMEMIN) { + return new CheckResult(Result.FAILED, player.getName() + " tried to alter their timer, took " + step + " steps in " + time + " ms (min = " + magic.TIMER_TIMEMIN + " ms)"); + } + } + return PASS; + } + + public CheckResult 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 PASS; + } + // 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 PASS; + } + } + return new CheckResult(Result.FAILED, player.getName()+" tried to damage an entity ("+le.getType()+") out of sight "); + }*/ + return PASS; + } + + public CheckResult checkFlight(Player player, Distance distance) { + if (distance.getYDifference() > magic.TELEPORT_MIN) { + // This was a teleport, so we don't care about it. + return PASS; + } + final String name = player.getName(); + final double y1 = distance.fromY(); + final double y2 = distance.toY(); + if (!isMovingExempt(player) && !Utilities.isHoveringOverWater(player.getLocation(), 1) && Utilities.cantStandAtExp(player.getLocation()) && Utilities.blockIsnt(player.getLocation().getBlock().getRelative(BlockFace.DOWN), new Material[]{Material.FENCE, Material.FENCE_GATE, Material.COBBLE_WALL})) { + + 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 new CheckResult(Result.FAILED, player.getName() + " flew over " + blocksOverFlight.get(name) + " blocks (max=" + magic.FLIGHT_BLOCK_LIMIT + ")"); + } + } else { + blocksOverFlight.put(name, 0D); + } + + return PASS; + } + + 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 CheckResult checkAscension(Player player, double y1, double y2) { + int max = magic.ASCENSION_COUNT_MAX; + String string = ""; + if (player.hasPotionEffect(PotionEffectType.JUMP)) { + max += 12; + string = " with jump potion"; + } + 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 new CheckResult(Result.FAILED, player.getName() + " ascended " + ascensionCount.get(name) + " times in a row (max = " + max + string + ")"); + } + } + } else { + ascensionCount.put(name, 0); + } + } + return PASS; + } + + public CheckResult 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 new CheckResult(Result.FAILED, player.getName() + " tried to break a block of " + block.getType() + " after only " + i + " punches (min=" + magic.BLOCK_PUNCH_MIN + ")"); + } else { + blockPunches.put(name, 0); // it should reset after EACH block break. + } + } + } + } + return PASS; + } + + public CheckResult checkFastBreak(Player player, Block block) { + int violations = magic.FASTBREAK_MAXVIOLATIONS; + long timemax = isInstantBreakExempt(player) ? 0 : 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); + int i = fastBreakViolation.get(name); + if (i > violations && math < magic.FASTBREAK_MAXVIOLATIONTIME) { + lastBlockBroken.put(name, System.currentTimeMillis()); + if (!silentMode()) { + player.sendMessage(ChatColor.RED + "[AntiCheat] Fastbreaking detected. Please wait 10 seconds before breaking blocks."); + } + return new CheckResult(Result.FAILED, player.getName() + " broke blocks too fast " + i + " times in a row (max=" + violations + ")"); + } 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 != 0L && timemax != 0L)) { + if (math < timemax) { + 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) { + int i = fastBreaks.get(name); + fastBreaks.put(name, 0); + fastBreakViolation.put(name, fastBreakViolation.get(name) + 1); + return new CheckResult(Result.FAILED, player.getName() + " tried to break " + i + " blocks in " + math + " ms (max=" + magic.FASTBREAK_LIMIT + " in " + timemax + " ms)"); + } 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 PASS; + } + + public CheckResult checkFastPlace(Player player) { + int violations = player.getGameMode() == GameMode.CREATIVE ? magic.FASTPLACE_MAXVIOLATIONS_CREATIVE : magic.FASTPLACE_MAXVIOLATIONS; + long time = System.currentTimeMillis(); + String name = player.getName(); + if (!lastBlockPlaceTime.containsKey(name) || !fastPlaceViolation.containsKey(name)) { + lastBlockPlaceTime.put(name, 0L); + if (!fastPlaceViolation.containsKey(name)) { + fastPlaceViolation.put(name, 0); + } + } else if (fastPlaceViolation.containsKey(name) && fastPlaceViolation.get(name) > violations) { + AntiCheat.debugLog("Noted that fastPlaceViolation contains key " + name + " with value " + fastPlaceViolation.get(name)); + Long math = System.currentTimeMillis() - lastBlockPlaced.get(name); + AntiCheat.debugLog("Player lastBlockPlaced value = " + lastBlockPlaced + ", diff=" + math); + if (lastBlockPlaced.get(name) > 0 && math < magic.FASTPLACE_MAXVIOLATIONTIME) { + lastBlockPlaced.put(name, time); + if (!silentMode()) { + player.sendMessage(ChatColor.RED + "[AntiCheat] Fastplacing detected. Please wait 10 seconds before placing blocks."); + } + return new CheckResult(Result.FAILED, player.getName() + " placed blocks too fast " + fastBreakViolation.get(name) + " times in a row (max=" + violations + ")"); + } else if (lastBlockPlaced.get(name) > 0 && math > magic.FASTPLACE_MAXVIOLATIONTIME) { + AntiCheat.debugLog("Reset facePlaceViolation for " + name); + fastPlaceViolation.put(name, 0); + } + } else if (lastBlockPlaced.containsKey(name)) { + long last = lastBlockPlaced.get(name); + long lastTime = lastBlockPlaceTime.get(name); + long thisTime = time - last; + + if (lastTime != 0 && thisTime < magic.FASTPLACE_TIMEMIN) { + lastBlockPlaceTime.put(name, (time - last)); + lastBlockPlaced.put(name, time); + fastPlaceViolation.put(name, fastPlaceViolation.get(name) + 1); + return new CheckResult(Result.FAILED, player.getName() + " tried to place a block " + thisTime + " ms after the last one (min=" + magic.FASTPLACE_TIMEMIN + " ms)"); + } + lastBlockPlaceTime.put(name, (time - last)); + } + lastBlockPlaced.put(name, time); + return PASS; + } + + public void logBowWindUp(Player player) { + bowWindUp.put(player.getName(), System.currentTimeMillis()); + } + + public void logEatingStart(Player player) { + startEat.put(player.getName(), System.currentTimeMillis()); + } + + public void logHeal(Player player) { + lastHeal.put(player.getName(), System.currentTimeMillis()); + } + + public CheckResult checkSpam(Player player, String msg) { + String name = player.getName(); + User user = manager.getUserManager().getUser(name); + if (user.getLastMessageTime() != -1) { + for (int i = 0; i < 2; i++) { + String m = user.getMessage(i); + if (m == null) { + break; + } + Long l = user.getMessageTime(i); + + if (System.currentTimeMillis() - l > magic.CHAT_REPEAT_MIN * 100) { + user.clearMessages(); + break; + } else if ((m.equalsIgnoreCase(msg) && i == 1) || System.currentTimeMillis() - user.getLastMessageTime() < magic.CHAT_MIN * 2) { + return new CheckResult(Result.FAILED, lang.spamWarning.getValue()); + } + } + } + user.addMessage(msg); + return PASS; + } + + public CheckResult checkInventoryClicks(Player player) { + if (player.getGameMode() == GameMode.CREATIVE) { + return PASS; + } + 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); + if (time < magic.INVENTORY_TIMEMIN) { + return new CheckResult(Result.FAILED, player.getName() + " clicked inventory slots " + clicks + " times in " + time + " ms (max=" + magic.INVENTORY_CHECK + " in " + magic.INVENTORY_TIMEMIN + " ms)"); + } + } + return PASS; + } + + public CheckResult checkAutoTool(Player player) { + if (itemInHand.containsKey(player.getName()) && itemInHand.get(player.getName()) != player.getItemInHand().getType()) { + return new CheckResult(Result.FAILED, player.getName() + " switched tools too fast (had " + itemInHand.get(player.getName()) + ", has " + player.getItemInHand().getType() + ")"); + } else { + return PASS; + } + } + + public CheckResult checkSprintDamage(Player player) { + if (isDoing(player, sprinted, magic.SPRINT_MIN)) { + return new CheckResult(Result.FAILED, player.getName() + " sprinted and damaged an entity too fast (min sprint=" + magic.SPRINT_MIN + " ms)"); + } else { + return PASS; + } + } + + public CheckResult checkAnimation(Player player, Entity e) { + if (!justAnimated(player)) { + return new CheckResult(Result.FAILED, player.getName() + " didn't animate before damaging a " + e.getType()); + } else { + return PASS; + } + } + + public CheckResult checkFastHeal(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()); + if ((System.currentTimeMillis() - l) < magic.HEAL_TIME_MIN) { + return new CheckResult(Result.FAILED, player.getName() + " healed too quickly (time=" + (System.currentTimeMillis() - l) + " ms, min=" + magic.HEAL_TIME_MIN + " ms)"); + } + } + return PASS; + } + + public CheckResult checkFastEat(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()); + if ((System.currentTimeMillis() - l) < magic.EAT_TIME_MIN) { + return new CheckResult(Result.FAILED, player.getName() + " ate too quickly (time=" + (System.currentTimeMillis() - l) + " ms, min=" + magic.EAT_TIME_MIN + " ms)"); + } + } + return PASS; + } + + public CheckResult checkFastAnimation(final Player player) { + logAnimation(player); + + String name = player.getName(); + int clicks = animations.containsKey(name) ? animations.get(name) + 1 : 1; + animations.put(name, clicks); + if (clicks == 1) { + animationTime.put(name, System.currentTimeMillis()); + } else if (clicks == magic.ANIMATION_CHECK) { + long time = System.currentTimeMillis() - animationTime.get(name); + animations.put(name, 0); + if (time < magic.ANIMATION_TIMEMIN) { + return new CheckResult(Result.FAILED, player.getName() + " clicked " + clicks + " times in " + time + " ms (max=" + magic.ANIMATION_CHECK + " in " + magic.ANIMATION_TIMEMIN + " ms)"); + } + } + return PASS; + } + + 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 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 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 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); + manager.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(manager.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 resetAnimation(final Player player) { + animated.remove(player.getName()); + blockPunches.put(player.getName(), 0); + } + + private boolean justAnimated(Player player) { + 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 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; + } + } + + public void processChatSpammer(Player player) { + if (chatLevel.get(player.getName()) != null && chatLevel.get(player.getName()) >= magic.CHAT_KICK_LEVEL) { + 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 ? manager.getConfiguration().getConfig().spamKickAction.getValue() : manager.getConfiguration().getConfig().spamBanAction.getValue(); + manager.getUserManager().execute(manager.getUserManager().getUser(player.getName()), Utilities.stringToList(event), CheckType.SPAM, lang.spamKickReason.getValue() + "(" + kick + "/3)", Utilities.stringToList(lang.spamWarning.getValue()), lang.spamBanReason.getValue()); + } + } else { + increment(player, chatLevel, magic.CHAT_KICK_LEVEL); + } + } + + 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 boolean silentMode() { + return manager.getConfiguration().getConfig().silentMode.getValue(); + } +} diff --git a/src/main/java/net/h31ix/anticheat/manage/CheckManager.java b/src/main/java/net/gravitydevelopment/anticheat/manage/CheckManager.java similarity index 94% rename from src/main/java/net/h31ix/anticheat/manage/CheckManager.java rename to src/main/java/net/gravitydevelopment/anticheat/manage/CheckManager.java index 2770506..b982985 100644 --- a/src/main/java/net/h31ix/anticheat/manage/CheckManager.java +++ b/src/main/java/net/gravitydevelopment/anticheat/manage/CheckManager.java @@ -1,211 +1,211 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.manage; - -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - *

- * 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 Configuration config; - 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, Configuration config) { - manager = instance; - this.config = config; - } - - /** - * Turn a check on - * - * @param type The CheckType to enable - */ - public void activateCheck(CheckType type) { - if (isActive(type)) { - manager.log("The " + type.toString() + " check was activated."); - checkIgnoreList.remove(type); - } - } - - /** - * Turn a check off - * - * @param type The CheckType to disable - */ - public void deactivateCheck(CheckType type) { - if (!isActive(type)) { - manager.log("The " + type.toString() + " check was deactivated."); - checkIgnoreList.add(type); - disabled++; - } - } - - /** - * Determine whether a check is enabled - * - * @param type The CheckType to check - * @return true if the check is active - */ - public boolean isActive(CheckType type) { - return !checkIgnoreList.contains(type); - } - - /** - * Exempt a player from a check - * - * @param player The player - * @param type The check - */ - 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++; - } - } - - /** - * Unexempt a player from a check - * - * @param player The player - * @param type The check - */ - 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); - } - } - - /** - * Determine whether a player is exempt from a check - * - * @param player The player - * @param type The check - */ - public boolean isExempt(Player player, CheckType type) { - return exemptList.containsKey(player.getName()) ? exemptList.get(player.getName()).contains(type) : false; - } - - /** - * Determine whether a player is exempt from all checks from op status - * - * @param player The player - */ - public boolean isOpExempt(Player player) { - return (this.manager.getConfiguration().getConfig().exemptOp.getValue() && player.isOp()); - } - - /** - * Determine whether a player should be checked in their world - * - * @param player The player - * @return true if the player's world is enabled - */ - public boolean checkInWorld(Player player) { - return !config.getConfig().exemptedWorlds.getValue().contains(player.getWorld().getName()); - } - - /** - * Run a quick version of the "willCheck" method, using the other non-check-specific methods beforehand - * - * @param player The player to check - * @param type The check being run - * @return true if the check should run - */ - public boolean willCheckQuick(Player player, CheckType type) { - return - isActive(type) - && !isExempt(player, type) - && !type.checkPermission(player); - } - - /** - * Determine whether a check should run on a player - * - * @param player The player to check - * @param type The check being run - * @return true if the check should run - */ - public boolean willCheck(Player player, CheckType type) { - boolean check = isActive(type) - && checkInWorld(player) - && !isExempt(player, type) - && !type.checkPermission(player) - && !isOpExempt(player); - AntiCheat.debugLog("Check " + type + (check ? " run " : " not run ") + "on " + player.getName()); - return check; - } - - /** - * Determine whether a player is actually online; not an NPC - * - * @param player Player to check - * @return true if the player is a real person - */ - 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; - } - - /** - * Get the number of exempt players - * - * @return exempt players - */ - public int getExempt() { - int x = exempt; - exempt = 0; - return x; - } - - /** - * Get the number of disabled checks - * - * @return disabled checks - */ - public int getDisabled() { - int x = disabled; - disabled = 0; - return x; - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.manage; + +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

+ * 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 Configuration config; + 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, Configuration config) { + manager = instance; + this.config = config; + } + + /** + * Turn a check on + * + * @param type The CheckType to enable + */ + public void activateCheck(CheckType type) { + if (isActive(type)) { + manager.log("The " + type.toString() + " check was activated."); + checkIgnoreList.remove(type); + } + } + + /** + * Turn a check off + * + * @param type The CheckType to disable + */ + public void deactivateCheck(CheckType type) { + if (!isActive(type)) { + manager.log("The " + type.toString() + " check was deactivated."); + checkIgnoreList.add(type); + disabled++; + } + } + + /** + * Determine whether a check is enabled + * + * @param type The CheckType to check + * @return true if the check is active + */ + public boolean isActive(CheckType type) { + return !checkIgnoreList.contains(type); + } + + /** + * Exempt a player from a check + * + * @param player The player + * @param type The check + */ + 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++; + } + } + + /** + * Unexempt a player from a check + * + * @param player The player + * @param type The check + */ + 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); + } + } + + /** + * Determine whether a player is exempt from a check + * + * @param player The player + * @param type The check + */ + public boolean isExempt(Player player, CheckType type) { + return exemptList.containsKey(player.getName()) ? exemptList.get(player.getName()).contains(type) : false; + } + + /** + * Determine whether a player is exempt from all checks from op status + * + * @param player The player + */ + public boolean isOpExempt(Player player) { + return (this.manager.getConfiguration().getConfig().exemptOp.getValue() && player.isOp()); + } + + /** + * Determine whether a player should be checked in their world + * + * @param player The player + * @return true if the player's world is enabled + */ + public boolean checkInWorld(Player player) { + return !config.getConfig().exemptedWorlds.getValue().contains(player.getWorld().getName()); + } + + /** + * Run a quick version of the "willCheck" method, using the other non-check-specific methods beforehand + * + * @param player The player to check + * @param type The check being run + * @return true if the check should run + */ + public boolean willCheckQuick(Player player, CheckType type) { + return + isActive(type) + && !isExempt(player, type) + && !type.checkPermission(player); + } + + /** + * Determine whether a check should run on a player + * + * @param player The player to check + * @param type The check being run + * @return true if the check should run + */ + public boolean willCheck(Player player, CheckType type) { + boolean check = isActive(type) + && checkInWorld(player) + && !isExempt(player, type) + && !type.checkPermission(player) + && !isOpExempt(player); + AntiCheat.debugLog("Check " + type + (check ? " run " : " not run ") + "on " + player.getName()); + return check; + } + + /** + * Determine whether a player is actually online; not an NPC + * + * @param player Player to check + * @return true if the player is a real person + */ + 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; + } + + /** + * Get the number of exempt players + * + * @return exempt players + */ + public int getExempt() { + int x = exempt; + exempt = 0; + return x; + } + + /** + * Get the number of disabled checks + * + * @return disabled checks + */ + 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/gravitydevelopment/anticheat/manage/CheckType.java similarity index 93% rename from src/main/java/net/h31ix/anticheat/manage/CheckType.java rename to src/main/java/net/gravitydevelopment/anticheat/manage/CheckType.java index 87bd6f0..6d1d171 100644 --- a/src/main/java/net/h31ix/anticheat/manage/CheckType.java +++ b/src/main/java/net/gravitydevelopment/anticheat/manage/CheckType.java @@ -1,125 +1,125 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.manage; - -import net.h31ix.anticheat.api.CheckFailEvent; -import net.h31ix.anticheat.util.Permission; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.util.HashMap; -import java.util.Map; - -/** - *

- * 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), - FAST_ANIMATION(Permission.CHECK_FASTANIMATION), - AUTOTOOL(Permission.CHECK_AUTOTOOL); - - private final Permission permission; - private final Map level = new HashMap(); - - /** - * Initialize a CheckType - * - * @param perm Permission that applies to this check - */ - private CheckType(Permission perm) { - this.permission = perm; - } - - /** - * Determine whether a player has permission to bypass this check - * - * @param player Player to check - * @return true if the player can bypass - */ - public boolean checkPermission(Player player) { - return permission.get(player); - } - - /** - * Log the failure of this check - * - * @param user User who failed the check - */ - public void logUse(User user) { - int amount = level.get(user.getName()) == null ? 1 : level.get(user.getName()) + 1; - level.put(user.getName(), amount); - Bukkit.getServer().getPluginManager().callEvent(new CheckFailEvent(user, this)); - } - - /** - * Clear failure history of this check for a user - * - * @param name User's name to clear - */ - public void clearUse(String name) { - level.put(name, 0); - } - - /** - * Get how many times a user has failed this check - * - * @param name User's name - * @return number of times failed - */ - public int getUses(String name) { - return level.get(name) != null ? level.get(name) : 0; - } - - /** - * Get the reference name of a check - * - * @param type Type of check - * @return reference name - */ - public static String getName(CheckType type) { - char[] chars = type.toString().replaceAll("_", " ").toLowerCase().toCharArray(); - chars[0] = Character.toUpperCase(chars[0]); - return new String(chars); - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.manage; + +import net.gravitydevelopment.anticheat.api.CheckFailEvent; +import net.gravitydevelopment.anticheat.util.Permission; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; + +/** + *

+ * 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), + FAST_ANIMATION(Permission.CHECK_FASTANIMATION), + AUTOTOOL(Permission.CHECK_AUTOTOOL); + + private final Permission permission; + private final Map level = new HashMap(); + + /** + * Initialize a CheckType + * + * @param perm Permission that applies to this check + */ + private CheckType(Permission perm) { + this.permission = perm; + } + + /** + * Determine whether a player has permission to bypass this check + * + * @param player Player to check + * @return true if the player can bypass + */ + public boolean checkPermission(Player player) { + return permission.get(player); + } + + /** + * Log the failure of this check + * + * @param user User who failed the check + */ + public void logUse(User user) { + int amount = level.get(user.getName()) == null ? 1 : level.get(user.getName()) + 1; + level.put(user.getName(), amount); + Bukkit.getServer().getPluginManager().callEvent(new CheckFailEvent(user, this)); + } + + /** + * Clear failure history of this check for a user + * + * @param name User's name to clear + */ + public void clearUse(String name) { + level.put(name, 0); + } + + /** + * Get how many times a user has failed this check + * + * @param name User's name + * @return number of times failed + */ + public int getUses(String name) { + return level.get(name) != null ? level.get(name) : 0; + } + + /** + * Get the reference name of a check + * + * @param type Type of check + * @return reference name + */ + 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/PacketManager.java b/src/main/java/net/gravitydevelopment/anticheat/manage/PacketManager.java similarity index 91% rename from src/main/java/net/h31ix/anticheat/manage/PacketManager.java rename to src/main/java/net/gravitydevelopment/anticheat/manage/PacketManager.java index 616c444..bd3949d 100644 --- a/src/main/java/net/h31ix/anticheat/manage/PacketManager.java +++ b/src/main/java/net/gravitydevelopment/anticheat/manage/PacketManager.java @@ -1,9 +1,9 @@ -package net.h31ix.anticheat.manage; +package net.gravitydevelopment.anticheat.manage; import com.comphenix.protocol.Packets; import com.comphenix.protocol.ProtocolManager; import com.comphenix.protocol.events.*; -import net.h31ix.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.AntiCheat; public class PacketManager { diff --git a/src/main/java/net/h31ix/anticheat/manage/User.java b/src/main/java/net/gravitydevelopment/anticheat/manage/User.java similarity index 94% rename from src/main/java/net/h31ix/anticheat/manage/User.java rename to src/main/java/net/gravitydevelopment/anticheat/manage/User.java index 2464fb5..586dcce 100644 --- a/src/main/java/net/h31ix/anticheat/manage/User.java +++ b/src/main/java/net/gravitydevelopment/anticheat/manage/User.java @@ -1,346 +1,346 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.manage; - -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.util.Level; -import net.h31ix.anticheat.util.Utilities; -import net.h31ix.anticheat.util.rule.Rule; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.List; - -public class User { - private final String name; - private final int id; - private int level = 0; - private Location goodLocation; - private List inventorySnapshot = null; - private Configuration config = AntiCheat.getManager().getConfiguration(); - private int toX, toY, toZ; - private String[] messages = new String[2]; - private Long[] messageTimes = new Long[2]; - - private boolean isWaitingOnLevelSync; - private Timestamp levelSyncTimestamp; - - /** - * Initialize an AntiCheat user - * - * @param name Player's name - */ - public User(String name) { - this.name = name; - this.id = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getEntityId() : -1; - } - - /** - * Get the player's name - * - * @return Player name - */ - public String getName() { - return name; - } - - /** - * Get the player's entity ID - * - * @return Entity id - */ - public int getId() { - return id; - } - - /** - * Get the Bukkit player - * - * @return Player - */ - public Player getPlayer() { - return Bukkit.getPlayer(name); - } - - /** - * Get the user's level value - * - * @return level - */ - public int getLevel() { - return level; - } - - public Level getNamedLevel() { - List levels = config.getEvents().getLevels(); - for (int i = 0; i < levels.size(); i++) { - if (i == 0 && level < levels.get(i).getValue()) break; - else if (i == levels.size() - 1) return levels.get(i); - else if (level >= levels.get(i).getValue() && level < levels.get(i + 1).getValue()) return levels.get(i); - } - return null; - } - - /** - * Increase the player's level (from failing a check) - * - * @param type The check failed - * @return true if the level was increased - */ - 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 { - if (level < config.getEvents().getHighestLevel()) { - level++; - - // Check levels - for (Level l : getLevels()) { - if (l.getValue() == level) { - AntiCheat.getManager().getUserManager().alert(this, l, type); - if (l.getValue() == config.getEvents().getHighestLevel()) { - level = l.getValue() - 10; - } - } - } - - // Execute rules - for (Rule rule : config.getRules().getRules()) { - rule.check(this, type); - } - return true; - } - return false; - } - } else { - return false; - } - } - - /** - * Decrease the player's level by one value - */ - public void decreaseLevel() { - level = level != 0 ? level - 1 : 0; - } - - /** - * Set the users level to a specific value. Must be 0 < level < config-defined highest level - * - * @param level level to set - * @return true if the level was valid and set properly - */ - public boolean setLevel(int level) { - isWaitingOnLevelSync = false; - if (level >= 0) { - if (level <= config.getEvents().getHighestLevel()) { - this.level = level; - return true; - } else { - this.level = config.getEvents().getHighestLevel(); - return false; - } - } else { - return false; - } - } - - /** - * Reset the user's level to zero and clear all check failures - */ - public void resetLevel() { - level = 0; - for (CheckType type : CheckType.values()) { - type.clearUse(name); - } - } - - /** - * Get the last known valid location of the player for use in resetting - * - * @param location default value to be returned if no known good location exists - * @return last known valid location - */ - public Location getGoodLocation(Location location) { - if (goodLocation == null) { - return location; - } - - return goodLocation; - } - - /** - * Set the last known valid location of the player - * - * @param location location to be set - * @return true if the location was valid and set properly - */ - public boolean setGoodLocation(Location location) { - if (Utilities.cantStandAtExp(location) || (location.getBlock().isLiquid() && !Utilities.isFullyInWater(location))) { - return false; - } - - goodLocation = location; - return true; - } - - /** - * Store a copy of the player's inventory, for use in resetting - * - * @param is ItemStack list to store - */ - public void setInventorySnapshot(ItemStack[] is) { - inventorySnapshot = new ArrayList(); - for (int i = 0; i < is.length; i++) { - if (is[i] != null) { - inventorySnapshot.add(is[i].clone()); - } - } - } - - /** - * Remove the current inventory snapshot - */ - public void removeInventorySnapshot() { - inventorySnapshot = null; - } - - /** - * Restore the player's inventory with the current inventory snapshot - * - * @param inventory Player's inventory - */ - public void restoreInventory(Inventory inventory) { - if (inventorySnapshot != null) { - inventory.clear(); - for (ItemStack is : inventorySnapshot) { - if (is != null) { - inventory.addItem(is); - } - } - } - } - - /** - * Set the player's to location - * - * @param x X value - * @param y Y value - * @param z Z value - */ - public void setTo(double x, double y, double z) { - toX = (int) x; - toY = (int) y; - toZ = (int) z; - } - - /** - * Check if a given to value is the same as the stored value - * - * @param x X value - * @param y Y value - * @param z Z value - * @return true if coordinates are all equal - */ - public boolean checkTo(double x, double y, double z) { - return (int) x == toX && (int) y == toY && (int) z == toZ; - } - - /** - * Log a player's chat message - * - * @param message Message to log - */ - public void addMessage(String message) { - messages[1] = messages[0]; - messages[0] = message; - - messageTimes[1] = messageTimes[0]; - messageTimes[0] = System.currentTimeMillis(); - } - - /** - * Get a stored chat message - * - * @param index Index of the chat in storage - * @return the message - */ - public String getMessage(int index) { - return messages[index]; - } - - /** - * Get the time a message in storage was sent - * - * @param index Index of the chat in storage - * @return time the message was sent - */ - public Long getMessageTime(int index) { - return messageTimes[index]; - } - - /** - * Clear all stored messages - */ - public void clearMessages() { - messages = new String[2]; - messageTimes = new Long[2]; - } - - /** - * Get the time the very last stored message was sent - * - * @return the last message's time - */ - public Long getLastMessageTime() { - return getMessageTime(0) == null ? -1 : getMessageTime(0); - } - - private List getLevels() { - return config.getEvents().getLevels(); - } - - private boolean silentMode() { - return config.getConfig().silentMode.getValue(); - } - - public void setIsWaitingOnLevelSync(boolean b) { - this.isWaitingOnLevelSync = b; - } - - public boolean isWaitingOnLevelSync() { - return isWaitingOnLevelSync; - } - - public void setLevelSyncTimestamp(Timestamp timestamp) { - levelSyncTimestamp = timestamp; - } - - public Timestamp getLevelSyncTimestamp() { - return levelSyncTimestamp; - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.manage; + +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.util.Level; +import net.gravitydevelopment.anticheat.util.Utilities; +import net.gravitydevelopment.anticheat.util.rule.Rule; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +public class User { + private final String name; + private final int id; + private int level = 0; + private Location goodLocation; + private List inventorySnapshot = null; + private Configuration config = AntiCheat.getManager().getConfiguration(); + private int toX, toY, toZ; + private String[] messages = new String[2]; + private Long[] messageTimes = new Long[2]; + + private boolean isWaitingOnLevelSync; + private Timestamp levelSyncTimestamp; + + /** + * Initialize an AntiCheat user + * + * @param name Player's name + */ + public User(String name) { + this.name = name; + this.id = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getEntityId() : -1; + } + + /** + * Get the player's name + * + * @return Player name + */ + public String getName() { + return name; + } + + /** + * Get the player's entity ID + * + * @return Entity id + */ + public int getId() { + return id; + } + + /** + * Get the Bukkit player + * + * @return Player + */ + public Player getPlayer() { + return Bukkit.getPlayer(name); + } + + /** + * Get the user's level value + * + * @return level + */ + public int getLevel() { + return level; + } + + public Level getNamedLevel() { + List levels = config.getEvents().getLevels(); + for (int i = 0; i < levels.size(); i++) { + if (i == 0 && level < levels.get(i).getValue()) break; + else if (i == levels.size() - 1) return levels.get(i); + else if (level >= levels.get(i).getValue() && level < levels.get(i + 1).getValue()) return levels.get(i); + } + return null; + } + + /** + * Increase the player's level (from failing a check) + * + * @param type The check failed + * @return true if the level was increased + */ + 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 { + if (level < config.getEvents().getHighestLevel()) { + level++; + + // Check levels + for (Level l : getLevels()) { + if (l.getValue() == level) { + AntiCheat.getManager().getUserManager().alert(this, l, type); + if (l.getValue() == config.getEvents().getHighestLevel()) { + level = l.getValue() - 10; + } + } + } + + // Execute rules + for (Rule rule : config.getRules().getRules()) { + rule.check(this, type); + } + return true; + } + return false; + } + } else { + return false; + } + } + + /** + * Decrease the player's level by one value + */ + public void decreaseLevel() { + level = level != 0 ? level - 1 : 0; + } + + /** + * Set the users level to a specific value. Must be 0 < level < config-defined highest level + * + * @param level level to set + * @return true if the level was valid and set properly + */ + public boolean setLevel(int level) { + isWaitingOnLevelSync = false; + if (level >= 0) { + if (level <= config.getEvents().getHighestLevel()) { + this.level = level; + return true; + } else { + this.level = config.getEvents().getHighestLevel(); + return false; + } + } else { + return false; + } + } + + /** + * Reset the user's level to zero and clear all check failures + */ + public void resetLevel() { + level = 0; + for (CheckType type : CheckType.values()) { + type.clearUse(name); + } + } + + /** + * Get the last known valid location of the player for use in resetting + * + * @param location default value to be returned if no known good location exists + * @return last known valid location + */ + public Location getGoodLocation(Location location) { + if (goodLocation == null) { + return location; + } + + return goodLocation; + } + + /** + * Set the last known valid location of the player + * + * @param location location to be set + * @return true if the location was valid and set properly + */ + public boolean setGoodLocation(Location location) { + if (Utilities.cantStandAtExp(location) || (location.getBlock().isLiquid() && !Utilities.isFullyInWater(location))) { + return false; + } + + goodLocation = location; + return true; + } + + /** + * Store a copy of the player's inventory, for use in resetting + * + * @param is ItemStack list to store + */ + public void setInventorySnapshot(ItemStack[] is) { + inventorySnapshot = new ArrayList(); + for (int i = 0; i < is.length; i++) { + if (is[i] != null) { + inventorySnapshot.add(is[i].clone()); + } + } + } + + /** + * Remove the current inventory snapshot + */ + public void removeInventorySnapshot() { + inventorySnapshot = null; + } + + /** + * Restore the player's inventory with the current inventory snapshot + * + * @param inventory Player's inventory + */ + public void restoreInventory(Inventory inventory) { + if (inventorySnapshot != null) { + inventory.clear(); + for (ItemStack is : inventorySnapshot) { + if (is != null) { + inventory.addItem(is); + } + } + } + } + + /** + * Set the player's to location + * + * @param x X value + * @param y Y value + * @param z Z value + */ + public void setTo(double x, double y, double z) { + toX = (int) x; + toY = (int) y; + toZ = (int) z; + } + + /** + * Check if a given to value is the same as the stored value + * + * @param x X value + * @param y Y value + * @param z Z value + * @return true if coordinates are all equal + */ + public boolean checkTo(double x, double y, double z) { + return (int) x == toX && (int) y == toY && (int) z == toZ; + } + + /** + * Log a player's chat message + * + * @param message Message to log + */ + public void addMessage(String message) { + messages[1] = messages[0]; + messages[0] = message; + + messageTimes[1] = messageTimes[0]; + messageTimes[0] = System.currentTimeMillis(); + } + + /** + * Get a stored chat message + * + * @param index Index of the chat in storage + * @return the message + */ + public String getMessage(int index) { + return messages[index]; + } + + /** + * Get the time a message in storage was sent + * + * @param index Index of the chat in storage + * @return time the message was sent + */ + public Long getMessageTime(int index) { + return messageTimes[index]; + } + + /** + * Clear all stored messages + */ + public void clearMessages() { + messages = new String[2]; + messageTimes = new Long[2]; + } + + /** + * Get the time the very last stored message was sent + * + * @return the last message's time + */ + public Long getLastMessageTime() { + return getMessageTime(0) == null ? -1 : getMessageTime(0); + } + + private List getLevels() { + return config.getEvents().getLevels(); + } + + private boolean silentMode() { + return config.getConfig().silentMode.getValue(); + } + + public void setIsWaitingOnLevelSync(boolean b) { + this.isWaitingOnLevelSync = b; + } + + public boolean isWaitingOnLevelSync() { + return isWaitingOnLevelSync; + } + + public void setLevelSyncTimestamp(Timestamp timestamp) { + levelSyncTimestamp = timestamp; + } + + public Timestamp getLevelSyncTimestamp() { + return levelSyncTimestamp; + } +} diff --git a/src/main/java/net/h31ix/anticheat/manage/UserManager.java b/src/main/java/net/gravitydevelopment/anticheat/manage/UserManager.java similarity index 94% rename from src/main/java/net/h31ix/anticheat/manage/UserManager.java rename to src/main/java/net/gravitydevelopment/anticheat/manage/UserManager.java index 6eb5694..b40d9a8 100644 --- a/src/main/java/net/h31ix/anticheat/manage/UserManager.java +++ b/src/main/java/net/gravitydevelopment/anticheat/manage/UserManager.java @@ -1,229 +1,229 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.manage; - -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.util.Level; -import net.h31ix.anticheat.util.Utilities; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; - -import java.util.ArrayList; -import java.util.List; - -public class UserManager { - private List users = new ArrayList(); - private static Configuration config; - 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; - private static List alert; - - /** - * Initialize the user manager with a given configuration - * - * @param conf Configuration to use - */ - public UserManager(Configuration conf) { - config = conf; - alert = config.getLang().alert.getValue(); - } - - /** - * Get a user with the given name - * - * @param name Name - * @return User with name - */ - public User getUser(String name) { - for (User user : users) { - if (user.getName().equalsIgnoreCase(name)) { - return user; - } - } - // Otherwise try to load them - User user = new User(name); - user.setIsWaitingOnLevelSync(true); - config.getLevels().loadLevelToUser(user); - return user; - } - - /** - * Get all users - * - * @return List of users - */ - public List getUsers() { - return users; - } - - /** - * Add a user to the list - * - * @param user User to add - */ - public void addUser(User user) { - users.add(user); - } - - /** - * Remove a user from the list - * - * @param user User to remove - */ - public void remove(User user) { - users.remove(user); - } - - /** - * Save a user's level - * - * @param user User to save - */ - public void saveLevel(User user) { - config.getLevels().saveLevelFromUser(user); - } - - /** - * Get a user's level, or 0 if the player isn't found - * - * @param name Name of the player - * @return player level - */ - public int safeGetLevel(String name) { - User user = getUser(name); - if (user == null) { - return 0; - } else { - return user.getLevel(); - } - } - - /** - * Set a user's level - * - * @param name Name of the player - * @param level Level to set - */ - public void safeSetLevel(String name, int level) { - User user = getUser(name); - if (user != null) { - user.setLevel(level); - } - } - - /** - * Reset a user - * - * @param name Name of the user - */ - public void safeReset(String name) { - User user = getUser(name); - if (user != null) { - user.resetLevel(); - } - } - - /** - * Fire an alert - * - * @param user The user to alert - * @param level The user's level - * @param type The CheckType that triggered the alert - */ - public void alert(User user, Level level, CheckType type) { - ArrayList messageArray = new ArrayList(); - for (int i = 0; i < alert.size(); i++) { - String message = alert.get(i); - if (!message.equals("")) { - message = message.replaceAll("&player", GOLD + user.getName() + GRAY); - message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY); - message = message.replaceAll("&level", level.getColor() + level.getName() + GRAY); - messageArray.add(message); - } - } - Utilities.alert(messageArray); - execute(user, level.getActions(), type); - } - - /** - * Execute configuration actions for an alert - * - * @param user The user - * @param actions The list of actions to execute - * @param type The CheckType that triggered the alert - */ - public void execute(User user, List actions, CheckType type) { - execute(user, actions, type, config.getLang().kickReason.getValue(), config.getLang().playerWarning.getValue(), config.getLang().banReason.getValue()); - } - - /** - * Execute configuration actions for an alert - * - * @param user The user - * @param actions The list of actions to execute - * @param type The CheckType that triggered the alert - * @param kickReason The config's kick reason - * @param warning The config's warning format - * @param banReason The config's ban reason - */ - public void execute(final User user, final List actions, final CheckType type, final String kickReason, final List warning, final String banReason) { - // Execute synchronously for thread safety when called from AsyncPlayerChatEvent - Bukkit.getScheduler().scheduleSyncDelayedTask(AntiCheat.getPlugin(), new Runnable() { - @Override - public void run() { - final String name = user.getName(); - for (String event : actions) { - event = event.replaceAll("&player", name).replaceAll("&world", user.getPlayer().getWorld().getName()).replaceAll("&check", type.name()); - - if (event.startsWith("COMMAND[")) { - for (String cmd : Utilities.getCommands(event)) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); - } - } else if (event.equalsIgnoreCase("KICK")) { - user.getPlayer().kickPlayer(RED + kickReason); - String msg = RED + config.getLang().kickBroadcast.getValue().replaceAll("&player", name); - if (!msg.equals("")) { - Bukkit.broadcastMessage(msg); - } - } else if (event.equalsIgnoreCase("WARN")) { - List message = warning; - for (String string : message) { - if (!string.equals("")) { - user.getPlayer().sendMessage(RED + string); - } - } - } else if (event.equalsIgnoreCase("BAN")) { - user.getPlayer().setBanned(true); - user.getPlayer().kickPlayer(RED + banReason); - String msg = RED + config.getLang().banBroadcast.getValue().replaceAll("&player", name); - if (!msg.equals("")) { - Bukkit.broadcastMessage(msg); - } - } else if (event.equalsIgnoreCase("RESET")) { - user.resetLevel(); - } - } - } - }); - } - -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.manage; + +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.util.Level; +import net.gravitydevelopment.anticheat.util.Utilities; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; + +import java.util.ArrayList; +import java.util.List; + +public class UserManager { + private List users = new ArrayList(); + private static Configuration config; + 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; + private static List alert; + + /** + * Initialize the user manager with a given configuration + * + * @param conf Configuration to use + */ + public UserManager(Configuration conf) { + config = conf; + alert = config.getLang().alert.getValue(); + } + + /** + * Get a user with the given name + * + * @param name Name + * @return User with name + */ + public User getUser(String name) { + for (User user : users) { + if (user.getName().equalsIgnoreCase(name)) { + return user; + } + } + // Otherwise try to load them + User user = new User(name); + user.setIsWaitingOnLevelSync(true); + config.getLevels().loadLevelToUser(user); + return user; + } + + /** + * Get all users + * + * @return List of users + */ + public List getUsers() { + return users; + } + + /** + * Add a user to the list + * + * @param user User to add + */ + public void addUser(User user) { + users.add(user); + } + + /** + * Remove a user from the list + * + * @param user User to remove + */ + public void remove(User user) { + users.remove(user); + } + + /** + * Save a user's level + * + * @param user User to save + */ + public void saveLevel(User user) { + config.getLevels().saveLevelFromUser(user); + } + + /** + * Get a user's level, or 0 if the player isn't found + * + * @param name Name of the player + * @return player level + */ + public int safeGetLevel(String name) { + User user = getUser(name); + if (user == null) { + return 0; + } else { + return user.getLevel(); + } + } + + /** + * Set a user's level + * + * @param name Name of the player + * @param level Level to set + */ + public void safeSetLevel(String name, int level) { + User user = getUser(name); + if (user != null) { + user.setLevel(level); + } + } + + /** + * Reset a user + * + * @param name Name of the user + */ + public void safeReset(String name) { + User user = getUser(name); + if (user != null) { + user.resetLevel(); + } + } + + /** + * Fire an alert + * + * @param user The user to alert + * @param level The user's level + * @param type The CheckType that triggered the alert + */ + public void alert(User user, Level level, CheckType type) { + ArrayList messageArray = new ArrayList(); + for (int i = 0; i < alert.size(); i++) { + String message = alert.get(i); + if (!message.equals("")) { + message = message.replaceAll("&player", GOLD + user.getName() + GRAY); + message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY); + message = message.replaceAll("&level", level.getColor() + level.getName() + GRAY); + messageArray.add(message); + } + } + Utilities.alert(messageArray); + execute(user, level.getActions(), type); + } + + /** + * Execute configuration actions for an alert + * + * @param user The user + * @param actions The list of actions to execute + * @param type The CheckType that triggered the alert + */ + public void execute(User user, List actions, CheckType type) { + execute(user, actions, type, config.getLang().kickReason.getValue(), config.getLang().playerWarning.getValue(), config.getLang().banReason.getValue()); + } + + /** + * Execute configuration actions for an alert + * + * @param user The user + * @param actions The list of actions to execute + * @param type The CheckType that triggered the alert + * @param kickReason The config's kick reason + * @param warning The config's warning format + * @param banReason The config's ban reason + */ + public void execute(final User user, final List actions, final CheckType type, final String kickReason, final List warning, final String banReason) { + // Execute synchronously for thread safety when called from AsyncPlayerChatEvent + Bukkit.getScheduler().scheduleSyncDelayedTask(AntiCheat.getPlugin(), new Runnable() { + @Override + public void run() { + final String name = user.getName(); + for (String event : actions) { + event = event.replaceAll("&player", name).replaceAll("&world", user.getPlayer().getWorld().getName()).replaceAll("&check", type.name()); + + if (event.startsWith("COMMAND[")) { + for (String cmd : Utilities.getCommands(event)) { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); + } + } else if (event.equalsIgnoreCase("KICK")) { + user.getPlayer().kickPlayer(RED + kickReason); + String msg = RED + config.getLang().kickBroadcast.getValue().replaceAll("&player", name); + if (!msg.equals("")) { + Bukkit.broadcastMessage(msg); + } + } else if (event.equalsIgnoreCase("WARN")) { + List message = warning; + for (String string : message) { + if (!string.equals("")) { + user.getPlayer().sendMessage(RED + string); + } + } + } else if (event.equalsIgnoreCase("BAN")) { + user.getPlayer().setBanned(true); + user.getPlayer().kickPlayer(RED + banReason); + String msg = RED + config.getLang().banBroadcast.getValue().replaceAll("&player", name); + if (!msg.equals("")) { + Bukkit.broadcastMessage(msg); + } + } else if (event.equalsIgnoreCase("RESET")) { + user.resetLevel(); + } + } + } + }); + } + +} diff --git a/src/main/java/net/h31ix/anticheat/update/Updater.java b/src/main/java/net/gravitydevelopment/anticheat/update/Updater.java similarity index 97% rename from src/main/java/net/h31ix/anticheat/update/Updater.java rename to src/main/java/net/gravitydevelopment/anticheat/update/Updater.java index 3f99c9b..b6e087f 100644 --- a/src/main/java/net/h31ix/anticheat/update/Updater.java +++ b/src/main/java/net/gravitydevelopment/anticheat/update/Updater.java @@ -1,515 +1,515 @@ -/* - * Updater for Bukkit. - * - * This class provides the means to safely and easily update a plugin, or check to see if it is updated using dev.bukkit.org - */ - -package net.h31ix.anticheat.update; - -import java.io.*; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.JSONValue; - -/** - * 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. - *

- * 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 Gravity - * @version 2.0 - */ - -public class Updater { - - private Plugin plugin; - private UpdateType type; - private String versionName; - private String versionLink; - private String versionType; - private String versionGameVersion; - - private boolean announce; // Whether to announce file downloads - - private URL url; // Connecting to RSS - private File file; // The plugin's file - private Thread thread; // Updater thread - - private int id = -1; // Project's Curse ID - private String apiKey = null; // BukkitDev ServerMods API key - private static final String TITLE_VALUE = "name"; // Gets remote file's title - private static final String LINK_VALUE = "downloadUrl"; // Gets remote file's download link - private static final String TYPE_VALUE = "releaseType"; // Gets remote file's release type - private static final String VERSION_VALUE = "gameVersion"; // Gets remote file's build version - private static final String QUERY = "/servermods/files?projectIds="; // Path to GET - private static final String HOST = "https://api.curseforge.com"; // Slugs will be appended to this to get to the project's RSS feed - - private static final String[] NO_UPDATE_TAG = { "-DEV", "-PRE", "-SNAPSHOT" }; // If the version number contains one of these, don't update. - private static final int BYTE_SIZE = 1024; // Used for downloading files - private YamlConfiguration config; // Config file - private String updateFolder;// The folder that downloads will be placed in - private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process - - /** - * 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, - /** - * The updater did not find an update, and nothing was downloaded. - */ - NO_UPDATE, - /** - * The server administrator has disabled the updating system - */ - DISABLED, - /** - * The updater found an update, but was unable to download it. - */ - FAIL_DOWNLOAD, - /** - * For some reason, the updater was unable to contact dev.bukkit.org to download the file. - */ - FAIL_DBO, - /** - * 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, - /** - * The id provided by the plugin running the updater was invalid and doesn't exist on DBO. - */ - FAIL_BADID, - /** - * The server administrator has improperly configured their API key in the configuration - */ - FAIL_APIKEY, - /** - * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded. - */ - UPDATE_AVAILABLE - } - - /** - * 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, - /** - * Don't run a version check, just find the latest update and download it. - */ - NO_VERSION_CHECK, - /** - * Get information about the version and the download size, but don't actually download anything. - */ - NO_DOWNLOAD - } - - /** - * Initialize the updater - * - * @param plugin The plugin that is checking for an update. - * @param id The dev.bukkit.org id of the project - * @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, int id, File file, UpdateType type, boolean announce) { - this.plugin = plugin; - this.type = type; - this.announce = announce; - this.file = file; - this.id = id; - this.updateFolder = plugin.getServer().getUpdateFolder(); - - final File pluginFile = plugin.getDataFolder().getParentFile(); - final File updaterFile = new File(pluginFile, "Updater"); - final File updaterConfigFile = new File(updaterFile, "config.yml"); - - if (!updaterFile.exists()) { - updaterFile.mkdir(); - } - if (!updaterConfigFile.exists()) { - try { - updaterConfigFile.createNewFile(); - } catch (final IOException e) { - plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath()); - e.printStackTrace(); - } - } - this.config = YamlConfiguration.loadConfiguration(updaterConfigFile); - - this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' - + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' - + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); - this.config.addDefault("api-key", "PUT_API_KEY_HERE"); - this.config.addDefault("disable", false); - - if (this.config.get("api-key", null) == null) { - this.config.options().copyDefaults(true); - try { - this.config.save(updaterConfigFile); - } catch (final IOException e) { - plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath()); - e.printStackTrace(); - } - } - - if (this.config.getBoolean("disable")) { - this.result = UpdateResult.DISABLED; - return; - } - - String key = this.config.getString("api-key"); - if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { - key = null; - } - - this.apiKey = key; - - try { - this.url = new URL(Updater.HOST + Updater.QUERY + id); - } catch (final MalformedURLException e) { - plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid."); - this.result = UpdateResult.FAIL_BADID; - e.printStackTrace(); - } - - this.thread = new Thread(new UpdateRunnable()); - this.thread.start(); - } - - /** - * Get the result of the update process. - */ - public Updater.UpdateResult getResult() { - this.waitForThread(); - return this.result; - } - - /** - * Get the latest version's release type (release, beta, or alpha). - */ - public String getLatestType() { - this.waitForThread(); - return this.versionType; - } - - /** - * Get the latest version's game version. - */ - public String getLatestGameVersion() { - this.waitForThread(); - return this.versionGameVersion; - } - - /** - * Get the latest version's name. - */ - public String getLatestName() { - this.waitForThread(); - return this.versionName; - } - - /** - * Get the latest version's file link. - */ - public String getLatestFileLink() { - this.waitForThread(); - return this.versionLink; - } - - /** - * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish - * before allowing anyone to check the result. - */ - private void waitForThread() { - if ((this.thread != null) && this.thread.isAlive()) { - try { - this.thread.join(); - } catch (final InterruptedException e) { - e.printStackTrace(); - } - } - } - - /** - * 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 - final URL url = new URL(u); - final int fileLength = url.openConnection().getContentLength(); - in = new BufferedInputStream(url.openStream()); - fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file); - - final byte[] data = new byte[Updater.BYTE_SIZE]; - int count; - if (this.announce) { - this.plugin.getLogger().info("About to download a new update: " + this.versionName); - } - long downloaded = 0; - while ((count = in.read(data, 0, Updater.BYTE_SIZE)) != -1) { - downloaded += count; - fout.write(data, 0, count); - final int percent = (int) ((downloaded * 100) / fileLength); - if (this.announce && ((percent % 10) == 0)) { - this.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 (final File xFile : new File(this.plugin.getDataFolder().getParent(), this.updateFolder).listFiles()) { - if (xFile.getName().endsWith(".zip")) { - xFile.delete(); - } - } - // Check to see if it's a zip file, if it is, unzip it. - final File dFile = new File(folder.getAbsolutePath() + "/" + file); - if (dFile.getName().endsWith(".zip")) { - // Unzip - this.unzip(dFile.getCanonicalPath()); - } - if (this.announce) { - this.plugin.getLogger().info("Finished updating."); - } - } catch (final Exception ex) { - this.plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); - this.result = Updater.UpdateResult.FAIL_DOWNLOAD; - } finally { - try { - if (in != null) { - in.close(); - } - if (fout != null) { - fout.close(); - } - } catch (final Exception ex) { - } - } - } - - /** - * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit - */ - private void unzip(String file) { - try { - final File fSourceZip = new File(file); - final String zipPath = file.substring(0, file.length() - 4); - ZipFile zipFile = new ZipFile(fSourceZip); - Enumeration e = zipFile.entries(); - while (e.hasMoreElements()) { - ZipEntry entry = e.nextElement(); - File destinationFilePath = new File(zipPath, entry.getName()); - destinationFilePath.getParentFile().mkdirs(); - if (entry.isDirectory()) { - continue; - } else { - final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); - int b; - final byte buffer[] = new byte[Updater.BYTE_SIZE]; - final FileOutputStream fos = new FileOutputStream(destinationFilePath); - final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); - while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { - bos.write(buffer, 0, b); - } - bos.flush(); - bos.close(); - bis.close(); - final String name = destinationFilePath.getName(); - if (name.endsWith(".jar") && this.pluginFile(name)) { - destinationFilePath.renameTo(new File(this.plugin.getDataFolder().getParent(), this.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 (final File dFile : new File(zipPath).listFiles()) { - if (dFile.isDirectory()) { - if (this.pluginFile(dFile.getName())) { - final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir - final File[] contents = oFile.listFiles(); // List of existing files in the current dir - for (final File cFile : dFile.listFiles()) // Loop through all the files in the new dir - { - boolean found = false; - for (final 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 (final IOException ex) { - this.plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); - this.result = Updater.UpdateResult.FAIL_DOWNLOAD; - ex.printStackTrace(); - } - 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. - */ - private boolean pluginFile(String name) { - for (final File file : new File("plugins").listFiles()) { - if (file.getName().equals(name)) { - return true; - } - } - return false; - } - - /** - * 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 (this.type != UpdateType.NO_VERSION_CHECK) { - final String version = this.plugin.getDescription().getVersion(); - if (title.split(" v").length == 2) { - final String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number - - if (this.hasTag(version) || version.equalsIgnoreCase(remoteVersion)) { - // We already have the latest version, or this build is tagged for no-update - this.result = Updater.UpdateResult.NO_UPDATE; - return false; - } - } else { - // The file's name did not contain the string 'vVersion' - final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; - this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); - this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); - this.plugin.getLogger().warning("Please notify the author of this error."); - this.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) { - for (final String string : Updater.NO_UPDATE_TAG) { - if (version.contains(string)) { - return true; - } - } - return false; - } - - private boolean read() { - try { - final URLConnection conn = this.url.openConnection(); - conn.setConnectTimeout(5000); - - if (this.apiKey != null) { - conn.addRequestProperty("X-API-Key", this.apiKey); - } - conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); - - conn.setDoOutput(true); - - final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); - final String response = reader.readLine(); - - final JSONArray array = (JSONArray) JSONValue.parse(response); - - if (array.size() == 0) { - this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); - this.result = UpdateResult.FAIL_BADID; - return false; - } - - this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); - this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); - this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); - this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE); - - return true; - } catch (final IOException e) { - if (e.getMessage().contains("HTTP response code: 403")) { - this.plugin.getLogger().warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); - this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct."); - this.result = UpdateResult.FAIL_APIKEY; - } else { - this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); - this.plugin.getLogger().warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); - this.result = UpdateResult.FAIL_DBO; - } - e.printStackTrace(); - return false; - } - } - - private class UpdateRunnable implements Runnable { - - @Override - public void run() { - if (Updater.this.url != null) { - // Obtain the results of the project's file feed - if (Updater.this.read()) { - if (Updater.this.versionCheck(Updater.this.versionName)) { - if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) { - String name = Updater.this.file.getName(); - // If it's a zip file, it shouldn't be downloaded as the plugin's name - if (Updater.this.versionLink.endsWith(".zip")) { - final String[] split = Updater.this.versionLink.split("/"); - name = split[split.length - 1]; - } - Updater.this.saveFile(new File(Updater.this.plugin.getDataFolder().getParent(), Updater.this.updateFolder), name, Updater.this.versionLink); - } else { - Updater.this.result = UpdateResult.UPDATE_AVAILABLE; - } - } - } - } - } - } -} +/* + * Updater for Bukkit. + * + * This class provides the means to safely and easily update a plugin, or check to see if it is updated using dev.bukkit.org + */ + +package net.gravitydevelopment.anticheat.update; + +import java.io.*; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; + +/** + * 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. + *

+ * 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 Gravity + * @version 2.0 + */ + +public class Updater { + + private Plugin plugin; + private UpdateType type; + private String versionName; + private String versionLink; + private String versionType; + private String versionGameVersion; + + private boolean announce; // Whether to announce file downloads + + private URL url; // Connecting to RSS + private File file; // The plugin's file + private Thread thread; // Updater thread + + private int id = -1; // Project's Curse ID + private String apiKey = null; // BukkitDev ServerMods API key + private static final String TITLE_VALUE = "name"; // Gets remote file's title + private static final String LINK_VALUE = "downloadUrl"; // Gets remote file's download link + private static final String TYPE_VALUE = "releaseType"; // Gets remote file's release type + private static final String VERSION_VALUE = "gameVersion"; // Gets remote file's build version + private static final String QUERY = "/servermods/files?projectIds="; // Path to GET + private static final String HOST = "https://api.curseforge.com"; // Slugs will be appended to this to get to the project's RSS feed + + private static final String[] NO_UPDATE_TAG = { "-DEV", "-PRE", "-SNAPSHOT" }; // If the version number contains one of these, don't update. + private static final int BYTE_SIZE = 1024; // Used for downloading files + private YamlConfiguration config; // Config file + private String updateFolder;// The folder that downloads will be placed in + private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process + + /** + * 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, + /** + * The updater did not find an update, and nothing was downloaded. + */ + NO_UPDATE, + /** + * The server administrator has disabled the updating system + */ + DISABLED, + /** + * The updater found an update, but was unable to download it. + */ + FAIL_DOWNLOAD, + /** + * For some reason, the updater was unable to contact dev.bukkit.org to download the file. + */ + FAIL_DBO, + /** + * 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, + /** + * The id provided by the plugin running the updater was invalid and doesn't exist on DBO. + */ + FAIL_BADID, + /** + * The server administrator has improperly configured their API key in the configuration + */ + FAIL_APIKEY, + /** + * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded. + */ + UPDATE_AVAILABLE + } + + /** + * 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, + /** + * Don't run a version check, just find the latest update and download it. + */ + NO_VERSION_CHECK, + /** + * Get information about the version and the download size, but don't actually download anything. + */ + NO_DOWNLOAD + } + + /** + * Initialize the updater + * + * @param plugin The plugin that is checking for an update. + * @param id The dev.bukkit.org id of the project + * @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, int id, File file, UpdateType type, boolean announce) { + this.plugin = plugin; + this.type = type; + this.announce = announce; + this.file = file; + this.id = id; + this.updateFolder = plugin.getServer().getUpdateFolder(); + + final File pluginFile = plugin.getDataFolder().getParentFile(); + final File updaterFile = new File(pluginFile, "Updater"); + final File updaterConfigFile = new File(updaterFile, "config.yml"); + + if (!updaterFile.exists()) { + updaterFile.mkdir(); + } + if (!updaterConfigFile.exists()) { + try { + updaterConfigFile.createNewFile(); + } catch (final IOException e) { + plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath()); + e.printStackTrace(); + } + } + this.config = YamlConfiguration.loadConfiguration(updaterConfigFile); + + this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' + + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' + + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); + this.config.addDefault("api-key", "PUT_API_KEY_HERE"); + this.config.addDefault("disable", false); + + if (this.config.get("api-key", null) == null) { + this.config.options().copyDefaults(true); + try { + this.config.save(updaterConfigFile); + } catch (final IOException e) { + plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath()); + e.printStackTrace(); + } + } + + if (this.config.getBoolean("disable")) { + this.result = UpdateResult.DISABLED; + return; + } + + String key = this.config.getString("api-key"); + if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { + key = null; + } + + this.apiKey = key; + + try { + this.url = new URL(Updater.HOST + Updater.QUERY + id); + } catch (final MalformedURLException e) { + plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid."); + this.result = UpdateResult.FAIL_BADID; + e.printStackTrace(); + } + + this.thread = new Thread(new UpdateRunnable()); + this.thread.start(); + } + + /** + * Get the result of the update process. + */ + public Updater.UpdateResult getResult() { + this.waitForThread(); + return this.result; + } + + /** + * Get the latest version's release type (release, beta, or alpha). + */ + public String getLatestType() { + this.waitForThread(); + return this.versionType; + } + + /** + * Get the latest version's game version. + */ + public String getLatestGameVersion() { + this.waitForThread(); + return this.versionGameVersion; + } + + /** + * Get the latest version's name. + */ + public String getLatestName() { + this.waitForThread(); + return this.versionName; + } + + /** + * Get the latest version's file link. + */ + public String getLatestFileLink() { + this.waitForThread(); + return this.versionLink; + } + + /** + * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish + * before allowing anyone to check the result. + */ + private void waitForThread() { + if ((this.thread != null) && this.thread.isAlive()) { + try { + this.thread.join(); + } catch (final InterruptedException e) { + e.printStackTrace(); + } + } + } + + /** + * 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 + final URL url = new URL(u); + final int fileLength = url.openConnection().getContentLength(); + in = new BufferedInputStream(url.openStream()); + fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file); + + final byte[] data = new byte[Updater.BYTE_SIZE]; + int count; + if (this.announce) { + this.plugin.getLogger().info("About to download a new update: " + this.versionName); + } + long downloaded = 0; + while ((count = in.read(data, 0, Updater.BYTE_SIZE)) != -1) { + downloaded += count; + fout.write(data, 0, count); + final int percent = (int) ((downloaded * 100) / fileLength); + if (this.announce && ((percent % 10) == 0)) { + this.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 (final File xFile : new File(this.plugin.getDataFolder().getParent(), this.updateFolder).listFiles()) { + if (xFile.getName().endsWith(".zip")) { + xFile.delete(); + } + } + // Check to see if it's a zip file, if it is, unzip it. + final File dFile = new File(folder.getAbsolutePath() + "/" + file); + if (dFile.getName().endsWith(".zip")) { + // Unzip + this.unzip(dFile.getCanonicalPath()); + } + if (this.announce) { + this.plugin.getLogger().info("Finished updating."); + } + } catch (final Exception ex) { + this.plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); + this.result = Updater.UpdateResult.FAIL_DOWNLOAD; + } finally { + try { + if (in != null) { + in.close(); + } + if (fout != null) { + fout.close(); + } + } catch (final Exception ex) { + } + } + } + + /** + * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit + */ + private void unzip(String file) { + try { + final File fSourceZip = new File(file); + final String zipPath = file.substring(0, file.length() - 4); + ZipFile zipFile = new ZipFile(fSourceZip); + Enumeration e = zipFile.entries(); + while (e.hasMoreElements()) { + ZipEntry entry = e.nextElement(); + File destinationFilePath = new File(zipPath, entry.getName()); + destinationFilePath.getParentFile().mkdirs(); + if (entry.isDirectory()) { + continue; + } else { + final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); + int b; + final byte buffer[] = new byte[Updater.BYTE_SIZE]; + final FileOutputStream fos = new FileOutputStream(destinationFilePath); + final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); + while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { + bos.write(buffer, 0, b); + } + bos.flush(); + bos.close(); + bis.close(); + final String name = destinationFilePath.getName(); + if (name.endsWith(".jar") && this.pluginFile(name)) { + destinationFilePath.renameTo(new File(this.plugin.getDataFolder().getParent(), this.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 (final File dFile : new File(zipPath).listFiles()) { + if (dFile.isDirectory()) { + if (this.pluginFile(dFile.getName())) { + final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir + final File[] contents = oFile.listFiles(); // List of existing files in the current dir + for (final File cFile : dFile.listFiles()) // Loop through all the files in the new dir + { + boolean found = false; + for (final 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 (final IOException ex) { + this.plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); + this.result = Updater.UpdateResult.FAIL_DOWNLOAD; + ex.printStackTrace(); + } + 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. + */ + private boolean pluginFile(String name) { + for (final File file : new File("plugins").listFiles()) { + if (file.getName().equals(name)) { + return true; + } + } + return false; + } + + /** + * 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 (this.type != UpdateType.NO_VERSION_CHECK) { + final String version = this.plugin.getDescription().getVersion(); + if (title.split(" v").length == 2) { + final String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number + + if (this.hasTag(version) || version.equalsIgnoreCase(remoteVersion)) { + // We already have the latest version, or this build is tagged for no-update + this.result = Updater.UpdateResult.NO_UPDATE; + return false; + } + } else { + // The file's name did not contain the string 'vVersion' + final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; + this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); + this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); + this.plugin.getLogger().warning("Please notify the author of this error."); + this.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) { + for (final String string : Updater.NO_UPDATE_TAG) { + if (version.contains(string)) { + return true; + } + } + return false; + } + + private boolean read() { + try { + final URLConnection conn = this.url.openConnection(); + conn.setConnectTimeout(5000); + + if (this.apiKey != null) { + conn.addRequestProperty("X-API-Key", this.apiKey); + } + conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); + + conn.setDoOutput(true); + + final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + final String response = reader.readLine(); + + final JSONArray array = (JSONArray) JSONValue.parse(response); + + if (array.size() == 0) { + this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); + this.result = UpdateResult.FAIL_BADID; + return false; + } + + this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); + this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); + this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); + this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE); + + return true; + } catch (final IOException e) { + if (e.getMessage().contains("HTTP response code: 403")) { + this.plugin.getLogger().warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); + this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct."); + this.result = UpdateResult.FAIL_APIKEY; + } else { + this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); + this.plugin.getLogger().warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); + this.result = UpdateResult.FAIL_DBO; + } + e.printStackTrace(); + return false; + } + } + + private class UpdateRunnable implements Runnable { + + @Override + public void run() { + if (Updater.this.url != null) { + // Obtain the results of the project's file feed + if (Updater.this.read()) { + if (Updater.this.versionCheck(Updater.this.versionName)) { + if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) { + String name = Updater.this.file.getName(); + // If it's a zip file, it shouldn't be downloaded as the plugin's name + if (Updater.this.versionLink.endsWith(".zip")) { + final String[] split = Updater.this.versionLink.split("/"); + name = split[split.length - 1]; + } + Updater.this.saveFile(new File(Updater.this.plugin.getDataFolder().getParent(), Updater.this.updateFolder), name, Updater.this.versionLink); + } else { + Updater.this.result = UpdateResult.UPDATE_AVAILABLE; + } + } + } + } + } + } +} diff --git a/src/main/java/net/h31ix/anticheat/util/BlockHardness.java b/src/main/java/net/gravitydevelopment/anticheat/util/BlockHardness.java similarity index 99% rename from src/main/java/net/h31ix/anticheat/util/BlockHardness.java rename to src/main/java/net/gravitydevelopment/anticheat/util/BlockHardness.java index 5d68e2f..420fdf2 100644 --- a/src/main/java/net/h31ix/anticheat/util/BlockHardness.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/BlockHardness.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.util; +package net.gravitydevelopment.anticheat.util; import org.bukkit.Material; diff --git a/src/main/java/net/h31ix/anticheat/util/Calibrator.java b/src/main/java/net/gravitydevelopment/anticheat/util/Calibrator.java similarity index 96% rename from src/main/java/net/h31ix/anticheat/util/Calibrator.java rename to src/main/java/net/gravitydevelopment/anticheat/util/Calibrator.java index 8e18001..8f4e196 100644 --- a/src/main/java/net/h31ix/anticheat/util/Calibrator.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/Calibrator.java @@ -1,239 +1,239 @@ -// Not production code yet. Still experimental and needs a lot of work. - -package net.h31ix.anticheat.util; - -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.entity.EntityShootBowEvent; -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 < 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; - } - } - } - } -} +// Not production code yet. Still experimental and needs a lot of work. + +package net.gravitydevelopment.anticheat.util; + +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityShootBowEvent; +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 < 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/CheckResult.java b/src/main/java/net/gravitydevelopment/anticheat/util/CheckResult.java similarity index 96% rename from src/main/java/net/h31ix/anticheat/util/CheckResult.java rename to src/main/java/net/gravitydevelopment/anticheat/util/CheckResult.java index 3449541..7ba56eb 100644 --- a/src/main/java/net/h31ix/anticheat/util/CheckResult.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/CheckResult.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.util; +package net.gravitydevelopment.anticheat.util; public class CheckResult { diff --git a/src/main/java/net/h31ix/anticheat/util/Distance.java b/src/main/java/net/gravitydevelopment/anticheat/util/Distance.java similarity index 94% rename from src/main/java/net/h31ix/anticheat/util/Distance.java rename to src/main/java/net/gravitydevelopment/anticheat/util/Distance.java index 2527dc1..457b6a1 100644 --- a/src/main/java/net/h31ix/anticheat/util/Distance.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/Distance.java @@ -1,59 +1,59 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.util; - -import org.bukkit.Location; - -public class Distance { - private final double l1Y; - private final double l2Y; - - private final double XDiff; - private final double YDiff; - private final double ZDiff; - - public Distance(Location from, Location to) { - l1Y = to.getY(); - l2Y = from.getY(); - - XDiff = Math.abs(to.getX() - from.getX()); - ZDiff = Math.abs(to.getZ() - from.getZ()); - YDiff = Math.abs(l1Y - l2Y); - } - - public double fromY() { - return l2Y; - } - - public double toY() { - return l1Y; - } - - public double getXDifference() { - return XDiff; - } - - public double getZDifference() { - return ZDiff; - } - - public double getYDifference() { - return YDiff; - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.util; + +import org.bukkit.Location; + +public class Distance { + private final double l1Y; + private final double l2Y; + + private final double XDiff; + private final double YDiff; + private final double ZDiff; + + public Distance(Location from, Location to) { + l1Y = to.getY(); + l2Y = from.getY(); + + XDiff = Math.abs(to.getX() - from.getX()); + ZDiff = Math.abs(to.getZ() - from.getZ()); + YDiff = Math.abs(l1Y - l2Y); + } + + public double fromY() { + return l2Y; + } + + public double toY() { + return l1Y; + } + + public double getXDifference() { + return XDiff; + } + + public double getZDifference() { + return ZDiff; + } + + public double getYDifference() { + return YDiff; + } +} diff --git a/src/main/java/net/h31ix/anticheat/util/FileFormatter.java b/src/main/java/net/gravitydevelopment/anticheat/util/FileFormatter.java similarity index 95% rename from src/main/java/net/h31ix/anticheat/util/FileFormatter.java rename to src/main/java/net/gravitydevelopment/anticheat/util/FileFormatter.java index cded51a..5345741 100644 --- a/src/main/java/net/h31ix/anticheat/util/FileFormatter.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/FileFormatter.java @@ -1,36 +1,36 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.util; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -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(); - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.util; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +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(); + } +} diff --git a/src/main/java/net/h31ix/anticheat/util/Level.java b/src/main/java/net/gravitydevelopment/anticheat/util/Level.java similarity index 97% rename from src/main/java/net/h31ix/anticheat/util/Level.java rename to src/main/java/net/gravitydevelopment/anticheat/util/Level.java index b8e92e8..0cf0a41 100644 --- a/src/main/java/net/h31ix/anticheat/util/Level.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/Level.java @@ -16,9 +16,9 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.util; +package net.gravitydevelopment.anticheat.util; -import net.h31ix.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.AntiCheat; import org.bukkit.ChatColor; import java.util.ArrayList; diff --git a/src/main/java/net/h31ix/anticheat/util/PastebinReport.java b/src/main/java/net/gravitydevelopment/anticheat/util/PastebinReport.java similarity index 98% rename from src/main/java/net/h31ix/anticheat/util/PastebinReport.java rename to src/main/java/net/gravitydevelopment/anticheat/util/PastebinReport.java index c90a877..d9cc343 100644 --- a/src/main/java/net/h31ix/anticheat/util/PastebinReport.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/PastebinReport.java @@ -16,10 +16,10 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.util; +package net.gravitydevelopment.anticheat.util; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.files.Magic; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.files.Magic; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; diff --git a/src/main/java/net/h31ix/anticheat/util/Permission.java b/src/main/java/net/gravitydevelopment/anticheat/util/Permission.java similarity index 98% rename from src/main/java/net/h31ix/anticheat/util/Permission.java rename to src/main/java/net/gravitydevelopment/anticheat/util/Permission.java index 4c0dc99..c505ed1 100644 --- a/src/main/java/net/h31ix/anticheat/util/Permission.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/Permission.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.util; +package net.gravitydevelopment.anticheat.util; import org.bukkit.command.CommandSender; diff --git a/src/main/java/net/h31ix/anticheat/util/SpyState.java b/src/main/java/net/gravitydevelopment/anticheat/util/SpyState.java similarity index 96% rename from src/main/java/net/h31ix/anticheat/util/SpyState.java rename to src/main/java/net/gravitydevelopment/anticheat/util/SpyState.java index 5e0ff61..c2de330 100644 --- a/src/main/java/net/h31ix/anticheat/util/SpyState.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/SpyState.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.util; +package net.gravitydevelopment.anticheat.util; import org.bukkit.Location; diff --git a/src/main/java/net/h31ix/anticheat/util/ToolHardness.java b/src/main/java/net/gravitydevelopment/anticheat/util/ToolHardness.java similarity index 96% rename from src/main/java/net/h31ix/anticheat/util/ToolHardness.java rename to src/main/java/net/gravitydevelopment/anticheat/util/ToolHardness.java index 1bb2efe..6f3ccff 100644 --- a/src/main/java/net/h31ix/anticheat/util/ToolHardness.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/ToolHardness.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.util; +package net.gravitydevelopment.anticheat.util; import org.bukkit.Material; diff --git a/src/main/java/net/h31ix/anticheat/util/Utilities.java b/src/main/java/net/gravitydevelopment/anticheat/util/Utilities.java similarity index 96% rename from src/main/java/net/h31ix/anticheat/util/Utilities.java rename to src/main/java/net/gravitydevelopment/anticheat/util/Utilities.java index 687123c..fa179d5 100644 --- a/src/main/java/net/h31ix/anticheat/util/Utilities.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/Utilities.java @@ -1,563 +1,563 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.util; - -import net.h31ix.anticheat.AntiCheat; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.NumberConversions; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -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 Map COMBO = new HashMap(); - - public static final String SPY_METADATA = "ac-spydata"; - - /** - * Send a hack level alert to players and console - * - * @param message List of strings to send as the alert - */ - 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().getConfig().logToConsole.getValue()) { - for (String msg : message) { - AntiCheat.getManager().log(msg); - } - } - if (AntiCheat.getManager().getConfiguration().getConfig().fileLogLevel.getValue() != 0) { - for (String msg : message) { - AntiCheat.getManager().log(msg, 1); - } - } - } - - /** - * Determine whether a player cannot stand on or around the given block - * - * @param block the block to check - * @return true if the player should be unable to stand here - */ - public static boolean cantStandAt(Block block) { - return !canStand(block) && cantStandClose(block) && cantStandFar(block); - } - - /** - * Determine whether a player should be unable to stand at a given location - * - * @param location the location to check - * @return true if the player should be unable to stand here - */ - public static boolean cantStandAtExp(Location location) { - return cantStandAt(new Location(location.getWorld(), fixXAxis(location.getX()), location.getY() - 0.01D, location.getBlockZ()).getBlock()); - } - - /** - * Determine whether cannot stand on the block's immediately surroundings (North, East, South, West) - * - * @param block the block to check - * @return true if a player cannot stand in the immediate vicinity - */ - 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)); - } - - /** - * Determine whether cannot stand on the block's outer surroundings - * - * @param block the block to check - * @return true if a player cannot stand in areas further away from the block - */ - 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)); - } - - /** - * Determine whether a player can stand on the given block - * - * @param block the block to check - * @return true if the player can stand here - */ - public static boolean canStand(Block block) { - return !(block.isLiquid() || block.getType() == Material.AIR); - } - - /** - * Determine whether a player is fully submerged in water - * - * @param player the player's location - * @return true if the player is fully in the water - */ - 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(); - } - - /** - * Fixes a player's X position to determine the block they are on, even if they're on the edge - * - * @param x player's x position - * @return fixed x position - */ - public static double fixXAxis(double x) { - /* 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; - } - - /** - * Determine if the player is hovering over water with the given limit - * - * @param player the player's location - * @param blocks max blocks to check - * @return true if the player is hovering over water - */ - 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.getType() != Material.AIR) { - return newloc.isLiquid(); - } - } - - return false; - } - - /** - * Determine if the player is hovering over water with a hard limit of 25 blocks - * - * @param player the player's location - * @return true if the player is hovering over water - */ - public static boolean isHoveringOverWater(Location player) { - return isHoveringOverWater(player, 25); - } - - /** - * Determine whether a material will break instantly when hit - * - * @param m the material to check - * @return true if the material is instant break - */ - public static boolean isInstantBreak(Material m) { - return INSTANT_BREAK.contains(m); - } - - /** - * Determine whether a material is edible - * - * @param m the material to check - * @return true if the material is food - */ - public static boolean isFood(Material m) { - return FOOD.contains(m); - } - - /** - * Determine whether a block is a slab - * - * @param block block to check - * @return true if slab - */ - public static boolean isSlab(Block block) { - Material type = block.getType(); - switch (type) { - case STEP: - case DOUBLE_STEP: - case WOOD_STEP: - case WOOD_DOUBLE_STEP: - return true; - default: - return false; - } - } - - /** - * Determine whether a block is a stair - * - * @param block block to check - * @return true if stair - */ - public static boolean isStair(Block block) { - Material type = block.getType(); - switch (type) { - case WOOD_STAIRS: - case SPRUCE_WOOD_STAIRS: - case SMOOTH_STAIRS: - case SANDSTONE_STAIRS: - case QUARTZ_STAIRS: - case JUNGLE_WOOD_STAIRS: - case NETHER_BRICK_STAIRS: - case BIRCH_WOOD_STAIRS: - case COBBLESTONE_STAIRS: - return true; - default: - return false; - } - } - - /** - * Determine whether a player can interact with this material - * - * @param m material to check - * @return true if interactable - */ - public static boolean isInteractable(Material m) { - return INTERACTABLE.contains(m); - } - - /** - * Determine whether a player is sprinting or flying - * - * @param player player to check - * @return true if sprinting or flying - */ - public static boolean sprintFly(Player player) { - return player.isSprinting() || player.isFlying(); - } - - /** - * Determine whether a player is standing on a lily pad - * - * @param player player to check - * @return true if on lily pad - */ - public static boolean isOnLilyPad(Player player) { - Block block = player.getLocation().getBlock(); - Material lily = Material.WATER_LILY; - // TODO: Can we fix X this? - 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; - } - - /** - * Determine whether a player is fully submersed in liquid - * - * @param player player to check - * @return true if submersed - */ - public static boolean isSubmersed(Player player) { - return player.getLocation().getBlock().isLiquid() && player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); - } - - /** - * Determine whether a player is in water - * - * @param player player to check - * @return true if in water - */ - 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(); - } - - /** - * Determine whether a player is in a web - * - * @param player player to check - * @return true if in web - */ - public static boolean isInWeb(Player player) { - return player.getLocation().getBlock().getType() == Material.WEB || player.getLocation().getBlock().getRelative(BlockFace.DOWN).getType() == Material.WEB || player.getLocation().getBlock().getRelative(BlockFace.UP).getType() == Material.WEB; - } - - /** - * Determine whether a block is climbable - * - * @param block block to check - * @return true if climbable - */ - public static boolean isClimbableBlock(Block block) { - return block.getType() == Material.VINE || block.getType() == Material.LADDER || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER; - } - - /** - * Determine whether a player is on a vine (can be free hanging) - * - * @param player to check - * @return true if on vine - */ - public static boolean isOnVine(Player player) { - return player.getLocation().getBlock().getType() == Material.VINE; - } - - /** - * Determine whether a String can be cast to an Integer - * - * @param string text to check - * @return true if int - */ - public static boolean isInt(String string) { - boolean x = false; - try { - Integer.parseInt(string); - x = true; - } catch (Exception ex) { - } - return x; - } - - /** - * Calculate the time in milliseconds that it should take to break the given block with the given tool - * - * @param tool tool to check - * @param block block to check - * @return time in milliseconds to break - */ - public static long calcSurvivalFastBreak(ItemStack tool, Material block) { - if (isInstantBreak(block) || (tool.getType() == Material.SHEARS && block == Material.LEAVES)) { - return 0; - } - double bhardness = BlockHardness.getBlockHardness(block); - double thardness = ToolHardness.getToolHardness(tool.getType()); - long enchantlvl = (long) tool.getEnchantmentLevel(Enchantment.DIG_SPEED); - - long result = Math.round((bhardness * thardness) * 0.10 * 10000); - - result += 150; - - if (enchantlvl > 0) { - result /= enchantlvl * enchantlvl + 1L; - } - - if (result > 25000) { - result = 25000; - } else if (result < 0) { - result = 0; - } - - if (isQuickCombo(tool, block)) { - result = result / 2; - } - - return result; - } - - /** - * Determine whether the given tool is a combination that makes the breaking of this block faster - * - * @param tool tool to check - * @param block block to check - * @return true if quick combo - */ - private static boolean isQuickCombo(ItemStack tool, Material block) { - for (Material t : COMBO.keySet()) { - if (tool.getType() == t && COMBO.get(t) == block) { - return true; - } - } - return false; - } - - /** - * Determine if a block ISN'T one of the specified types - * - * @param block block to check - * @param materials array of possible materials - * @return true if the block isn't any of the materials - */ - public static boolean blockIsnt(Block block, Material[] materials) { - Material type = block.getType(); - for (Material m : materials) { - if (m == type) { - return false; - } - } - return false; - } - - /** - * Parse a COMMAND[] input to a set of commands to execute - * - * @param command input string - * @return parsed commands - */ - public static String[] getCommands(String command) { - return command.replaceAll("COMMAND\\[", "").replaceAll("]", "").split(";"); - } - - /** - * Remove all whitespace from the given string to ready it for parsing - * - * @param string the string to parse - * @return string with whitespace removed - */ - public static String removeWhitespace(String string) { - return string.replaceAll(" ", ""); - } - - /** - * Determine if a player has the given enchantment on their armor - * - * @param player player to check - * @param e enchantment to check - * @return true if the armor has this enchantment - */ - public static boolean hasArmorEnchantment(Player player, Enchantment e) { - for (ItemStack is : player.getInventory().getArmorContents()) { - if (is != null && is.containsEnchantment(e)) { - return true; - } - } - return false; - } - - /** - * Create a list with the given string for execution - * - * @param string the string to parse - * @return ArrayList with string - */ - public static ArrayList stringToList(String string) { - ArrayList i = new ArrayList(); - i.add(string); - return i; - } - - /** - * Create a comma-delimited string from a list - * - * @param list the list to parse - * @return the list in a string format - */ - public static String listToCommaString(List list) { - StringBuilder b = new StringBuilder(); - for (int i = 0; i < list.size(); i++) { - b.append(list.get(i)); - if (i < list.size() - 1) { - b.append(","); - } - } - return b.toString(); - } - - /** - * Parse a string in the format of "XdXhXmXs" to seconds - * @param string The string to parse - * @return seconds - */ - public static long lifeToSeconds(String string) { - if (string.equals("0") || string.equals("")) return 0; - String[] lifeMatch = new String[]{ "d", "h", "m", "s" }; - int[] lifeInterval = new int[]{ 86400, 3600, 60, 1 }; - long seconds = 0L; - - for (int i=0;i. + */ + +package net.gravitydevelopment.anticheat.util; + +import net.gravitydevelopment.anticheat.AntiCheat; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.NumberConversions; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +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 Map COMBO = new HashMap(); + + public static final String SPY_METADATA = "ac-spydata"; + + /** + * Send a hack level alert to players and console + * + * @param message List of strings to send as the alert + */ + 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().getConfig().logToConsole.getValue()) { + for (String msg : message) { + AntiCheat.getManager().log(msg); + } + } + if (AntiCheat.getManager().getConfiguration().getConfig().fileLogLevel.getValue() != 0) { + for (String msg : message) { + AntiCheat.getManager().log(msg, 1); + } + } + } + + /** + * Determine whether a player cannot stand on or around the given block + * + * @param block the block to check + * @return true if the player should be unable to stand here + */ + public static boolean cantStandAt(Block block) { + return !canStand(block) && cantStandClose(block) && cantStandFar(block); + } + + /** + * Determine whether a player should be unable to stand at a given location + * + * @param location the location to check + * @return true if the player should be unable to stand here + */ + public static boolean cantStandAtExp(Location location) { + return cantStandAt(new Location(location.getWorld(), fixXAxis(location.getX()), location.getY() - 0.01D, location.getBlockZ()).getBlock()); + } + + /** + * Determine whether cannot stand on the block's immediately surroundings (North, East, South, West) + * + * @param block the block to check + * @return true if a player cannot stand in the immediate vicinity + */ + 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)); + } + + /** + * Determine whether cannot stand on the block's outer surroundings + * + * @param block the block to check + * @return true if a player cannot stand in areas further away from the block + */ + 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)); + } + + /** + * Determine whether a player can stand on the given block + * + * @param block the block to check + * @return true if the player can stand here + */ + public static boolean canStand(Block block) { + return !(block.isLiquid() || block.getType() == Material.AIR); + } + + /** + * Determine whether a player is fully submerged in water + * + * @param player the player's location + * @return true if the player is fully in the water + */ + 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(); + } + + /** + * Fixes a player's X position to determine the block they are on, even if they're on the edge + * + * @param x player's x position + * @return fixed x position + */ + public static double fixXAxis(double x) { + /* 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; + } + + /** + * Determine if the player is hovering over water with the given limit + * + * @param player the player's location + * @param blocks max blocks to check + * @return true if the player is hovering over water + */ + 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.getType() != Material.AIR) { + return newloc.isLiquid(); + } + } + + return false; + } + + /** + * Determine if the player is hovering over water with a hard limit of 25 blocks + * + * @param player the player's location + * @return true if the player is hovering over water + */ + public static boolean isHoveringOverWater(Location player) { + return isHoveringOverWater(player, 25); + } + + /** + * Determine whether a material will break instantly when hit + * + * @param m the material to check + * @return true if the material is instant break + */ + public static boolean isInstantBreak(Material m) { + return INSTANT_BREAK.contains(m); + } + + /** + * Determine whether a material is edible + * + * @param m the material to check + * @return true if the material is food + */ + public static boolean isFood(Material m) { + return FOOD.contains(m); + } + + /** + * Determine whether a block is a slab + * + * @param block block to check + * @return true if slab + */ + public static boolean isSlab(Block block) { + Material type = block.getType(); + switch (type) { + case STEP: + case DOUBLE_STEP: + case WOOD_STEP: + case WOOD_DOUBLE_STEP: + return true; + default: + return false; + } + } + + /** + * Determine whether a block is a stair + * + * @param block block to check + * @return true if stair + */ + public static boolean isStair(Block block) { + Material type = block.getType(); + switch (type) { + case WOOD_STAIRS: + case SPRUCE_WOOD_STAIRS: + case SMOOTH_STAIRS: + case SANDSTONE_STAIRS: + case QUARTZ_STAIRS: + case JUNGLE_WOOD_STAIRS: + case NETHER_BRICK_STAIRS: + case BIRCH_WOOD_STAIRS: + case COBBLESTONE_STAIRS: + return true; + default: + return false; + } + } + + /** + * Determine whether a player can interact with this material + * + * @param m material to check + * @return true if interactable + */ + public static boolean isInteractable(Material m) { + return INTERACTABLE.contains(m); + } + + /** + * Determine whether a player is sprinting or flying + * + * @param player player to check + * @return true if sprinting or flying + */ + public static boolean sprintFly(Player player) { + return player.isSprinting() || player.isFlying(); + } + + /** + * Determine whether a player is standing on a lily pad + * + * @param player player to check + * @return true if on lily pad + */ + public static boolean isOnLilyPad(Player player) { + Block block = player.getLocation().getBlock(); + Material lily = Material.WATER_LILY; + // TODO: Can we fix X this? + 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; + } + + /** + * Determine whether a player is fully submersed in liquid + * + * @param player player to check + * @return true if submersed + */ + public static boolean isSubmersed(Player player) { + return player.getLocation().getBlock().isLiquid() && player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); + } + + /** + * Determine whether a player is in water + * + * @param player player to check + * @return true if in water + */ + 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(); + } + + /** + * Determine whether a player is in a web + * + * @param player player to check + * @return true if in web + */ + public static boolean isInWeb(Player player) { + return player.getLocation().getBlock().getType() == Material.WEB || player.getLocation().getBlock().getRelative(BlockFace.DOWN).getType() == Material.WEB || player.getLocation().getBlock().getRelative(BlockFace.UP).getType() == Material.WEB; + } + + /** + * Determine whether a block is climbable + * + * @param block block to check + * @return true if climbable + */ + public static boolean isClimbableBlock(Block block) { + return block.getType() == Material.VINE || block.getType() == Material.LADDER || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER; + } + + /** + * Determine whether a player is on a vine (can be free hanging) + * + * @param player to check + * @return true if on vine + */ + public static boolean isOnVine(Player player) { + return player.getLocation().getBlock().getType() == Material.VINE; + } + + /** + * Determine whether a String can be cast to an Integer + * + * @param string text to check + * @return true if int + */ + public static boolean isInt(String string) { + boolean x = false; + try { + Integer.parseInt(string); + x = true; + } catch (Exception ex) { + } + return x; + } + + /** + * Calculate the time in milliseconds that it should take to break the given block with the given tool + * + * @param tool tool to check + * @param block block to check + * @return time in milliseconds to break + */ + public static long calcSurvivalFastBreak(ItemStack tool, Material block) { + if (isInstantBreak(block) || (tool.getType() == Material.SHEARS && block == Material.LEAVES)) { + return 0; + } + double bhardness = BlockHardness.getBlockHardness(block); + double thardness = ToolHardness.getToolHardness(tool.getType()); + long enchantlvl = (long) tool.getEnchantmentLevel(Enchantment.DIG_SPEED); + + long result = Math.round((bhardness * thardness) * 0.10 * 10000); + + result += 150; + + if (enchantlvl > 0) { + result /= enchantlvl * enchantlvl + 1L; + } + + if (result > 25000) { + result = 25000; + } else if (result < 0) { + result = 0; + } + + if (isQuickCombo(tool, block)) { + result = result / 2; + } + + return result; + } + + /** + * Determine whether the given tool is a combination that makes the breaking of this block faster + * + * @param tool tool to check + * @param block block to check + * @return true if quick combo + */ + private static boolean isQuickCombo(ItemStack tool, Material block) { + for (Material t : COMBO.keySet()) { + if (tool.getType() == t && COMBO.get(t) == block) { + return true; + } + } + return false; + } + + /** + * Determine if a block ISN'T one of the specified types + * + * @param block block to check + * @param materials array of possible materials + * @return true if the block isn't any of the materials + */ + public static boolean blockIsnt(Block block, Material[] materials) { + Material type = block.getType(); + for (Material m : materials) { + if (m == type) { + return false; + } + } + return false; + } + + /** + * Parse a COMMAND[] input to a set of commands to execute + * + * @param command input string + * @return parsed commands + */ + public static String[] getCommands(String command) { + return command.replaceAll("COMMAND\\[", "").replaceAll("]", "").split(";"); + } + + /** + * Remove all whitespace from the given string to ready it for parsing + * + * @param string the string to parse + * @return string with whitespace removed + */ + public static String removeWhitespace(String string) { + return string.replaceAll(" ", ""); + } + + /** + * Determine if a player has the given enchantment on their armor + * + * @param player player to check + * @param e enchantment to check + * @return true if the armor has this enchantment + */ + public static boolean hasArmorEnchantment(Player player, Enchantment e) { + for (ItemStack is : player.getInventory().getArmorContents()) { + if (is != null && is.containsEnchantment(e)) { + return true; + } + } + return false; + } + + /** + * Create a list with the given string for execution + * + * @param string the string to parse + * @return ArrayList with string + */ + public static ArrayList stringToList(String string) { + ArrayList i = new ArrayList(); + i.add(string); + return i; + } + + /** + * Create a comma-delimited string from a list + * + * @param list the list to parse + * @return the list in a string format + */ + public static String listToCommaString(List list) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < list.size(); i++) { + b.append(list.get(i)); + if (i < list.size() - 1) { + b.append(","); + } + } + return b.toString(); + } + + /** + * Parse a string in the format of "XdXhXmXs" to seconds + * @param string The string to parse + * @return seconds + */ + public static long lifeToSeconds(String string) { + if (string.equals("0") || string.equals("")) return 0; + String[] lifeMatch = new String[]{ "d", "h", "m", "s" }; + int[] lifeInterval = new int[]{ 86400, 3600, 60, 1 }; + long seconds = 0L; + + for (int i=0;i. */ -package net.h31ix.anticheat.util.enterprise; +package net.gravitydevelopment.anticheat.util.enterprise; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.manage.CheckType; -import net.h31ix.anticheat.manage.User; -import net.h31ix.anticheat.util.Utilities; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.manage.CheckType; +import net.gravitydevelopment.anticheat.manage.User; +import net.gravitydevelopment.anticheat.util.Utilities; import org.bukkit.Bukkit; import org.bukkit.scheduler.BukkitTask; diff --git a/src/main/java/net/h31ix/anticheat/util/rule/ConditionalRule.java b/src/main/java/net/gravitydevelopment/anticheat/util/rule/ConditionalRule.java similarity index 94% rename from src/main/java/net/h31ix/anticheat/util/rule/ConditionalRule.java rename to src/main/java/net/gravitydevelopment/anticheat/util/rule/ConditionalRule.java index 200d3e3..f0be89d 100644 --- a/src/main/java/net/h31ix/anticheat/util/rule/ConditionalRule.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/rule/ConditionalRule.java @@ -16,10 +16,10 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.util.rule; +package net.gravitydevelopment.anticheat.util.rule; -import net.h31ix.anticheat.manage.CheckType; -import net.h31ix.anticheat.manage.User; +import net.gravitydevelopment.anticheat.manage.CheckType; +import net.gravitydevelopment.anticheat.manage.User; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; @@ -42,7 +42,7 @@ import java.util.SortedMap; * Check_SPIDER > 0 ? Player.KICK : null
* The above statement would read 'If the spider check has been failed over zero times, kick the player. Otherwise, do nothing.' *

- * To see syntax for variables and functions that you may use, see {@link net.h31ix.anticheat.util.rule.Rule} + * To see syntax for variables and functions that you may use, see {@link net.gravitydevelopment.anticheat.util.rule.Rule} */ public class ConditionalRule extends Rule { diff --git a/src/main/java/net/h31ix/anticheat/util/rule/Rule.java b/src/main/java/net/gravitydevelopment/anticheat/util/rule/Rule.java similarity index 88% rename from src/main/java/net/h31ix/anticheat/util/rule/Rule.java rename to src/main/java/net/gravitydevelopment/anticheat/util/rule/Rule.java index 996e6dc..2a5ba09 100644 --- a/src/main/java/net/h31ix/anticheat/util/rule/Rule.java +++ b/src/main/java/net/gravitydevelopment/anticheat/util/rule/Rule.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.util.rule; +package net.gravitydevelopment.anticheat.util.rule; -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.manage.CheckType; -import net.h31ix.anticheat.manage.User; -import net.h31ix.anticheat.util.Utilities; +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.manage.CheckType; +import net.gravitydevelopment.anticheat.manage.User; +import net.gravitydevelopment.anticheat.util.Utilities; import java.lang.reflect.Constructor; import java.util.ArrayList; @@ -39,7 +39,7 @@ import java.util.TreeMap; *

*

* Types of variables:
- * - Check: Contains all valid checks as listed in {@link net.h31ix.anticheat.manage.CheckType}, and will return the number of times this user has failed the given check
+ * - Check: Contains all valid checks as listed in {@link net.gravitydevelopment.anticheat.manage.CheckType}, and will return the number of times this user has failed the given check
* - Player: Contains LEVEL, the player's current level and CHECK, the check that was just failed *

*

@@ -56,7 +56,7 @@ import java.util.TreeMap; *

* The Rule class itself is not an functional rule setup, * it is inherited and made functional by different implementations of the rule parser.
- * The only current Rule implementation is the {@link net.h31ix.anticheat.util.rule.ConditionalRule} + * The only current Rule implementation is the {@link net.gravitydevelopment.anticheat.util.rule.ConditionalRule} */ public class Rule { @@ -66,7 +66,7 @@ public class Rule { private Type type; public enum Type { - CONDITIONAL(".*[?]*.*:.*", "net.h31ix.anticheat.util.rule.ConditionalRule"); + CONDITIONAL(".*[?]*.*:.*", "net.gravitydevelopment.anticheat.util.rule.ConditionalRule"); private String regex; private String c; @@ -125,7 +125,7 @@ public class Rule { /** * Get the type of rule this is * - * @return a {@link net.h31ix.anticheat.util.rule.Rule.Type} + * @return a {@link net.gravitydevelopment.anticheat.util.rule.Rule.Type} */ public Type getType() { return type; diff --git a/src/main/java/net/h31ix/anticheat/xray/XRayListener.java b/src/main/java/net/gravitydevelopment/anticheat/xray/XRayListener.java similarity index 90% rename from src/main/java/net/h31ix/anticheat/xray/XRayListener.java rename to src/main/java/net/gravitydevelopment/anticheat/xray/XRayListener.java index 6b5eed0..a66a94e 100644 --- a/src/main/java/net/h31ix/anticheat/xray/XRayListener.java +++ b/src/main/java/net/gravitydevelopment/anticheat/xray/XRayListener.java @@ -1,66 +1,66 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.xray; - -import net.h31ix.anticheat.AntiCheat; -import net.h31ix.anticheat.config.Configuration; -import net.h31ix.anticheat.manage.CheckManager; -import net.h31ix.anticheat.manage.CheckType; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.entity.Player; -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.getConfig().logXRayStats.getValue()) { - Player p = event.getPlayer(); - if (p.getGameMode() == GameMode.CREATIVE && !config.getConfig().trackCreativeXRay.getValue()) { - 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 || m == Material.GLOWING_REDSTONE_ORE) { - tracker.addRedstone(player); - } else if (m == Material.GOLD_ORE) { - tracker.addGold(player); - } else { - tracker.addBlock(player); - } - tracker.addTotal(player); - } - } - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.xray; + +import net.gravitydevelopment.anticheat.AntiCheat; +import net.gravitydevelopment.anticheat.config.Configuration; +import net.gravitydevelopment.anticheat.manage.CheckManager; +import net.gravitydevelopment.anticheat.manage.CheckType; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.entity.Player; +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.getConfig().logXRayStats.getValue()) { + Player p = event.getPlayer(); + if (p.getGameMode() == GameMode.CREATIVE && !config.getConfig().trackCreativeXRay.getValue()) { + 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 || m == Material.GLOWING_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/gravitydevelopment/anticheat/xray/XRayStats.java similarity index 95% rename from src/main/java/net/h31ix/anticheat/xray/XRayStats.java rename to src/main/java/net/gravitydevelopment/anticheat/xray/XRayStats.java index 841da62..0fced4b 100644 --- a/src/main/java/net/h31ix/anticheat/xray/XRayStats.java +++ b/src/main/java/net/gravitydevelopment/anticheat/xray/XRayStats.java @@ -1,84 +1,84 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -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; - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.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; + } +} diff --git a/src/main/java/net/h31ix/anticheat/xray/XRayTracker.java b/src/main/java/net/gravitydevelopment/anticheat/xray/XRayTracker.java similarity index 96% rename from src/main/java/net/h31ix/anticheat/xray/XRayTracker.java rename to src/main/java/net/gravitydevelopment/anticheat/xray/XRayTracker.java index 5d52475..f3bc346 100644 --- a/src/main/java/net/h31ix/anticheat/xray/XRayTracker.java +++ b/src/main/java/net/gravitydevelopment/anticheat/xray/XRayTracker.java @@ -1,152 +1,152 @@ -/* - * AntiCheat for Bukkit. - * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.h31ix.anticheat.xray; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -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 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); - } -} +/* + * AntiCheat for Bukkit. + * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.gravitydevelopment.anticheat.xray; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +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 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); + } +} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 7a113a2..87ac17d 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,12 +1,12 @@ author: Gravity database: false description: Prevention of hacks and other malicious tinkering on a Minecraft server. -main: net.h31ix.anticheat.AntiCheat +main: net.gravitydevelopment.anticheat.AntiCheat name: AntiCheat softdepend: [ProtocolLib] startup: postworld url: http://gravitydevelopment.net -version: ${project.version}-b${BUILD_NUMBER} +version: ${project.build.version} commands: anticheat: description: Control and view info about AntiCheat diff --git a/src/test/java/net/h31ix/anticheat/util/BlockHardnessTest.java b/src/test/java/net/gravitydevelopment/anticheat/util/BlockHardnessTest.java similarity index 96% rename from src/test/java/net/h31ix/anticheat/util/BlockHardnessTest.java rename to src/test/java/net/gravitydevelopment/anticheat/util/BlockHardnessTest.java index b97a67b..b10ca77 100644 --- a/src/test/java/net/h31ix/anticheat/util/BlockHardnessTest.java +++ b/src/test/java/net/gravitydevelopment/anticheat/util/BlockHardnessTest.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package net.h31ix.anticheat.util; +package net.gravitydevelopment.anticheat.util; import org.bukkit.Material;