Refactor package to new namespace

This commit is contained in:
h31ix committed 2013-10-13 21:47:19 -04:00
1 parent 089759dbad
commit fd1e5232e0
55 files changed
+5632 -5624

No files matched your search

@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat;
import com.comphenix.protocol.ProtocolLibrary;
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;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.List;
public class AntiCheat extends JavaPlugin {
private static AnticheatManager manager;
private static AntiCheat plugin;
private static List<Listener> eventList = new ArrayList<Listener>();
private static boolean update = false;
private static Configuration config;
private static boolean verbose;
private static boolean developer;
private static final long XRAY_TIME = 1200;
private static final int PROJECT_ID = 38723;
private static PacketManager packetManager;
private static boolean protocolLib = false;
@Override
public void onEnable() {
plugin = this;
manager = new AnticheatManager(this, getLogger());
eventList.add(new PlayerListener());
eventList.add(new BlockListener());
eventList.add(new EntityListener());
eventList.add(new VehicleListener());
eventList.add(new InventoryListener());
// Order is important in some cases, don't screw with these unless needed, especially config
setupConfig();
// Xray must come before events
setupXray();
setupEvents();
setupCommands();
setupUpdater();
setupProtocol();
// Enterprise must come before levels
setupEnterprise();
restoreLevels();
// Check if NoCheatPlus is installed
Bukkit.getScheduler().runTaskLater(this, new Runnable() {
public void run() {
if (Bukkit.getPluginManager().getPlugin("NoCheatPlus") != null) {
getLogger().severe("You are also running NoCheatPlus!");
getLogger().severe("NoCheatPlus has been known to conflict with AntiCheat's results and create false cheat detections.");
getLogger().severe("Please remove or disable NoCheatPlus to silence this warning.");
}
}
}, 40L);
// End tests
verboseLog("Finished loading.");
}
@Override
public void onDisable() {
verboseLog("Saving user levels...");
config.getLevels().saveLevelsFromUsers(getManager().getUserManager().getUsers());
AnticheatManager.close();
getServer().getScheduler().cancelTasks(this);
cleanup();
}
private void setupProtocol() {
if (Bukkit.getPluginManager().getPlugin("ProtocolLib") != null) {
protocolLib = true;
packetManager = new PacketManager(ProtocolLibrary.getProtocolManager(), this, manager);
verboseLog("Hooked into ProtocolLib");
}
}
private void setupXray() {
final XRayTracker xtracker = manager.getXRayTracker();
if (config.getConfig().logXRayStats.getValue()) {
eventList.add(new XRayListener());
if (config.getConfig().alertWhenXRayIsFound.getValue()) {
getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() {
@Override
public void run() {
for (Player player : getServer().getOnlinePlayers()) {
String name = player.getName();
if (!xtracker.hasAlerted(name) && xtracker.sufficientData(name) && xtracker.hasAbnormal(name)) {
List<String> alert = new ArrayList<String>();
alert.add(ChatColor.YELLOW + "[ALERT] " + ChatColor.WHITE + name + ChatColor.YELLOW + " might be using xray.");
alert.add(ChatColor.YELLOW + "[ALERT] Please check their xray stats using " + ChatColor.WHITE + "/anticheat xray " + name + ChatColor.YELLOW + ".");
Utilities.alert(alert);
xtracker.logAlert(name);
}
}
}
}, XRAY_TIME, XRAY_TIME);
verboseLog("Scheduled the XRay checker.");
}
}
}
private void setupEvents() {
for (Listener listener : eventList) {
getServer().getPluginManager().registerEvents(listener, this);
verboseLog("Registered events for ".concat(listener.toString().split("@")[0].split(".anticheat.")[1]));
}
}
private void setupCommands() {
getCommand("anticheat").setExecutor(new CommandHandler());
verboseLog("Registered commands.");
}
private void setupUpdater() {
if (config.getConfig().autoUpdate.getValue()) {
verboseLog("Checking for a new update...");
Updater updater = new Updater(this, PROJECT_ID, this.getFile(), Updater.UpdateType.DEFAULT, false);
update = updater.getResult() != Updater.UpdateResult.NO_UPDATE;
verboseLog("Update available: " + update);
}
}
private void setupConfig() {
config = manager.getConfiguration();
verbose = config.getConfig().verboseStartup.getValue();
verboseLog("Setup the config.");
}
private void setupEnterprise() {
if (config.getConfig().enterprise.getValue()) {
if (config.getEnterprise().loggingEnabled.getValue()) {
config.getEnterprise().database.cleanEvents();
}
}
}
private void restoreLevels() {
for (Player player : getServer().getOnlinePlayers()) {
String name = player.getName();
User user = new User(name);
user.setIsWaitingOnLevelSync(true);
config.getLevels().loadLevelToUser(user);
manager.getUserManager().addUser(user);
verboseLog("Data for " + name + " loaded");
}
}
public static AntiCheat getPlugin() {
return plugin;
}
public static AnticheatManager getManager() {
return manager;
}
public static boolean isUpdated() {
return !update;
}
public static String getVersion() {
return manager.getPlugin().getDescription().getVersion();
}
private void cleanup() {
eventList = null;
manager = null;
config = null;
}
public static boolean developerMode() {
return developer;
}
public static void setDeveloperMode(boolean b) {
developer = b;
}
public static boolean isUsingProtocolLib() {
return protocolLib;
}
public static void debugLog(final String string) {
Bukkit.getScheduler().runTask(getPlugin(), new Runnable() {
public void run() {
if (developer) {
manager.log("[DEBUG] " + string);
}
}
});
}
public void verboseLog(final String string) {
if (verbose) {
getLogger().info(string);
}
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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<String> high = new ArrayList<String>();
private List<String> med = new ArrayList<String>();
private List<String> low = new ArrayList<String>();
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<Player> 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<Player> 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<Player> 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<String> 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<CheckType> l = new ArrayList<CheckType>();
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<CheckType> 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;
}
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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();
}
}
@@ -0,0 +1,64 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.api;
import net.gravitydevelopment.anticheat.manage.CheckType;
import net.gravitydevelopment.anticheat.manage.User;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Fired when a player fails an AntiCheat check
*/
public class CheckFailEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private final User user;
private final CheckType type;
public CheckFailEvent(User user, CheckType type) {
this.user = user;
this.type = type;
}
/**
* Get the {@link net.gravitydevelopment.anticheat.manage.User} who failed the check
*
* @return a {@link net.gravitydevelopment.anticheat.manage.User}
*/
public User getUser() {
return user;
}
/**
* Get the {@link net.gravitydevelopment.anticheat.manage.CheckType} failed
*
* @return a {@link net.gravitydevelopment.anticheat.manage.CheckType}
*/
public CheckType getCheck() {
return type;
}
public HandlerList getHandlers() {
return handlers;
}
}
@@ -0,0 +1,144 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config;
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;
public class Configuration {
private Config config;
private Enterprise enterprise;
private Lang lang;
private Magic magic;
private Events events;
private Levels levels;
private Rules rules;
private ArrayList<ConfigurationFile> flatfiles;
private ArrayList<ConfigurationTable> dbfiles;
public Configuration(AntiCheat plugin) {
config = new Config(plugin, this);
enterprise = new Enterprise(plugin, this);
lang = new Lang(plugin, this);
magic = new Magic(plugin, this);
flatfiles = new ArrayList<ConfigurationFile>() {{
add(config);
add(enterprise);
add(lang);
add(magic);
}};
dbfiles = new ArrayList<ConfigurationTable>();
// The following values can be configuration from a database, or from flatfile.
if (config.enterprise.getValue() && enterprise.configEvents.getValue()) {
events = new MySQLEventsHolder(this);
dbfiles.add((MySQLEventsHolder) events);
} else {
events = new YamlEventsHolder(plugin, this);
flatfiles.add((YamlEventsHolder) events);
}
if (config.enterprise.getValue() && enterprise.configRules.getValue()) {
rules = new MySQLRulesHolder(this);
dbfiles.add((MySQLRulesHolder) rules);
} else {
rules = new YamlRulesHolder(plugin, this);
flatfiles.add((YamlRulesHolder) rules);
}
if (config.enterprise.getValue() && enterprise.configEvents.getValue()) {
levels = new MySQLLevelsHolder(this);
dbfiles.add((MySQLLevelsHolder) levels);
} else {
levels = new YamlLevelsHolder(plugin, this);
flatfiles.add((YamlLevelsHolder) levels);
}
// End
for (ConfigurationFile file : flatfiles) {
file.save();
checkReload(file);
}
}
public void load() {
for (ConfigurationFile file : flatfiles) {
file.load();
checkReload(file);
}
for (ConfigurationTable table : dbfiles) {
table.load();
}
}
private void checkReload(ConfigurationFile file) {
if (file.needsReload()) {
file.reload();
file.setNeedsReload(false);
}
}
public Config getConfig() {
return config;
}
public Events getEvents() {
return events;
}
public Rules getRules() {
return rules;
}
public Lang getLang() {
return lang;
}
public Enterprise getEnterprise() {
return enterprise;
}
public Levels getLevels() {
return levels;
}
public Magic getMagic() {
return magic;
}
}
@@ -0,0 +1,188 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config;
import net.gravitydevelopment.anticheat.AntiCheat;
import net.gravitydevelopment.anticheat.config.yaml.CommentedConfiguration;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
public class ConfigurationFile {
private File rawFile;
private String fileName;
private CommentedConfiguration configFile;
private FileConfiguration defaultConfigFile;
private Configuration config;
private AntiCheat plugin;
private boolean saveDefault;
private boolean didSaveDefault;
protected boolean needsReload;
public ConfigurationFile(AntiCheat plugin, Configuration config, String fileName) {
this(plugin, config, fileName, true);
}
public ConfigurationFile(AntiCheat plugin, Configuration config, String fileName, boolean saveDefault) {
this(plugin, config, fileName, saveDefault, new File(plugin.getDataFolder(), fileName));
}
public ConfigurationFile(AntiCheat plugin, Configuration config, String fileName, boolean saveDefault, File rawFile) {
// Can't change with user editing
this.plugin = plugin;
this.config = config;
this.fileName = fileName;
this.rawFile = rawFile;
this.saveDefault = saveDefault;
if (saveDefault) {
defaultConfigFile = YamlConfiguration.loadConfiguration(plugin.getResource(fileName));
}
load();
}
public void load() {
// Can change with user editing
if (!rawFile.exists()) {
if (saveDefault) {
plugin.saveResource(fileName, true);
didSaveDefault = true;
} else {
if (!rawFile.getParentFile().exists()) {
rawFile.getParentFile().mkdir();
}
try {
rawFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
configFile = CommentedConfiguration.loadConfiguration(rawFile);
open();
}
public void open() {
// Nothing to do
}
public void close() {
// Nothing to do
}
public void save() {
close();
try {
configFile.save(rawFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public void reload() {
save();
load();
}
public File getRawFile() {
return rawFile;
}
public CommentedConfiguration getConfigFile() {
return configFile;
}
public FileConfiguration getDefaultConfigFile() {
return defaultConfigFile;
}
public Configuration getConfiguration() {
return config;
}
public void setNeedsReload(boolean reload) {
this.needsReload = reload;
}
public boolean needsReload() {
return needsReload;
}
public class ConfigValue<T> {
private String path;
private Object value = null;
private boolean didLoadDefault;
public ConfigValue(String path) {
this(path, true);
}
public ConfigValue(String path, boolean loadDefault) {
this.path = path;
if (getConfigFile().contains(path)) {
value = getConfigFile().get(path);
} else if (loadDefault) {
getConfigFile().set(path, getDefaultConfigFile().get(path));
value = getDefaultConfigFile().get(path);
getConfigFile().set(path, value);
save();
didLoadDefault = true;
}
}
public String getPath() {
return path;
}
public T getValue() {
return (T) value;
}
public T setValue(T value) {
getConfigFile().set(path, value);
save();
return value;
}
public T getDefaultValue() {
return (T) getDefaultConfigFile().get(path);
}
public boolean hasValue() {
return value != null;
}
public boolean didLoadDefault() {
return didLoadDefault;
}
}
}
@@ -0,0 +1,68 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config;
import net.gravitydevelopment.anticheat.util.enterprise.Database;
import java.sql.Connection;
public class ConfigurationTable {
private final String table;
private final Configuration config;
private Database database;
private String prefix;
private String serverName;
public ConfigurationTable(Configuration config, String table) {
this.config = config;
this.table = table;
load();
}
public void load() {
this.database = config.getEnterprise().database;
this.prefix = database.getPrefix();
this.serverName = config.getEnterprise().serverName.getValue();
open();
}
public void open() {
// Nothing to do
}
public Database getDatabase() {
return database;
}
public String getFullTable() {
return prefix + table;
}
public String getServerName() {
return serverName;
}
public Connection getConnection() {
return database.getConnection();
}
}
@@ -0,0 +1,77 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.files;
import net.gravitydevelopment.anticheat.AntiCheat;
import net.gravitydevelopment.anticheat.config.Configuration;
import net.gravitydevelopment.anticheat.config.ConfigurationFile;
import java.util.List;
public class Config extends ConfigurationFile {
public static final String FILENAME = "config.yml";
public ConfigValue<Boolean> logToConsole;
public ConfigValue<Boolean> logXRayStats;
public ConfigValue<Boolean> autoUpdate;
public ConfigValue<Boolean> verboseStartup;
public ConfigValue<Boolean> alertWhenXRayIsFound;
public ConfigValue<Boolean> silentMode;
public ConfigValue<Boolean> exemptOp;
public ConfigValue<Boolean> trackCreativeXRay;
public ConfigValue<Boolean> eventChains;
public ConfigValue<Boolean> enterprise;
public ConfigValue<Boolean> blockChatSpam;
public ConfigValue<Boolean> blockCommandSpam;
public ConfigValue<Integer> fileLogLevel;
public ConfigValue<String> spamKickAction;
public ConfigValue<String> spamBanAction;
public ConfigValue<List<String>> exemptedWorlds;
public Config(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
@Override
public void open() {
logToConsole = new ConfigValue<Boolean>("System.Log to console");
logXRayStats = new ConfigValue<Boolean>("XRay.Log xray stats");
autoUpdate = new ConfigValue<Boolean>("System.Auto update");
verboseStartup = new ConfigValue<Boolean>("System.Verbose startup");
alertWhenXRayIsFound = new ConfigValue<Boolean>("XRay.Alert when xray is found");
silentMode = new ConfigValue<Boolean>("System.Silent mode");
exemptOp = new ConfigValue<Boolean>("System.Exempt op");
trackCreativeXRay = new ConfigValue<Boolean>("XRay.Track creative");
eventChains = new ConfigValue<Boolean>("System.Event Chains");
enterprise = new ConfigValue<Boolean>("System.Enterprise");
blockChatSpam = new ConfigValue<Boolean>("Chat.Block chat spam");
blockCommandSpam = new ConfigValue<Boolean>("Chat.Block command spam");
fileLogLevel = new ConfigValue<Integer>("System.File log level");
spamKickAction = new ConfigValue<String>("Chat.Kick Action");
spamBanAction = new ConfigValue<String>("Chat.Ban Action");
exemptedWorlds = new ConfigValue<List<String>>("Disable in");
}
}
@@ -0,0 +1,86 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.files;
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 {
public static final String FILENAME = "enterprise.yml";
public ConfigValue<String> serverName;
public ConfigValue<Boolean> loggingEnabled;
public ConfigValue<String> loggingLife;
public ConfigValue<String> loggingInterval;
public ConfigValue<Boolean> syncUsers;
public ConfigValue<Boolean> configEvents;
public ConfigValue<Boolean> configRules;
public Database database;
public Enterprise(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
@Override
public void open() {
serverName = new ConfigValue<String>("server.name");
loggingEnabled = new ConfigValue<Boolean>("log.enable");
loggingLife = new ConfigValue<String>("log.life");
loggingInterval = new ConfigValue<String>("log.interval");
syncUsers = new ConfigValue<Boolean>("sync.users");
configEvents = new ConfigValue<Boolean>("config.events");
configRules = new ConfigValue<Boolean>("config.rules");
ConfigValue<String> databaseType = new ConfigValue<String>("database.type");
ConfigValue<String> databaseHostname = new ConfigValue<String>("database.hostname");
ConfigValue<String> databaseUsername = new ConfigValue<String>("database.username");
ConfigValue<String> databasePassword = new ConfigValue<String>("database.password");
ConfigValue<String> databasePrefix = new ConfigValue<String>("database.prefix");
ConfigValue<String> databaseSchema = new ConfigValue<String>("database.database");
ConfigValue<Integer> databasePort = new ConfigValue<Integer>("database.port");
if (getConfiguration().getConfig().enterprise.getValue()) {
// Convert database values to Database
database = new Database(
Database.DatabaseType.valueOf(databaseType.getValue()),
databaseHostname.getValue(),
databasePort.getValue(),
databaseUsername.getValue(),
databasePassword.getValue(),
databasePrefix.getValue(),
databaseSchema.getValue(),
serverName.getValue(),
loggingInterval.getValue(),
loggingLife.getValue()
);
database.connect();
}
}
}
@@ -0,0 +1,61 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.files;
import net.gravitydevelopment.anticheat.AntiCheat;
import net.gravitydevelopment.anticheat.config.Configuration;
import net.gravitydevelopment.anticheat.config.ConfigurationFile;
import java.util.List;
public class Lang extends ConfigurationFile {
public static final String FILENAME = "lang.yml";
public ConfigValue<List<String>> alert;
public ConfigValue<List<String>> playerWarning;
public ConfigValue<String> spamWarning;
public ConfigValue<String> spamKickReason;
public ConfigValue<String> spamBanReason;
public ConfigValue<String> spamKickBroadcast;
public ConfigValue<String> spamBanBroadcast;
public ConfigValue<String> banReason;
public ConfigValue<String> banBroadcast;
public ConfigValue<String> kickReason;
public ConfigValue<String> kickBroadcast;
public Lang(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
@Override
public void open() {
alert = new ConfigValue<List<String>>("alert");
playerWarning = new ConfigValue<List<String>>("warning.player_warning");
spamWarning = new ConfigValue<String>("chat.warning");
spamKickReason = new ConfigValue<String>("chat.kick_reason");
spamBanReason = new ConfigValue<String>("chat.ban_reason");
spamKickBroadcast = new ConfigValue<String>("chat.kick_broadcast");
spamBanBroadcast = new ConfigValue<String>("chat.ban_broadcast");
banReason = new ConfigValue<String>("ban.ban_reason");
banBroadcast = new ConfigValue<String>("ban.ban_broadcast");
kickReason = new ConfigValue<String>("kick.kick_reason");
kickBroadcast = new ConfigValue<String>("kick.kick_broadcast");
}
}
@@ -0,0 +1,462 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.files;
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.
* <p/>
* Note that although each value is documented, changing it may have unintended side-effects. For instance, setting something to 0 that the plugin then uses as a dividend will result in an error. <br>
* Also realize that the smaller a value is, the less you should change it; it's probably small for a reason. The larger a value is, the safer it is to probably change it.
* <p/>
* <b>How to read the value documentation:</b> <br>
* First, you will see a description of the value. Then, you will see a type: <br>
* <b>Type SYSTEM:</b> This is a 'long' value, measured in milliseconds, used to compare past and future events with the current system time. Remember, 1000 ms = 1 second. <br>
* <b>Type INTEGER:</b> This is a regular number. It's typically used as something trivial, such as how many times X event can occur. <br>
* <b>Type DOUBLE:</b> This is a number that has a decimal in it. It's typically used to evaluate speed or distance.
* <p/>
* After the type, you may see a recommendation labeled as '+Leniency'. This means 'In order to add leniency to this value, do X' <br>
* The suggestion for adding leniency will either be to INCREASE or DECREASE the variable. Doing what it suggests will cause the system to not judge the people being checked so vigorously.
*/
public class Magic extends ConfigurationFile {
/**
* The number of animations to wait before checking fastclicking; Type=integer; +Leniency=Increase.
*/
public int ANIMATION_CHECK;
/**
* The minimum time it should have taken for the player to click X times; Type=integer; +Leniency=Increase.
*/
public long ANIMATION_TIMEMIN;
/**
* Time to exempt a player from moving because of entering/exiting a vehicle; Type=system, +Leniency=Increase.
*/
public int ENTERED_EXITED_TIME;
/**
* Time to exempt a player from moving because of entering/exiting sneak mode; Type=system, +Leniency=Increase.
*/
public int SNEAK_TIME;
/**
* Time to exempt a player from moving because of teleporting; Type=system, +Leniency=Increase.
*/
public int TELEPORT_TIME;
/**
* Time to exempt a player from moving because of exiting fly mode; Type=system, +Leniency=Increase.
*/
public int EXIT_FLY_TIME;
/**
* Time to exempt a player from moving because of joining the server; Type=system, +Leniency=Increase.
*/
public int JOIN_TIME;
/**
* Time to exempt a player from fastbreak check because of using instant break; Type=seconds, +Leniency=Increase.
*/
public int INSTANT_BREAK_TIME;
/**
* Time to exempt a player from moving because of taking damage; Type=system, +Leniency=Increase.
*/
public long DAMAGE_TIME;
/**
* Time to exempt a player from moving because of taking damage with knockback effects; Type=system, +Leniency=Increase.
*/
public long KNOCKBACK_DAMAGE_TIME;
/**
* Time to exempt a player from moving because of taking damage from an explosion; Type=system, +Leniency=Increase.
*/
public long EXPLOSION_DAMAGE_TIME;
/**
* Minimum time it takes to fire X projectiles; Type=system, +Leniency=Decrease.
*/
public int PROJECTILE_TIME_MIN;
/**
* Number of projectiles to wait for before checking how long they took to fire off; Type=integer.
*/
public int PROJECTILE_CHECK;
/**
* Minimum time it takes to drop X items; Type=system, +Leniency=Decrease.
*/
public int DROP_TIME_MIN;
/**
* Number of item drops to wait for before checking how long they took to drop; Type=integer.
*/
public int DROP_CHECK;
/**
* Max number of blocks that can be broken in a given time; Type=integer, +Leniency=Increase.
*/
public int FASTBREAK_LIMIT;
/**
* Time to wait before checking block breaks; Type=system, +Leniency=Increase.
*/
public int FASTBREAK_TIMEMAX;
/**
* Time to wait before checking block breaks in creative mode; Type=system, +Leniency=Increase.
*/
public int FASTBREAK_TIMEMAX_CREATIVE;
/**
* Number of times fastbreak can be observed before taking action; Type=integer, +Leniency=Increase.
*/
public int FASTBREAK_MAXVIOLATIONS;
/**
* Number of times fastbreak can be observed before taking action in creative mode; Type=integer, +Leniency=Increase.
*/
public int FASTBREAK_MAXVIOLATIONS_CREATIVE;
/**
* Time a player is forced to wait after fastbreak has been detected; Type=system, +Leniency=Decrease.
*/
public int FASTBREAK_MAXVIOLATIONTIME;
/**
* Number of blocks that can be broken without being hit before taking action; Type=integer, +Leniency=Increase.
*/
public int FASTPLACE_ZEROLIMIT;
/**
* Minimum time in between block places; Type=system, +Leniency=Decrease.
*/
public int FASTPLACE_TIMEMIN;
/**
* Number of times fastplace can be observed before taking action; Type=integer, +Leniency=Increase.
*/
public int FASTPLACE_MAXVIOLATIONS;
/**
* Number of times fastplace can be observed before taking action in creative mode; Type=integer, +Leniency=Increase.
*/
public int FASTPLACE_MAXVIOLATIONS_CREATIVE;
/**
* Time a player is forced to wait after fastplace has been detected; Type=system, +Leniency=Decrease.
*/
public int FASTPLACE_MAXVIOLATIONTIME;
/**
* Number of times required to punch a block before it breaks; Type=integer, +Leniency=Decrease.
*/
public int BLOCK_PUNCH_MIN;
/**
* Number of chat spam violations before a player is warned; Type=integer, +Leniency=Increase.
*/
public int CHAT_WARN_LEVEL;
/**
* Number of chat spam violations before a player is kicked; Type=integer, +Leniency=Increase.
*/
public int CHAT_KICK_LEVEL;
/**
* Number of kicks for chat violation before a player is banned; Type=integer, +Leniency=Increase.
*/
public int CHAT_BAN_LEVEL;
/**
* Number of times a player can be caught in-flight before action is taken; Type=integer, +Leniency=Increase.
*/
public int FLIGHT_LIMIT;
/**
* How many blocks you can travel before action is taken; Type=integer, +Leniency=Increase.
*/
public double FLIGHT_BLOCK_LIMIT;
/**
* Maximum speed that a player can climb a waterfall; Type=double, +Leniency=Increase.
*/
public double WATER_CLIMB_MAX;
/**
* Number of times a player can fly on the y-axis before action is taken; Type=integer, +Leniency=Increase.
*/
public int Y_MAXVIOLATIONS;
/**
* Time a player is forced to wait after flying on the y-axis; Type=system, +Leniency=Decrease.
*/
public int Y_MAXVIOTIME;
/**
* Number of times a player can fail a velocity check before action is taken; Type=integer, +Leniency=Increase.
*/
public int VELOCITY_TIME;
/**
* Time used to schedule increasing a players velocity count - probably not touching this would be good; Type=integer.
*/
public long VELOCITY_SCHETIME;
/**
* Maximum time a player is considered to have a change in velocity; Type=system, +Leniency=Increase.
*/
public long VELOCITY_CHECKTIME;
/**
* Time to extend a player's velocity count by; Type=system, +Leniency=Increase.
*/
public long VELOCITY_PREVENT;
/**
* Number of times a player can fail the velocity check before action is taken; Type=integer, +Leniency=Increase.
*/
public int VELOCITY_MAXTIMES;
/**
* Number of times a player can fail the nofall check before action is taken; Type=integer, +Leniency=Increase.
*/
public int NOFALL_LIMIT;
/**
* Number of times a player can fail the ascension check before action is taken; Type=integer, +Leniency=Increase.
*/
public int ASCENSION_COUNT_MAX;
/**
* Number of times a player can fail the ascension check while in water before action is taken; Type=integer, +Leniency=Increase.
*/
public int WATER_ASCENSION_VIOLATION_MAX;
/**
* Number of times a player can be caught speeding in water before action is taken; Type=integer, +Leniency=Increase.
*/
public int WATER_SPEED_VIOLATION_MAX;
/**
* Number of times a player can sprint without proper food level before action is taken; Type=integer, +Leniency=Increase.
*/
public int SPRINT_FOOD_MIN;
/**
* Minimum time between animations; Type=system, +Leniency=Increase.
*/
public int ANIMATION_MIN;
/**
* Minimum time between chats; Type=system, +Leniency=Increase.
*/
public int CHAT_MIN;
/**
* Minimum time between repeating yourself in the chat; Type=system, +Leniency=Increase.
*/
public int CHAT_REPEAT_MIN;
/**
* Maximum speed you can travel while sprinting; Type=double, +Leniency=Increase.
*/
public double SPRINT_MIN;
/**
* Minimum time in between block breaks; Type=seconds, +Leniency=Decrease.
*/
public double BLOCK_BREAK_MIN;
/**
* Minimum time in between block placing; Type=seconds, +Leniency=Decrease.
*/
public double BLOCK_PLACE_MIN;
/**
* Minimum time in between healing; Type=system, +Leniency=Decrease.
*/
public long HEAL_TIME_MIN;
/**
* Minimum time in between eating; Type=system, +Leniency=Decrease.
*/
public long EAT_TIME_MIN;
/**
* Maximum percent error between predicted bow force and actual bow force; Type=double, +Leniency=Increase.
*/
public double BOW_ERROR;
/**
* Minimum distance a player can break a block from; Type=double, +Leniency=Increase.
*/
public double BLOCK_MAX_DISTANCE;
/**
* Minimum distance a player can break a block from in creative mode; Type=double, +Leniency=Increase.
*/
public double BLOCK_MAX_DISTANCE_CREATIVE;
/**
* Minimum distance a player can damage an entity from; Type=double, +Leniency=Increase.
*/
public double ENTITY_MAX_DISTANCE;
/**
* Minimum distance a player can damage an entity from in creative mode; Type=double, +Leniency=Increase.
*/
public double ENTITY_MAX_DISTANCE_CREATIVE;
/**
* Maximum speed a player on a ladder can travel; Type=double, +Leniency=Increase.
*/
public double LADDER_Y_MAX;
/**
* Minimum speed a player on a ladder can travel; Type=double, +Leniency=Decrease.
*/
public double LADDER_Y_MIN;
/**
* Maximum speed a player can travel up; Type=double, +Leniency=Increase.
*/
public double Y_SPEED_MAX;
/**
* Maximum difference between the player's last 2 Y values when traveling up; Type=double, +Leniency=Increase.
*/
public double Y_MAXDIFF;
/**
* Time in between Y difference measures; Type=system, +Leniency=Decrease.
*/
public long Y_TIME;
/**
* Maximum speed a player can travel forwards or backwards; Type=double, +Leniency=Increase.
*/
public double XZ_SPEED_MAX;
/**
* Maximum speed a player can travel forwards or backwards while sprinting; Type=double, +Leniency=Increase.
*/
public double XZ_SPEED_MAX_SPRINT;
/**
* Maximum speed a player can travel forwards or backwards while flying; Type=double, +Leniency=Increase.
*/
public double XZ_SPEED_MAX_FLY;
/**
* Maximum speed a player can travel forwards or backwards while under the influence; Type=double, +Leniency=Increase.
*/
public double XZ_SPEED_MAX_POTION;
/**
* Maximum speed a player can travel forwards or backwards while sneaking; Type=double, +Leniency=Increase.
*/
public double XZ_SPEED_MAX_SNEAK;
/**
* Maximum speed a player can travel forwards or backwards in water; Type=double, +Leniency=Increase.
*/
public double XZ_SPEED_MAX_WATER;
/**
* Maximum speed a player can travel forwards or backwards in water while sprinting; Type=double, +Leniency=Increase.
*/
public double XZ_SPEED_MAX_WATER_SPRINT;
/**
* Maximum speed a player can travel forwards or backwards on soul sand; Type=double, +Leniency=Increase.
*/
public double XZ_SPEED_MAX_SOULSAND;
/**
* Maximum speed a player can travel forwards or backwards on soul sand while sprinting; Type=double, +Leniency=Increase.
*/
public double XZ_SPEED_MAX_SOULSAND_SPRINT;
/**
* Maximum speed a player can travel forwards or backwards on soul sand while under the influence; Type=double, +Leniency=Increase.
*/
public double XZ_SPEED_MAX_SOULSAND_POTION;
/**
* Maximum times a player can fail the speed check before action is taken; Type=integer, +Leniency=Increase.
*/
public int SPEED_MAX;
/**
* The number of clicks we should wait before checking if the player has used fast inventory; Type=integer; +Leniency=Increase.
*/
public int INVENTORY_CHECK;
/**
* The minimum time it should have taken for the player to click X times; Type=integer; +Leniency=Increase.
*/
public long INVENTORY_TIMEMIN;
/**
* The number of steps we should wait before checking if the player has used timer cheating; Type=integer; +Leniency=Increase.
*/
public int TIMER_STEP_CHECK;
/**
* The minimum time it should have taken for the player to travel X steps; Type=system; +Leniency=Decrease.
*/
public long TIMER_TIMEMIN;
/**
* Minimum travel distance for move to be considered a teleport and subsequently be ignored; Type=int; +Leniency=Increase.
*/
public long TELEPORT_MIN;
private double version;
public Magic(AntiCheat plugin, Configuration config) {
super(plugin, config, "magic.yml");
}
@Override
public void open() {
version = new ConfigValue<Double>("VERSION").getValue();
if (version == 0.2D) {
// 0.2 -> 0.3 diffs
// Fix improperly stored double Y_MAXDIFF
new ConfigValue<Double>("Y_MAXDIFF").setValue(new ConfigValue<Double>("Y_MAXDIFF").getDefaultValue());
// Update version
version = new ConfigValue<Double>("VERSION").setValue(0.3D);
setNeedsReload(true);
}
ENTERED_EXITED_TIME = new ConfigValue<Integer>("ENTERED_EXITED_TIME").getValue();
SNEAK_TIME = new ConfigValue<Integer>("SNEAK_TIME").getValue();
TELEPORT_TIME = new ConfigValue<Integer>("TELEPORT_TIME").getValue();
EXIT_FLY_TIME = new ConfigValue<Integer>("EXIT_FLY_TIME").getValue();
JOIN_TIME = new ConfigValue<Integer>("JOIN_TIME").getValue();
INSTANT_BREAK_TIME = new ConfigValue<Integer>("INSTANT_BREAK_TIME").getValue();
DAMAGE_TIME = new ConfigValue<Integer>("DAMAGE_TIME").getValue();
KNOCKBACK_DAMAGE_TIME = new ConfigValue<Integer>("KNOCKBACK_DAMAGE_TIME").getValue();
EXPLOSION_DAMAGE_TIME = new ConfigValue<Integer>("EXPLOSION_DAMAGE_TIME").getValue();
PROJECTILE_TIME_MIN = new ConfigValue<Integer>("PROJECTILE_TIME_MIN").getValue();
PROJECTILE_CHECK = new ConfigValue<Integer>("PROJECTILE_CHECK").getValue();
DROP_TIME_MIN = new ConfigValue<Integer>("DROP_TIME_MIN").getValue();
DROP_CHECK = new ConfigValue<Integer>("DROP_CHECK").getValue();
FASTBREAK_LIMIT = new ConfigValue<Integer>("FASTBREAK_LIMIT").getValue();
FASTBREAK_TIMEMAX = new ConfigValue<Integer>("FASTBREAK_TIMEMAX").getValue();
FASTBREAK_TIMEMAX_CREATIVE = new ConfigValue<Integer>("FASTBREAK_TIMEMAX_CREATIVE").getValue();
FASTBREAK_MAXVIOLATIONS = new ConfigValue<Integer>("FASTBREAK_MAXVIOLATIONS").getValue();
FASTBREAK_MAXVIOLATIONS_CREATIVE = new ConfigValue<Integer>("FASTBREAK_MAXVIOLATIONS_CREATIVE").getValue();
FASTBREAK_MAXVIOLATIONTIME = new ConfigValue<Integer>("FASTBREAK_MAXVIOLATIONTIME").getValue();
FASTPLACE_ZEROLIMIT = new ConfigValue<Integer>("FASTPLACE_ZEROLIMIT").getValue();
FASTPLACE_TIMEMIN = new ConfigValue<Integer>("FASTPLACE_TIMEMIN").getValue();
FASTPLACE_MAXVIOLATIONS = new ConfigValue<Integer>("FASTPLACE_MAXVIOLATIONS").getValue();
FASTPLACE_MAXVIOLATIONS_CREATIVE = new ConfigValue<Integer>("FASTPLACE_MAXVIOLATIONS_CREATIVE").getValue();
FASTPLACE_MAXVIOLATIONTIME = new ConfigValue<Integer>("FASTPLACE_MAXVIOLATIONTIME").getValue();
BLOCK_PUNCH_MIN = new ConfigValue<Integer>("BLOCK_PUNCH_MIN").getValue();
CHAT_WARN_LEVEL = new ConfigValue<Integer>("CHAT_WARN_LEVEL").getValue();
CHAT_KICK_LEVEL = new ConfigValue<Integer>("CHAT_KICK_LEVEL").getValue();
CHAT_BAN_LEVEL = new ConfigValue<Integer>("CHAT_BAN_LEVEL").getValue();
FLIGHT_LIMIT = new ConfigValue<Integer>("FLIGHT_LIMIT").getValue();
FLIGHT_BLOCK_LIMIT = new ConfigValue<Double>("FLIGHT_BLOCK_LIMIT").getValue();
WATER_CLIMB_MAX = new ConfigValue<Double>("WATER_CLIMB_MAX").getValue();
Y_MAXVIOLATIONS = new ConfigValue<Integer>("Y_MAXVIOLATIONS").getValue();
Y_MAXVIOTIME = new ConfigValue<Integer>("Y_MAXVIOTIME").getValue();
VELOCITY_TIME = new ConfigValue<Integer>("VELOCITY_TIME").getValue();
VELOCITY_SCHETIME = new ConfigValue<Integer>("VELOCITY_SCHETIME").getValue();
VELOCITY_CHECKTIME = new ConfigValue<Integer>("VELOCITY_CHECKTIME").getValue();
VELOCITY_PREVENT = new ConfigValue<Integer>("VELOCITY_PREVENT").getValue();
VELOCITY_MAXTIMES = new ConfigValue<Integer>("VELOCITY_MAXTIMES").getValue();
NOFALL_LIMIT = new ConfigValue<Integer>("NOFALL_LIMIT").getValue();
ASCENSION_COUNT_MAX = new ConfigValue<Integer>("ASCENSION_COUNT_MAX").getValue();
WATER_ASCENSION_VIOLATION_MAX = new ConfigValue<Integer>("WATER_ASCENSION_VIOLATION_MAX").getValue();
WATER_SPEED_VIOLATION_MAX = new ConfigValue<Integer>("WATER_SPEED_VIOLATION_MAX").getValue();
SPRINT_FOOD_MIN = new ConfigValue<Integer>("SPRINT_FOOD_MIN").getValue();
ANIMATION_MIN = new ConfigValue<Integer>("ANIMATION_MIN").getValue();
CHAT_MIN = new ConfigValue<Integer>("CHAT_MIN").getValue();
CHAT_REPEAT_MIN = new ConfigValue<Integer>("CHAT_REPEAT_MIN").getValue();
SPRINT_MIN = new ConfigValue<Double>("SPRINT_MIN").getValue();
BLOCK_BREAK_MIN = new ConfigValue<Double>("BLOCK_BREAK_MIN").getValue();
BLOCK_PLACE_MIN = new ConfigValue<Double>("BLOCK_PLACE_MIN").getValue();
HEAL_TIME_MIN = new ConfigValue<Integer>("HEAL_TIME_MIN").getValue();
EAT_TIME_MIN = new ConfigValue<Integer>("EAT_TIME_MIN").getValue();
BOW_ERROR = new ConfigValue<Double>("BOW_ERROR").getValue();
BLOCK_MAX_DISTANCE = new ConfigValue<Double>("BLOCK_MAX_DISTANCE").getValue();
BLOCK_MAX_DISTANCE_CREATIVE = new ConfigValue<Double>("BLOCK_MAX_DISTANCE_CREATIVE").getValue();
ENTITY_MAX_DISTANCE = new ConfigValue<Double>("ENTITY_MAX_DISTANCE").getValue();
ENTITY_MAX_DISTANCE_CREATIVE = new ConfigValue<Double>("ENTITY_MAX_DISTANCE_CREATIVE").getValue();
LADDER_Y_MAX = new ConfigValue<Double>("LADDER_Y_MAX").getValue();
LADDER_Y_MIN = new ConfigValue<Double>("LADDER_Y_MIN").getValue();
Y_SPEED_MAX = new ConfigValue<Double>("Y_SPEED_MAX").getValue();
Y_MAXDIFF = new ConfigValue<Double>("Y_MAXDIFF").getValue();
Y_TIME = new ConfigValue<Integer>("Y_TIME").getValue();
XZ_SPEED_MAX = new ConfigValue<Double>("XZ_SPEED_MAX").getValue();
XZ_SPEED_MAX_SPRINT = new ConfigValue<Double>("XZ_SPEED_MAX_SPRINT").getValue();
XZ_SPEED_MAX_FLY = new ConfigValue<Double>("XZ_SPEED_MAX_FLY").getValue();
XZ_SPEED_MAX_POTION = new ConfigValue<Double>("XZ_SPEED_MAX_POTION").getValue();
XZ_SPEED_MAX_SNEAK = new ConfigValue<Double>("XZ_SPEED_MAX_SNEAK").getValue();
XZ_SPEED_MAX_WATER = new ConfigValue<Double>("XZ_SPEED_MAX_WATER").getValue();
XZ_SPEED_MAX_SOULSAND = new ConfigValue<Double>("XZ_SPEED_MAX_SOULSAND").getValue();
XZ_SPEED_MAX_SOULSAND_SPRINT = new ConfigValue<Double>("XZ_SPEED_MAX_SOULSAND_SPRINT").getValue();
XZ_SPEED_MAX_SOULSAND_POTION = new ConfigValue<Double>("XZ_SPEED_MAX_SOULSAND_POTION").getValue();
XZ_SPEED_MAX_WATER_SPRINT = new ConfigValue<Double>("XZ_SPEED_MAX_WATER_SPRINT").getValue();
SPEED_MAX = new ConfigValue<Integer>("SPEED_MAX").getValue();
INVENTORY_CHECK = new ConfigValue<Integer>("INVENTORY_CHECK").getValue();
INVENTORY_TIMEMIN = new ConfigValue<Integer>("INVENTORY_TIMEMIN").getValue();
TIMER_STEP_CHECK = new ConfigValue<Integer>("TIMER_STEP_CHECK").getValue();
TIMER_TIMEMIN = new ConfigValue<Integer>("TIMER_TIMEMIN").getValue();
TELEPORT_MIN = new ConfigValue<Integer>("TELEPORT_MIN").getValue();
ANIMATION_CHECK = new ConfigValue<Integer>("ANIMATION_CHECK").getValue();
ANIMATION_TIMEMIN = new ConfigValue<Integer>("ANIMATION_TIMEMIN").getValue();
}
public double getVersion() {
return version;
}
}
@@ -0,0 +1,87 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.holders.mysql;
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;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MySQLEventsHolder extends ConfigurationTable implements Events {
private static final String TABLE = "events";
private List<Level> levels;
private int highestLevel;
public MySQLEventsHolder(Configuration config) {
super(config, TABLE);
}
@Override
public void open() {
highestLevel = 0;
levels = new ArrayList<Level>();
String sqlCreate = "CREATE TABLE IF NOT EXISTS " + getFullTable() + "(" +
" `id` INT NOT NULL," +
" `name` VARCHAR(45) NOT NULL," +
" `level` INT NOT NULL," +
" `color` VARCHAR(45) NOT NULL," +
" `actions` VARCHAR(45) NOT NULL," +
" PRIMARY KEY (`id`));";
String sqlLoad = "SELECT * FROM " + getFullTable();
try {
getConnection().prepareStatement(sqlCreate).executeUpdate();
getConnection().commit();
ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery();
while (set.next()) {
String name = set.getString("name");
int level = set.getInt("level");
String color = set.getString("color");
List<String> actions = Arrays.asList(set.getString("actions").split(","));
levels.add(new Level(name, level, color, actions));
if (level > highestLevel) {
highestLevel = level;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public List<Level> getLevels() {
return levels;
}
@Override
public int getHighestLevel() {
return highestLevel;
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.holders.mysql;
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;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class MySQLLevelsHolder extends ConfigurationTable implements Levels {
private static final String TABLE = "levels";
private String sqlSave;
private String sqlLoad;
public MySQLLevelsHolder(Configuration config) {
super(config, TABLE);
}
@Override
public void open() {
sqlSave = "INSERT INTO " + getFullTable() +
" (user, level, last_update_server) " +
"VALUES (?, ?, ?) " +
"ON DUPLICATE KEY UPDATE " +
"level = IF(last_update = ?, ?, level+?), " +
"last_update=CURRENT_TIMESTAMP, " +
"last_update_server=?";
sqlLoad = "SELECT level, last_update FROM " + getFullTable() + " " +
"WHERE user = ?";
String sqlCreate = "CREATE TABLE IF NOT EXISTS " + getFullTable() + "(" +
" `user` VARCHAR(45) NOT NULL," +
" `level` INT NOT NULL," +
" `last_update` TIMESTAMP NOT NULL DEFAULT NOW()," +
" `last_update_server` VARCHAR(45) NOT NULL," +
" PRIMARY KEY (`user`));";
try {
getConnection().prepareStatement(sqlCreate).executeUpdate();
getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void saveLevelFromUser(final User user) {
Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
if (!user.isWaitingOnLevelSync()) {
AntiCheat.debugLog("Syncing to " + user.getName() + " value " + user.getLevel());
try {
PreparedStatement statement = getConnection().prepareStatement(sqlSave);
statement.setString(1, user.getName());
statement.setInt(2, user.getLevel());
statement.setString(3, getServerName());
statement.setTimestamp(4, user.getLevelSyncTimestamp());
statement.setInt(5, user.getLevel());
statement.setInt(6, user.getLevel());
statement.setString(7, getServerName());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
AntiCheat.getManager().getUserManager().remove(user);
}
});
}
@Override
public void loadLevelToUser(final User user) {
Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
try {
PreparedStatement statement = getConnection().prepareStatement(sqlLoad);
statement.setString(1, user.getName());
ResultSet set = statement.executeQuery();
boolean has = false;
while (set.next()) {
has = true;
AntiCheat.debugLog("Syncing from " + user.getName() + " value " + set.getInt("level"));
user.setLevel(set.getInt("level"));
user.setLevelSyncTimestamp(set.getTimestamp("last_update"));
}
if (!has) user.setLevel(0);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
@Override
public void saveLevelsFromUsers(List<User> users) {
try {
PreparedStatement statement = getConnection().prepareStatement(sqlSave);
for (User user : users) {
if (!user.isWaitingOnLevelSync()) {
try {
statement.setString(1, user.getName());
statement.setInt(2, user.getLevel());
statement.setString(3, getServerName());
statement.setTimestamp(4, user.getLevelSyncTimestamp());
statement.setInt(5, user.getLevel());
statement.setInt(6, user.getLevel());
statement.setString(7, getServerName());
statement.addBatch();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
statement.executeBatch();
getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,74 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.holders.mysql;
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;
import java.util.ArrayList;
import java.util.List;
public class MySQLRulesHolder extends ConfigurationTable implements Rules {
private static final String TABLE = "rules";
private List<Rule> rules;
public MySQLRulesHolder(Configuration config) {
super(config, TABLE);
}
@Override
public void open() {
String sqlCreate = "CREATE TABLE IF NOT EXISTS " + getFullTable() + "(" +
" `id` INT NOT NULL AUTO_INCREMENT," +
" `rule` VARCHAR(45) NOT NULL," +
" PRIMARY KEY (`id`));";
String sqlLoad = "SELECT * FROM " + getFullTable();
try {
getConnection().prepareStatement(sqlCreate).executeUpdate();
getConnection().commit();
this.rules = new ArrayList<Rule>();
ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery();
while (set.next()) {
String string = set.getString("rule");
Rule rule = Rule.load(string);
if (rule != null) {
this.rules.add(rule);
} else {
AntiCheat.getPlugin().getLogger().warning("Couldn't load rule '" + string + "' from the database. Improper format used.");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Rule> getRules() {
return rules;
}
}
@@ -0,0 +1,86 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.holders.yaml;
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.*;
public class YamlEventsHolder extends ConfigurationFile implements Events {
public static final String FILENAME = "events.yml";
private List<Level> levels;
private int highestLevel;
public YamlEventsHolder(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
@Override
public List<Level> getLevels() {
return levels;
}
@Override
public int getHighestLevel() {
return highestLevel;
}
@Override
public void open() {
ConfigValue<List<String>> levels = new ConfigValue<List<String>>("events");
// Clean up old values
if(levels.didLoadDefault()) {
new ConfigValue<List<String>>("levels").setValue(null);
new ConfigValue<List<String>>("actions").setValue(null);
save();
}
// Convert levels list to Levels
this.levels = new ArrayList<Level>();
for (String string : levels.getValue()) {
Level level = Level.load(string);
if (level == null || level.getValue() < 0) {
continue;
}
this.levels.add(level);
highestLevel = level.getValue() > highestLevel ? level.getValue() : highestLevel;
}
// Sort levels
Collections.sort(this.levels, new Comparator<Level>() {
public int compare(Level l1, Level l2) {
if (l1.getValue() == l2.getValue()) {
return 0;
} else if (l1.getValue() < l2.getValue()) {
return -1;
}
return 1;
}
});
}
}
@@ -0,0 +1,71 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.holders.yaml;
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;
public class YamlLevelsHolder extends ConfigurationFile implements Levels {
public static final String FILENAME = "data/levels.yml";
public YamlLevelsHolder(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME, false);
}
@Override
public void loadLevelToUser(User user) {
user.setLevel(getLevel(user.getName()));
}
@Override
public void saveLevelFromUser(User user) {
saveLevelFromUser(user, true);
}
private void saveLevelFromUser(User user, boolean remove) {
saveLevel(user.getName(), user.getLevel());
if (remove) AntiCheat.getManager().getUserManager().remove(user);
}
@Override
public void saveLevelsFromUsers(List<User> users) {
for (User user : users) {
saveLevelFromUser(user, false);
}
}
private int getLevel(String name) {
ConfigValue<Integer> level = new ConfigValue<Integer>(name, false);
if (level.hasValue()) {
return level.getValue();
} else {
return 0;
}
}
private void saveLevel(String name, int level) {
new ConfigValue<Integer>(name, false).setValue(new Integer(level));
}
}
@@ -0,0 +1,68 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.holders.yaml;
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;
public class YamlRulesHolder extends ConfigurationFile implements Rules {
public static final String FILENAME = "events.yml";
private List<Rule> rules;
public YamlRulesHolder(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
@Override
public List<Rule> getRules() {
return rules;
}
@Override
public void open() {
ConfigValue<List<String>> rules = new ConfigValue<List<String>>("rules");
// Convert rules list to Rules
this.rules = new ArrayList<Rule>();
List<String> tempRules = rules.getValue();
for (int i = 0; i < tempRules.size(); i++) {
String string = tempRules.get(i);
if (string.equals("Check_SPIDER < 0 ? Player.KICK : null")) {
// Default rule, won't ever run so we shouldn't load it; only used as example
continue;
}
Rule rule = Rule.load(string);
if (rule != null) {
this.rules.add(rule);
} else {
AntiCheat.getPlugin().getLogger().warning("Couldn't load rule '" + string + "' from config. Improper format used.");
}
}
}
}
@@ -0,0 +1,30 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.providers;
import net.gravitydevelopment.anticheat.util.Level;
import java.util.List;
public interface Events {
public List<Level> getLevels();
public int getHighestLevel();
}
@@ -0,0 +1,32 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.providers;
import net.gravitydevelopment.anticheat.manage.User;
import java.util.List;
public interface Levels {
public void loadLevelToUser(User user);
public void saveLevelFromUser(User user);
public void saveLevelsFromUsers(List<User> users);
}
@@ -0,0 +1,29 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.providers;
import net.gravitydevelopment.anticheat.util.rule.Rule;
import java.util.List;
public interface Rules {
public List<Rule> getRules();
}
@@ -0,0 +1,200 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.config.yaml;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.file.YamlConstructor;
import org.bukkit.configuration.file.YamlRepresenter;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.representer.Representer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
/**
* An extension of {@link org.bukkit.configuration.file.YamlConfiguration} which preserves comments.
* Note that this implementation is not synchronized.
* <br>
* Some overridden code has been moved to this file from its parent & modified.
*/
public class CommentedConfiguration extends YamlConfiguration {
private Map<Integer, String> comments = new HashMap<Integer, String>();
private final DumperOptions yamlOptions = new DumperOptions();
private final Representer yamlRepresenter = new YamlRepresenter();
private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
@Override
public void loadFromString(String contents) throws InvalidConfigurationException {
Validate.notNull(contents, "Contents cannot be null");
Map<?, ?> input;
try {
input = (Map<?, ?>) yaml.load(contents);
} catch (YAMLException e) {
throw new InvalidConfigurationException(e);
} catch (ClassCastException e) {
throw new InvalidConfigurationException("Top level is not a Map.");
}
/** - CommentedConfiguration
String header = parseHeader(contents);
if (header.length() > 0) {
options().header(header);
}
**/
if (input != null) {
convertMapsToSections(input, this);
}
// Begin CommentedConfiguration
int i = 0;
int blank = 0;
String[] lines = contents.split("\n");
while (i < lines.length) {
if (lines[i].trim().equalsIgnoreCase("")) {
i++;
blank++;
continue;
}
if (lines[i].contains(COMMENT_PREFIX)) {
comments.put(i - blank, lines[i]);
}
i++;
}
// End CommentedConfiguration
}
@Override
public String saveToString() {
yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
// String header = buildHeader(); - CommentedConfiguration
String dump = yaml.dump(getValues(false));
if (dump.equals(BLANK_CONFIG)) {
dump = "";
}
// Begin CommentedConfiguration
StringBuilder builder = new StringBuilder();
String[] lines = dump.split("\n");
ArrayDeque<String> queue = new ArrayDeque<String>();
for (String string : lines) {
queue.add(string);
}
int i = 0;
while (queue.size() > 0) {
if (comments.containsKey(i)) {
builder.append(comments.get(i));
// Handle subsequent comments
int b = i;
while (true) {
b++;
if (comments.containsKey(b)) {
builder.append('\n');
builder.append(comments.get(b));
} else {
break;
}
}
builder.append('\n');
i = b;
}
builder.append(queue.getFirst());
builder.append('\n');
queue.pop();
i++;
}
// End CommentedConfiguration
return builder.toString();
}
/**
* Creates a new {@link CommentedConfiguration}, loading from the given file.
* <p/>
* Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be returned.
*
* @param file Input file
* @return Resulting configuration
* @throws IllegalArgumentException Thrown if file is null
*/
public static CommentedConfiguration loadConfiguration(File file) {
Validate.notNull(file, "File cannot be null");
CommentedConfiguration config = new CommentedConfiguration();
try {
config.load(file);
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex);
} catch (InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex);
}
return config;
}
/**
* Creates a new {@link CommentedConfiguration}, loading from the given stream.
* <p/>
* Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be returned.
*
* @param stream Input stream
* @return Resulting configuration
* @throws IllegalArgumentException Thrown if stream is null
*/
public static CommentedConfiguration loadConfiguration(InputStream stream) {
Validate.notNull(stream, "Stream cannot be null");
CommentedConfiguration config = new CommentedConfiguration();
try {
config.load(stream);
} catch (IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex);
} catch (InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex);
}
return config;
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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);
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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());
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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<CheckType, Integer> USAGE_LIST = new EnumMap<CheckType, Integer>(CheckType.class);
private static final Map<String, Integer> DECREASE_LIST = new HashMap<String, Integer>();
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();
}
}
@@ -0,0 +1,70 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
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 org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType;
public class InventoryListener extends EventListener {
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (!event.isRightClick() && !event.isShiftClick() && event.getWhoClicked() instanceof Player) {
Player player = (Player) event.getWhoClicked();
if (getCheckManager().willCheck(player, CheckType.FAST_INVENTORY)) {
CheckResult result = getBackend().checkInventoryClicks(player);
if (result.failed()) {
if (!silentMode()) {
//getUserManager().getUser(player.getName()).restoreInventory(event.getInventory());
player.getInventory().clear();
event.setCancelled(true);
}
log(result.getMessage(), player, CheckType.FAST_INVENTORY);
} else {
decrease(player);
}
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onInventoryOpen(InventoryOpenEvent event) {
if (event.getInventory().getType() != InventoryType.BEACON) {
getUserManager().getUser(event.getPlayer().getName()).setInventorySnapshot(event.getInventory().getContents());
}
}
@EventHandler
public void onInventoryClose(InventoryCloseEvent event) {
User user = getUserManager().getUser(event.getPlayer().getName());
if (user != null) {
user.removeInventorySnapshot();
}
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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);
}
}
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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());
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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<String, RegisteredListener[]> eventchains = new ConcurrentHashMap<String, RegisteredListener[]>();
private static Map<String, Long> eventcache = new ConcurrentHashMap<String, Long>();
private static List<String> logs = new CopyOnWriteArrayList<String>();
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<String> getLastLogs() {
List<String> log = new CopyOnWriteArrayList<String>();
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<String, RegisteredListener[]> 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();
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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;
/**
* <p/>
* 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<CheckType> checkIgnoreList = new ArrayList<CheckType>();
private static Map<String, List<CheckType>> exemptList = new HashMap<String, List<CheckType>>();
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<CheckType>());
}
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;
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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;
/**
* <p/>
* 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<String, Integer> level = new HashMap<String, Integer>();
/**
* 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);
}
}
@@ -0,0 +1,37 @@
package net.gravitydevelopment.anticheat.manage;
import com.comphenix.protocol.Packets;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.*;
import net.gravitydevelopment.anticheat.AntiCheat;
public class PacketManager {
private ProtocolManager protocolManager;
private AntiCheat plugin;
private AnticheatManager manager;
public PacketManager(ProtocolManager protocolManager, AntiCheat plugin, AnticheatManager manager) {
this.protocolManager = protocolManager;
this.plugin = plugin;
this.manager = manager;
addListeners();
}
private void addListeners() {
// Arm Animation
protocolManager.addPacketListener(new PacketAdapter(plugin,
ConnectionSide.CLIENT_SIDE,
ListenerPriority.NORMAL,
Packets.Client.ARM_ANIMATION) {
@Override
public void onPacketReceiving(PacketEvent event) {
if (event.getPacketID() == Packets.Client.ARM_ANIMATION) {
PacketContainer packet = event.getPacket();
//System.out.println("Arm animation from "+packet.getIntegers().read(0));
}
}
});
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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<ItemStack> 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<Level> 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<ItemStack>();
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<Level> 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;
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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<User> users = new ArrayList<User>();
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<String> 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<User> 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<String> messageArray = new ArrayList<String>();
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<String> 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<String> actions, final CheckType type, final String kickReason, final List<String> 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<String> 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();
}
}
}
});
}
}
@@ -0,0 +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.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.
* <p/>
* <b>VERY, VERY IMPORTANT</b>: 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.
* <br>
* It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config that prevents the auto-updater from running <b>AT ALL</b>.
* <br>
* If you fail to include this option in your config, your plugin will be <b>REJECTED</b> when you attempt to submit it to dev.bukkit.org.
* <p/>
* 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.
* <br>
* 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<? extends ZipEntry> 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;
}
}
}
}
}
}
}
@@ -0,0 +1,213 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import org.bukkit.Material;
public enum BlockHardness {
STONE(1.50D),
GRASS(0.60D),
DIRT(0.50D),
COBBLESTONE(2.00D),
WOOD(2.00D),
SAPLING(0.00D),
WATER(100.00D),
STATIONARY_WATER(100.00D),
LAVA(0.00D),
STATIONARY_LAVA(100.00D),
SAND(0.50D),
GRAVEL(0.60D),
GOLD_ORE(3.00D),
IRON_ORE(3.00D),
COAL_ORE(3.00D),
LOG(2.00D),
LEAVES(0.20D),
SPONGE(0.60D),
GLASS(0.30D),
LAPIS_ORE(3.00D),
LAPIS_BLOCK(3.00D),
DISPENSER(3.50D),
DROPPER(3.50D),
SANDSTONE(0.80D),
NOTE_BLOCK(0.80D),
BED(0.20D),
RAILS(0.70D),
DETECTOR_RAIL(0.70D),
POWERED_RAIL(0.70D),
ACTIVATOR_RAIL(0.70D),
WEB(4.00D),
LONG_GRASS(0.00D),
DEAD_BUSH(0.00D),
WOOL(0.80D),
YELLOW_FLOWER(0.00D),
RED_ROSE(0.00D),
BROWN_MUSHROOM(0.00D),
RED_MUSHROOM(0.00D),
GOLD_BLOCK(3.00D),
IRON_BLOCK(5.00D),
DOUBLE_STEP(2.00D),
STEP(2.00D),
BRICK(2.00D),
TNT(0.00D),
BOOKSHELF(1.50D),
MOSSY_COBBLESTONE(2.00D),
OBSIDIAN(50.00D),
TORCH(0.00D),
FIRE(0.00D),
MOB_SPAWNER(5.00D),
CHEST(2.50D),
TRAPPED_CHEST(2.50D),
REDSTONE_WIRE(0.00D),
DIAMOND_ORE(3.00D),
DIAMOND_BLOCK(5.00D),
WORKBENCH(2.50D),
SOIL(0.60D),
FURNACE(3.50D),
BURNING_FURNACE(3.50D),
WOODEN_DOOR(3.00D),
LADDER(0.40D),
LEVER(0.50D),
IRON_DOOR_BLOCK(5.00D),
HOPPER(2.00D),
STONE_PLATE(0.50D),
WOOD_PLATE(0.50D),
GOLD_PLATE(0.50D),
IRON_PLATE(0.50D),
QUARTZ_BLOCK(0.80D),
QUARTZ_ORE(3.00D),
QUARTZ_STAIRS(0.80D),
REDSTONE_BLOCK(5.00D),
REDSTONE_ORE(3.00D),
GLOWING_REDSTONE_ORE(3.00D),
REDSTONE_TORCH_OFF(0.00D),
REDSTONE_TORCH_ON(0.00D),
REDSTONE_COMPARATOR_OFF(0.00D),
REDSTONE_COMPARATOR_ON(0.00D),
DAYLIGHT_DETECTOR(0.20D),
STONE_BUTTON(0.50D),
SNOW(0.10D),
ICE(0.50D),
SNOW_BLOCK(0.20D),
CACTUS(0.40D),
CLAY(0.60D),
HARD_CLAY(1.25D),
STAINED_CLAY(1.25D),
SUGAR_CANE_BLOCK(0.00D),
JUKEBOX(2.00D),
FENCE(2.00D),
NETHERRACK(0.40D),
SOUL_SAND(0.50D),
GLOWSTONE(0.30D),
PORTAL(-1.00D),
CAKE_BLOCK(0.50D),
LOCKED_CHEST(0.00D),
TRAP_DOOR(3.00D),
MONSTER_EGGS(0.750D),
SMOOTH_BRICK(1.50D),
IRON_FENCE(5.00D),
THIN_GLASS(0.30D),
PUMPKIN_STEM(0.00D),
MELON_STEM(0.00D),
VINE(0.20D),
FENCE_GATE(2.00D),
MYCEL(0.60D),
WATER_LILY(0.00D),
NETHER_BRICK(2.00D),
NETHER_FENCE(2.00D),
ENCHANTMENT_TABLE(5.00D),
BREWING_STAND(0.50D),
CAULDRON(2.00D),
ENDER_PORTAL(-1.00D),
ENDER_PORTAL_FRAME(-1.00D),
DRAGON_EGG(3.00D),
REDSTONE_LAMP_OFF(0.30D),
REDSTONE_LAMP_ON(0.30D),
WOOD_DOUBLE_STEP(2.00D),
WOOD_STEP(2.00D),
COCOA(0.20D),
EMERALD_ORE(3.00D),
ENDER_CHEST(22.50D),
EMERALD_BLOCK(5.00D),
FLOWER_POT(0.00D),
WOOD_BUTTON(0.50D),
ANVIL(5.00D),
HUGE_MUSHROOM_1(0.20D),
HUGE_MUSHROOM_2(0.20D),
BED_BLOCK(0.20D),
WOOD_STAIRS(2.00D),
COBBLESTONE_STAIRS(2.00D),
BRICK_STAIRS(2.00D),
SMOOTH_STAIRS(2.00D),
NETHER_BRICK_STAIRS(2.00D),
SANDSTONE_STAIRS(2.00D),
SPRUCE_WOOD_STAIRS(2.00D),
BIRCH_WOOD_STAIRS(2.00D),
JUNGLE_WOOD_STAIRS(2.00D),
COMMAND(0.00D),
BEACON(3.00D),
COBBLE_WALL(2.00D),
CROPS(0.00D),
CARROT(0.00D),
POTATO(0.00D),
SKULL(1.00D),
NETHER_WARTS(0.00D),
SIGN_POST(1.00D),
WALL_SIGN(1.00D),
PUMPKIN(1.00D),
JACK_O_LANTERN(1.00D),
DIODE_BLOCK_ON(0.00D),
DIODE_BLOCK_OFF(0.00D),
MELON_BLOCK(1.00D),
ENDER_STONE(3.00D),
TRIPWIRE(0.00D),
TRIPWIRE_HOOK(0.00D),
HAY_BLOCK(0.50D),
CARPET(0.10D),
COAL_BLOCK(5.00D),
PISTON_BASE(0.70D),
PISTON_EXTENSION(0.70D),
PISTON_MOVING_PIECE(0.70D),
PISTON_STICKY_BASE(0.70D);
Material mat;
double hardness;
BlockHardness(double hard) {
mat = Material.getMaterial(name());
hardness = hard;
}
public static double getBlockHardness(Material m) {
BlockHardness h = getHardness(m);
return h == null ? 0D : h.hardness;
}
public static boolean hasBlockHardness(Material m) {
return getHardness(m) != null;
}
public static BlockHardness getHardness(Material m) {
for (BlockHardness e : BlockHardness.values()) {
if (e.mat.equals(m)) {
return e;
}
}
return null;
}
}
@@ -0,0 +1,239 @@
// 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;
}
}
}
}
}
@@ -0,0 +1,61 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
public class CheckResult {
public enum Result {
PASSED, FAILED
}
private Result result;
private String message;
private int data;
public CheckResult(Result result, String message, int data) {
this(result, message);
this.data = data;
}
public CheckResult(Result result, String message) {
this(result);
this.message = message;
}
public CheckResult(Result result) {
this.result = result;
}
public boolean failed() {
return result == Result.FAILED;
}
public String getMessage() {
return message;
}
public Result getResult() {
return result;
}
public int getData() {
return data;
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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;
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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();
}
}
@@ -0,0 +1,94 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import net.gravitydevelopment.anticheat.AntiCheat;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Level {
private String name;
private int value;
private ChatColor color = ChatColor.RED;
private List<String> actions = new ArrayList<String>();
public Level(String name, int value, String color, List<String> actions) {
this.name = name;
this.value = value;
this.actions = actions;
ChatColor c = ChatColor.valueOf(color);
if (c == null) {
AntiCheat.getPlugin().getLogger().warning("Event '" + name + "' was initialized with the color '" + color + "' which is invalid.");
AntiCheat.getPlugin().getLogger().warning("This event will not run properly. See http://jd.bukkit.org/apidocs/org/bukkit/ChatColor.html#enum_constant_summary for a list of valid colors");
} else {
this.color = c;
}
}
public void setValue(int value) {
this.value = value;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public ChatColor getColor() {
return color;
}
public List<String> getActions() {
return actions;
}
public static Level load(String string) {
try {
if (string.split(":").length == 4) {
string = Utilities.removeWhitespace(string);
String name = string.split(":")[0];
int level = Integer.parseInt(string.split(":")[1]);
String color = string.split(":")[2];
List<String> actions = Arrays.asList(string.split(":")[3].split(","));
return new Level(name, level, color, actions);
} else {
throw new Exception();
}
} catch (Exception ex) {
AntiCheat.getPlugin().getLogger().warning("An event was initialized with an invalid string: '" + string + "'");
AntiCheat.getPlugin().getLogger().warning("The proper format is: 'name : threshold : color : action' such as 'High : 50 : RED : KICK'");
AntiCheat.getPlugin().getLogger().warning("This event will NOT run. (" + ex.getMessage() + ")");
return null;
}
}
@Override
public String toString() {
return name + " : " + value + " : " + color.name() + " : " + Utilities.listToCommaString(actions);
}
}
@@ -0,0 +1,216 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
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;
import org.bukkit.entity.Player;
import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class PastebinReport {
private StringBuilder report = new StringBuilder();
private String url = "";
private Date date = new Date();
private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd kk:mm Z");
public PastebinReport(CommandSender cs) {
Player player = null;
if (cs instanceof Player) {
player = (Player) cs;
}
createReport(player);
try {
writeReport();
} catch (IOException e) {
}
postReport();
}
public PastebinReport(CommandSender cs, Player tp) {
createReport(tp);
try {
writeReport();
} catch (IOException e) {
}
postReport();
}
public String getURL() {
return url;
}
private void appendPermissionsTester(Player player) {
if (player == null) {
append("No player defined.");
return;
}
for (Permission node : Permission.values()) {
report.append(player.getName() + ": " + node.toString() + " " + node.get(player));
if (node.get(player) && !node.whichPermission(player).equals(node.toString())) {
report.append(" (Applied by " + node.whichPermission(player) + ")");
}
report.append('\n');
}
}
private void createReport(Player player) {
if (Bukkit.getPluginManager().getPlugin("NoCheatPlus") != null) {
append("------------ WARNING! ------------");
append("This report was run with NoCheatPlus enabled. Results may be inaccurate." + '\n');
}
append("------------ AntiCheat Report - " + format.format(date) + " ------------");
appendSystemInfo();
append("------------Last 30 logs------------");
appendLogs();
append("------------Permission Tester------------");
appendPermissionsTester(player);
append("------------Event Chains------------");
appendEventHandlers();
append("------------Magic Diff------------");
appendMagicDiff();
append("-----------End Of Report------------");
}
private void appendLogs() {
List<String> logs = AntiCheat.getManager().getLastLogs();
if (logs.size() == 0) {
append("No recent logs.");
return;
}
for (String log : logs) {
append(log);
}
}
private void appendSystemInfo() {
Runtime runtime = Runtime.getRuntime();
append("AntiCheat Version: " + AntiCheat.getVersion() + (AntiCheat.isUpdated() ? "" : " (OUTDATED)"));
append("Server Version: " + Bukkit.getVersion());
append("Server Implementation: " + Bukkit.getName());
append("Server ID: " + Bukkit.getServerId());
append("Java Version: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version"));
append("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
append("Free Memory: " + runtime.freeMemory() / 1024 / 1024 + "MB");
append("Max Memory: " + runtime.maxMemory() / 1024 / 1024 + "MB");
append("Total Memory: " + runtime.totalMemory() / 1024 / 1024 + "MB");
append("Online Mode: " + String.valueOf(Bukkit.getOnlineMode()).toUpperCase());
append("Players: " + Bukkit.getOnlinePlayers().length + "/" + Bukkit.getMaxPlayers());
append("Plugin Count: " + Bukkit.getPluginManager().getPlugins().length);
}
private void appendMagicDiff() {
// This is hacky, and I like it
Magic magic = AntiCheat.getManager().getConfiguration().getMagic();
FileConfiguration file = magic.getDefaultConfigFile();
append("Version: " + magic.getVersion());
boolean changed = false;
for (Field field : Magic.class.getFields()) {
Object defaultValue = file.get(field.getName());
try {
Field value = magic.getClass().getDeclaredField(field.getName());
boolean x = false;
String s1 = value.get(magic).toString();
String s2 = defaultValue.toString();
if (!s1.equals(s2) && !s1.equals(s2 + ".0")) {
changed = true;
append(field.getName() + ": " + s1 + " (Default: " + s2 + ")");
} else {
}
} catch (NoSuchFieldException ex) {
} catch (IllegalAccessException ex) {
}
}
if (!changed) {
append("No changes from default.");
}
}
private void appendEventHandlers() {
report.append(AntiCheat.getManager().getEventChainReport());
}
private void writeReport() throws IOException {
File f = new File(AntiCheat.getPlugin().getDataFolder() + "/report.txt");
FileWriter r = new FileWriter(f);
BufferedWriter writer = new BufferedWriter(r);
writer.write(report.toString());
writer.close();
}
private void postReport() {
try {
URL urls = new URL("http://pastebin.com/api/api_post.php");
HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("POST");
conn.addRequestProperty("Content-type", "application/x-www-form-urlencoded");
conn.setInstanceFollowRedirects(false);
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
out.write(("api_option=paste" + "&api_dev_key=" + URLEncoder.encode("c0616def494dcb5b7632304f8c52c0f1", "utf-8") + "&api_paste_code=" + URLEncoder.encode(report.toString(), "utf-8") + "&api_paste_private=" + URLEncoder.encode("1", "utf-8") + "&api_paste_name=" + URLEncoder.encode("", "utf-8") + "&api_paste_expire_date=" + URLEncoder.encode("1M", "utf-8") + "&api_paste_format=" + URLEncoder.encode("text", "utf-8") + "&api_user_key=" + URLEncoder.encode("", "utf-8")).getBytes());
out.flush();
out.close();
if (conn.getResponseCode() == 200) {
InputStream receive = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(receive));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
response.append("\r\n");
}
reader.close();
String result = response.toString().trim();
if (!result.contains("http://")) {
url = "Failed to post. Check report.txt";
} else {
url = result.trim();
}
} else {
url = "Failed to post. Check report.txt";
}
} catch (Exception e) {
url = "Failed to post. Check report.txt";
}
}
private void append(String s) {
report.append(s + '\n');
}
}
@@ -0,0 +1,90 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import org.bukkit.command.CommandSender;
public enum Permission {
/* Check Nodes */
CHECK_ZOMBE_FLY,
CHECK_ZOMBE_NOCLIP,
CHECK_ZOMBE_CHEAT,
CHECK_FLY,
CHECK_WATERWALK,
CHECK_NOSWING,
CHECK_FASTBREAK,
CHECK_FASTPLACE,
CHECK_SPAM,
CHECK_SPRINT,
CHECK_SNEAK,
CHECK_SPEED,
CHECK_VCLIP,
CHECK_SPIDER,
CHECK_NOFALL,
CHECK_FASTBOW,
CHECK_FASTEAT,
CHECK_FASTHEAL,
CHECK_FORCEFIELD,
CHECK_XRAY,
CHECK_LONGREACH,
CHECK_FASTPROJECTILE,
CHECK_ITEMSPAM,
CHECK_VISUAL,
CHECK_FASTINVENTORY,
CHECK_FASTANIMATION,
CHECK_AUTOTOOL,
/* System Nodes */
SYSTEM_LOG,
SYSTEM_XRAY,
SYSTEM_RESET,
SYSTEM_SPY,
SYSTEM_HELP,
SYSTEM_UPDATE,
SYSTEM_REPORT,
SYSTEM_ALERT,
SYSTEM_CALIBRATE,
SYSTEM_DEBUG,
SYSTEM_RELOAD;
private static final String PERMISSION_ALL = "anticheat.*";
public boolean get(CommandSender cs) {
return cs.hasPermission(toString()) || cs.hasPermission(getBase()) || cs.hasPermission(PERMISSION_ALL);
}
public String getBase() {
return "anticheat." + this.name().toLowerCase().split("_")[0] + ".*";
}
public String whichPermission(CommandSender cs) {
for (String s : new String[]{toString(), getBase(), PERMISSION_ALL}) {
if (cs.hasPermission(s)) {
return s;
}
}
return null;
}
@Override
public String toString() {
return "anticheat." + this.name().toLowerCase().replace("_", ".");
}
}
@@ -0,0 +1,45 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import org.bukkit.Location;
public class SpyState {
private boolean allowFlight;
private boolean flying;
private Location location;
public SpyState(boolean allowFlight, boolean flying, Location location) {
this.allowFlight = allowFlight;
this.flying = flying;
this.location = location;
}
public boolean getAllowFlight() {
return this.allowFlight;
}
public boolean getFlying() {
return this.flying;
}
public Location getLocation() {
return this.location;
}
}
@@ -0,0 +1,48 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import org.bukkit.Material;
public enum ToolHardness {
// NOTHING(null, 1.5)
WOOD(0.75D),
STONE(0.40D),
IRON(0.25D),
DIAMOND(0.20D),
SHEARS(0.55D),
GOLD(0.15D);
double hardness;
ToolHardness(double hard) {
hardness = hard;
}
public static double getToolHardness(Material tool) {
for (ToolHardness e : ToolHardness.values()) {
if (tool.name().contains(e.name())) {
return e.hardness;
}
}
return 1.50D;
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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<Material> INSTANT_BREAK = new ArrayList<Material>();
private static final List<Material> FOOD = new ArrayList<Material>();
private static final List<Material> INTERACTABLE = new ArrayList<Material>();
private static final Map<Material, Material> COMBO = new HashMap<Material, Material>();
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<String> 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<String> stringToList(String string) {
ArrayList<String> i = new ArrayList<String>();
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<String> 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<lifeMatch.length;i++) {
Matcher matcher = Pattern.compile("([0-9]*)" + lifeMatch[i]).matcher(string);
while (matcher.find()) {
seconds += Integer.parseInt(matcher.group(1)) * lifeInterval[i];
}
}
return seconds;
}
static {
// START INSTANT BREAK MATERIALS
INSTANT_BREAK.add(Material.RED_MUSHROOM);
INSTANT_BREAK.add(Material.RED_ROSE);
INSTANT_BREAK.add(Material.BROWN_MUSHROOM);
INSTANT_BREAK.add(Material.YELLOW_FLOWER);
INSTANT_BREAK.add(Material.REDSTONE);
INSTANT_BREAK.add(Material.REDSTONE_TORCH_OFF);
INSTANT_BREAK.add(Material.REDSTONE_TORCH_ON);
INSTANT_BREAK.add(Material.REDSTONE_WIRE);
INSTANT_BREAK.add(Material.LONG_GRASS);
INSTANT_BREAK.add(Material.PAINTING);
INSTANT_BREAK.add(Material.WHEAT);
INSTANT_BREAK.add(Material.SUGAR_CANE);
INSTANT_BREAK.add(Material.SUGAR_CANE_BLOCK);
INSTANT_BREAK.add(Material.DIODE);
INSTANT_BREAK.add(Material.DIODE_BLOCK_OFF);
INSTANT_BREAK.add(Material.DIODE_BLOCK_ON);
INSTANT_BREAK.add(Material.SAPLING);
INSTANT_BREAK.add(Material.TORCH);
INSTANT_BREAK.add(Material.CROPS);
INSTANT_BREAK.add(Material.SNOW);
INSTANT_BREAK.add(Material.TNT);
INSTANT_BREAK.add(Material.POTATO);
INSTANT_BREAK.add(Material.CARROT);
// END INSTANT BREAK MATERIALS
// START INTERACTABLE MATERIALS
INTERACTABLE.add(Material.STONE_BUTTON);
INTERACTABLE.add(Material.LEVER);
INTERACTABLE.add(Material.CHEST);
// END INTERACTABLE MATERIALS
// START FOOD
FOOD.add(Material.COOKED_BEEF);
FOOD.add(Material.COOKED_CHICKEN);
FOOD.add(Material.COOKED_FISH);
FOOD.add(Material.GRILLED_PORK);
FOOD.add(Material.PORK);
FOOD.add(Material.MUSHROOM_SOUP);
FOOD.add(Material.RAW_BEEF);
FOOD.add(Material.RAW_CHICKEN);
FOOD.add(Material.RAW_FISH);
FOOD.add(Material.APPLE);
FOOD.add(Material.GOLDEN_APPLE);
FOOD.add(Material.MELON);
FOOD.add(Material.COOKIE);
FOOD.add(Material.BREAD);
FOOD.add(Material.SPIDER_EYE);
FOOD.add(Material.ROTTEN_FLESH);
FOOD.add(Material.POTATO_ITEM);
// END FOOD
// START COMBOS
COMBO.put(Material.SHEARS, Material.WOOL);
COMBO.put(Material.IRON_SWORD, Material.WEB);
COMBO.put(Material.DIAMOND_SWORD, Material.WEB);
COMBO.put(Material.STONE_SWORD, Material.WEB);
COMBO.put(Material.WOOD_SWORD, Material.WEB);
// END COMBOS
}
}
@@ -0,0 +1,207 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util.enterprise;
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;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Database {
private static final String EVENTS_TABLE = "logs";
private String sqlLogEvent;
private String sqlCleanEvents;
private String sqlCreateEvents;
public enum DatabaseType {
MySQL,
}
private DatabaseType type;
private String hostname;
private int port;
private String username;
private String password;
private String prefix;
private String schema;
private String serverName;
private long logInterval;
private long logLife;
private Connection connection;
private PreparedStatement eventBatch;
private BukkitTask eventTask;
public Database(DatabaseType type, String hostname, int port, String username, String password, String prefix, String schema, String serverName, String logInterval, String logLife) {
this.type = type;
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
this.prefix = prefix;
this.schema = schema;
this.serverName = serverName;
this.logInterval = Utilities.lifeToSeconds(logInterval);
this.logLife = Utilities.lifeToSeconds(logLife);
sqlLogEvent = "INSERT INTO " + prefix + EVENTS_TABLE +
" (server, user, check_type) " +
"VALUES (?, ?, ?)";
sqlCleanEvents = "DELETE FROM " + prefix + EVENTS_TABLE + " " +
"WHERE time < (CURRENT_TIMESTAMP - INTERVAL ? SECOND)";
sqlCreateEvents = "CREATE TABLE IF NOT EXISTS " + prefix + EVENTS_TABLE + "(" +
" `id` INT NOT NULL AUTO_INCREMENT," +
" `server` VARCHAR(45) NOT NULL," +
" `time` TIMESTAMP NOT NULL DEFAULT NOW()," +
" `user` VARCHAR(45) NOT NULL," +
" `check_type` VARCHAR(45) NOT NULL," +
" PRIMARY KEY (`id`));";
}
public DatabaseType getType() {
return type;
}
public String getHostname() {
return hostname;
}
public int getPort() {
return port;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getPrefix() {
return prefix;
}
public String getSchema() {
return schema;
}
public void connect() {
String url = "jdbc:" + type.toString().toLowerCase() + "://" + hostname + ":" + port + "/" + schema;
try {
connection = DriverManager.getConnection(url, username, password);
eventBatch = connection.prepareStatement(sqlLogEvent);
connection.prepareStatement(sqlCreateEvents).executeUpdate();
connection.setAutoCommit(false);
if (logInterval != 0) {
eventTask = Bukkit.getScheduler().runTaskTimerAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
flushEvents();
}
}, logInterval * 20, logInterval * 20);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void shutdown() {
eventTask.cancel();
flushEvents();
try {
eventBatch.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getConnection() {
return connection;
}
public void logEvent(User user, CheckType checkType) {
try {
eventBatch.setString(1, serverName);
eventBatch.setString(2, user.getName());
eventBatch.setString(3, checkType.toString());
eventBatch.addBatch();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void flushEvents() {
try {
eventBatch.executeBatch();
connection.commit();
eventBatch = connection.prepareStatement(sqlLogEvent);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void cleanEvents() {
if (logLife != 0) {
Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
try {
PreparedStatement statement = connection.prepareStatement(sqlCleanEvents);
statement.setLong(1, logLife);
statement.executeUpdate();
connection.commit();
AntiCheat.getPlugin().verboseLog("Cleaned " + statement.getUpdateCount() + " old events from the database");
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
}
}
@@ -0,0 +1,94 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util.rule;
import net.gravitydevelopment.anticheat.manage.CheckType;
import net.gravitydevelopment.anticheat.manage.User;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.SortedMap;
/**
* The conditional rule follows the same syntax as the traditional CS conditional operator.<br />
* (CONDITION) ? (TRUE RESULT) : (FALSE RESULT)<br />
* Where CONDITION is a statement that will be evaluated as either <b>TRUE</b> or <b>FALSE</b>
* and the results are actions to be taken for either outcome.
* <br /><br />
* <p/>
* Should you need additional actions, the system will recursively parse the following values and handle appropriately.
* <br />
* For instance, (CONDITION) ? (TRUE RESULT) : (CONDITION) ? (TRUE RESULT) : (FALSE RESULT) is a valid rule
* <br /><br />
* <p/>
* An example of a valid Conditional Rule:<br />
* Check_SPIDER > 0 ? Player.KICK : null<br />
* <i>The above statement would read 'If the spider check has been failed over zero times, kick the player. Otherwise, do nothing.'</i>
* <p/>
* To see syntax for variables and functions that you may use, see {@link net.gravitydevelopment.anticheat.util.rule.Rule}
*/
public class ConditionalRule extends Rule {
private static ScriptEngineManager factory = new ScriptEngineManager();
private static ScriptEngine engine = factory.getEngineByName("js");
private static final String TRUE_DELIMITER = "\\?";
private static final String FALSE_DELIMITER = ":";
private static final Type TYPE = Type.CONDITIONAL;
public ConditionalRule(String string) {
super(string, TYPE);
}
@Override
public boolean check(User user, CheckType type) {
try {
// Load all variables
SortedMap<String, Object> map = getVariables(user, type);
for (String key : map.keySet()) {
engine.put(key, map.get(key));
}
boolean value = (Boolean) engine.eval(getString().split(TRUE_DELIMITER)[0]);
// Yo dawg I heard you like conditionals...
String next = value ? getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[0] : getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[1];
execute(next, user, type);
return value;
} catch (ScriptException e) {
e.printStackTrace();
}
return true;
}
private void execute(String string, User user, CheckType type) {
// If we're told to do nothing
if (string.equalsIgnoreCase("null") || string.equalsIgnoreCase("none")) return;
// If this string is a new conditional statement
if (TYPE.matches(string)) {
new ConditionalRule(string).check(user, type);
} else if (isVariableSet(string)) {
setVariable(string.split("=")[0], string.split("=")[1], user);
} else if (isFunction(string)) {
doFunction(string, type, user);
}
}
}
@@ -0,0 +1,177 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util.rule;
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;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* A rule is a scriptable function used to customize the functions of AntiCheat<br />
* Rules are executed whenever a user's level rises.<br /><br />
* <p/>
* There are various variables you can use to interact with AntiCheat through your rules<br />
* Variables are denoted with the type followed by a _ followed by the variable name.<br />
* For instance, a variable coming from a user who has used FLY 5 times and is checked by a rule containing 'Check_FLY' will produce a value of 5.
* <br /><br />
* <p/>
* <b>Types of variables:</b><br />
* - 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<br />
* - Player: Contains LEVEL, the player's current level and CHECK, the check that was just failed
* <br /><br />
* <p/>
* There are also functions you can use to execute an action within AntiCheat<br />
* Functions are denoted with the type followed by a period followed by the function name.<br />
* For instance, a rule containing Player.KICK will result in the user being kicked.<br />
* <br /><br />
* <p/>
* <b>Types of functions:</b><br />
* - Player: RESET, KICK, BAN, COMMAND[command] OR COMMAND[command1;command2]
* <i>- when using commands <b>&player</b> will be replaced by the player name, <b>&world</b> will be replaced by the player's world,
* and <b>&check</b> will be replaced by the check that caused this rule to be run</i><br />
* <br /><br />
* <p/>
* The Rule class itself is not an functional rule setup,
* it is inherited and made functional by different implementations of the rule parser.<br />
* The only current Rule implementation is the {@link net.gravitydevelopment.anticheat.util.rule.ConditionalRule}
*/
public class Rule {
private static String string;
private static final String VARIABLE_SET_REGEX = ".*(_).*=.*";
private static final String FUNCTION_REGEX = ".*\\..*";
private Type type;
public enum Type {
CONDITIONAL(".*[?]*.*:.*", "net.gravitydevelopment.anticheat.util.rule.ConditionalRule");
private String regex;
private String c;
private Type(String regex, String c) {
this.regex = regex;
this.c = c;
}
public boolean matches(String s) {
return s.matches(regex);
}
public String getInstance() {
return c;
}
}
public Rule(String string, Type type) {
this.string = Utilities.removeWhitespace(string).toLowerCase();
this.type = type;
}
/**
* Check if the rule passed or failed
*
* @param user the user to check
* @return true if the rule has passed, false if failed
*/
public boolean check(User user, CheckType type) {
// Default value
return true;
}
/**
* Load a rule by its string value
*
* @param string the string value to load
* @return an instance of Rule if an implementation exists to handle this rule, null if none are found
*/
public static Rule load(String string) {
for (Type type : Type.values()) {
if (type.matches(string)) {
try {
Class c = Class.forName(type.getInstance());
Constructor con = c.getConstructor(String.class);
return (Rule) con.newInstance(string);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
/**
* Get the type of rule this is
*
* @return a {@link net.gravitydevelopment.anticheat.util.rule.Rule.Type}
*/
public Type getType() {
return type;
}
protected String getString() {
return string;
}
protected SortedMap<String, Object> getVariables(User user, CheckType type) {
SortedMap<String, Object> map = new TreeMap<String, Object>();
map.put("player_check", type.name().toLowerCase());
map.put("player_level", user.getLevel());
for (CheckType t : CheckType.values()) {
map.put("check_" + t.name().toLowerCase(), t.getUses(user.getName()));
}
return map;
}
protected void setVariable(String variable, String value, User user) {
// Only variable that can be set for now, may change in the future
// others wouldn't make any sense to set
if (variable.equals("player_level") && Utilities.isInt(value)) {
user.setLevel(Integer.parseInt(value));
}
}
protected void doFunction(String text, CheckType type, User user) {
if (text.toLowerCase().startsWith("player")) {
text = text.split("\\.")[1];
List<String> action = new ArrayList<String>();
action.add(text);
AntiCheat.getManager().getUserManager().execute(user, action, type);
}
}
protected boolean isFunction(String string) {
return string.matches(FUNCTION_REGEX);
}
protected boolean isVariableSet(String string) {
return string.matches(VARIABLE_SET_REGEX);
}
@Override
public String toString() {
return type + "{" + string + "}";
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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);
}
}
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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<String, Integer> diamond, Map<String, Integer> gold, Map<String, Integer> iron, Map<String, Integer> lapis, Map<String, Integer> redstone, Map<String, Integer> other, Map<String, Integer> 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;
}
}
@@ -0,0 +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 <http://www.gnu.org/licenses/>.
*/
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<String, Integer> diamond = new HashMap<String, Integer>();
private Map<String, Integer> gold = new HashMap<String, Integer>();
private Map<String, Integer> iron = new HashMap<String, Integer>();
private Map<String, Integer> lapis = new HashMap<String, Integer>();
private Map<String, Integer> redstone = new HashMap<String, Integer>();
private Map<String, Integer> block = new HashMap<String, Integer>();
private Map<String, Integer> totalblock = new HashMap<String, Integer>();
private List<String> alerted = new ArrayList<String>();
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<String, Integer> 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);
}
}