diff --git a/src/main/java/net/h31ix/anticheat/AntiCheat.java b/src/main/java/net/h31ix/anticheat/AntiCheat.java index 3169559..158a8fd 100644 --- a/src/main/java/net/h31ix/anticheat/AntiCheat.java +++ b/src/main/java/net/h31ix/anticheat/AntiCheat.java @@ -66,6 +66,8 @@ public class AntiCheat extends JavaPlugin { setupCommands(); setupUpdater(); setupProtocol(); + // Enterprise must come before levels + setupEnterprise(); restoreLevels(); // Check if NoCheatPlus is installed Bukkit.getScheduler().runTaskLater(this, new Runnable() { @@ -78,15 +80,15 @@ public class AntiCheat extends JavaPlugin { } }, 40L); // End tests - if (verbose) { - getLogger().log(Level.INFO, "Finished loading."); - } + verboseLog("Finished loading."); } @Override public void onDisable() { - for (User user : manager.getUserManager().getUsers()) { - config.getLevels().saveLevel(user.getName(), user.getLevel()); + if (!config.shouldSyncUsers()) { + for (User user : manager.getUserManager().getUsers()) { + config.getLevels().saveLevel(user.getName(), user.getLevel()); + } } AnticheatManager.close(); @@ -98,9 +100,7 @@ public class AntiCheat extends JavaPlugin { if (Bukkit.getPluginManager().getPlugin("ProtocolLib") != null) { protocolLib = true; packetManager = new PacketManager(ProtocolLibrary.getProtocolManager(), this, manager); - if (verbose) { - getLogger().log(Level.INFO, "Hooked into ProtocolLib"); - } + verboseLog("Hooked into ProtocolLib"); } } @@ -125,9 +125,7 @@ public class AntiCheat extends JavaPlugin { } }, XRAY_TIME, XRAY_TIME); - if (verbose) { - getLogger().log(Level.INFO, "Scheduled the XRay checker."); - } + verboseLog("Scheduled the XRay checker."); } } } @@ -135,45 +133,37 @@ public class AntiCheat extends JavaPlugin { private void setupEvents() { for (Listener listener : eventList) { getServer().getPluginManager().registerEvents(listener, this); - if (verbose) { - getLogger().log(Level.INFO, "Registered events for ".concat(listener.toString().split("@")[0].split(".anticheat.")[1])); - } + verboseLog("Registered events for ".concat(listener.toString().split("@")[0].split(".anticheat.")[1])); } } private void setupCommands() { getCommand("anticheat").setExecutor(new CommandHandler()); - if (verbose) { - getLogger().log(Level.INFO, "Registered commands."); - } + verboseLog("Registered commands."); } private void setupUpdater() { if (config.getConfig().autoUpdate.getValue()) { - if (verbose) { - getLogger().log(Level.INFO, "Checking for a new update..."); - } + verboseLog("Checking for a new update..."); Updater updater = new Updater(this, "anticheat", this.getFile(), Updater.UpdateType.DEFAULT, false); update = updater.getResult() != Updater.UpdateResult.NO_UPDATE; - if (verbose) { - getLogger().log(Level.INFO, "Update available: " + update); - } + verboseLog("Update available: " + update); } } private void setupConfig() { config = manager.getConfiguration(); verbose = config.getConfig().verboseStartup.getValue(); - if (verbose) { - getLogger().log(Level.INFO, "Setup the config."); - } + verboseLog("Setup the config."); } private void setupEnterprise() { if(config.getConfig().enterprise.getValue()) { config.getEnterprise().database.connect(); - if (verbose) { - getLogger().log(Level.INFO, "Connected to the database."); + verboseLog("Connected to the database."); + + if(config.getEnterprise().loggingEnabled.getValue()) { + config.getEnterprise().database.cleanEvents(); } } } @@ -181,16 +171,15 @@ public class AntiCheat extends JavaPlugin { private void restoreLevels() { for (Player player : getServer().getOnlinePlayers()) { String name = player.getName(); - if(!config.getConfig().enterprise.getValue()) { + if (!config.shouldSyncUsers()) { manager.getUserManager().addUser(new User(player.getName(), config.getLevels().getLevel(name))); } else { User user = new User(player.getName()); + user.setIsWaitingOnLevelSync(true); config.getEnterprise().database.syncFrom(user); manager.getUserManager().addUser(user); } - if (verbose) { - getLogger().log(Level.INFO, "Data for " + player.getName() + " re-applied from flatfile"); - } + verboseLog("Data for " + player.getName() + " loaded"); } } @@ -237,4 +226,8 @@ public class AntiCheat extends JavaPlugin { } }); } + + public void verboseLog(final String string) { + getLogger().info(string); + } } diff --git a/src/main/java/net/h31ix/anticheat/CommandHandler.java b/src/main/java/net/h31ix/anticheat/CommandHandler.java index 191c2a4..4789393 100644 --- a/src/main/java/net/h31ix/anticheat/CommandHandler.java +++ b/src/main/java/net/h31ix/anticheat/CommandHandler.java @@ -352,18 +352,21 @@ public class CommandHandler implements CommandExecutor { public void sendPlayerReport(CommandSender cs, List types, User user, int page) { String name = user.getName(); int pages = (int) Math.ceil(((float) types.size()) / 6); - String levelString = ChatColor.GREEN+"Low"; - for(Level level : CONFIG.getEvents().levels) { - if(level.getValue() == user.getLevel()) { - levelString = level.getColor()+level.getName(); - } + + Level level = CONFIG.getEvents().getUserLevel(user.getLevel()); + 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) * 1)); + int index = ((page - 1) * 5) + (x + ((page - 1))); if (index < types.size()) { int use = types.get(index).getUses(name); ChatColor color = WHITE; @@ -391,7 +394,7 @@ public class CommandHandler implements CommandExecutor { public void handleReload(CommandSender cs) { if (hasPermission(cs, Permission.SYSTEM_RELOAD)) { - CONFIG.reload(); + CONFIG.load(); cs.sendMessage(GREEN + "AntiCheat configuration reloaded."); } } diff --git a/src/main/java/net/h31ix/anticheat/config/Configuration.java b/src/main/java/net/h31ix/anticheat/config/Configuration.java index a3330f8..7b47d63 100644 --- a/src/main/java/net/h31ix/anticheat/config/Configuration.java +++ b/src/main/java/net/h31ix/anticheat/config/Configuration.java @@ -47,7 +47,9 @@ public class Configuration { magic = new Magic(plugin, this); - load(); + for(ConfigurationFile file : new ConfigurationFile[]{config, events, lang, enterprise, levels, magic}) { + checkReload(file); + } } public void load() { @@ -73,11 +75,6 @@ public class Configuration { } } - public void reload() { - save(); - load(); - } - public Config getConfig() { return config; } @@ -101,4 +98,12 @@ public class Configuration { public Magic getMagic() { return magic; } + + public boolean shouldSyncEvents() { + return getConfig().enterprise.getValue() && getEnterprise().loggingEnabled.getValue(); + } + + public boolean shouldSyncUsers() { + return getConfig().enterprise.getValue() && getEnterprise().usersEnabled.getValue(); + } } diff --git a/src/main/java/net/h31ix/anticheat/config/ConfigurationFile.java b/src/main/java/net/h31ix/anticheat/config/ConfigurationFile.java index 0d50348..f72e234 100644 --- a/src/main/java/net/h31ix/anticheat/config/ConfigurationFile.java +++ b/src/main/java/net/h31ix/anticheat/config/ConfigurationFile.java @@ -149,6 +149,8 @@ public class ConfigurationFile { } else if(loadDefault) { getConfigFile().set(path, getDefaultConfigFile().get(path)); value = getDefaultConfigFile().get(path); + getConfigFile().set(path, value); + save(); } } @@ -162,6 +164,7 @@ public class ConfigurationFile { public T setValue(T value) { getConfigFile().set(path, value); + save(); return value; } diff --git a/src/main/java/net/h31ix/anticheat/config/files/Enterprise.java b/src/main/java/net/h31ix/anticheat/config/files/Enterprise.java index f528357..abffbe7 100644 --- a/src/main/java/net/h31ix/anticheat/config/files/Enterprise.java +++ b/src/main/java/net/h31ix/anticheat/config/files/Enterprise.java @@ -72,14 +72,10 @@ public class Enterprise extends ConfigurationFile { databasePassword.getValue(), databasePrefix.getValue(), databaseSchema.getValue(), + serverName.getValue(), loggingInterval.getValue(), - usersInterval.getValue() + usersInterval.getValue(), + loggingLife.getValue() ); } - - public void logEvent(User user, CheckType type) { - if(loggingEnabled.getValue()) { - database.logEvent(serverName.getValue(), user, type); - } - } } diff --git a/src/main/java/net/h31ix/anticheat/config/files/Events.java b/src/main/java/net/h31ix/anticheat/config/files/Events.java index 5b27148..a558562 100644 --- a/src/main/java/net/h31ix/anticheat/config/files/Events.java +++ b/src/main/java/net/h31ix/anticheat/config/files/Events.java @@ -25,6 +25,8 @@ import net.h31ix.anticheat.util.Level; import net.h31ix.anticheat.util.rule.Rule; import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.List; public class Events extends ConfigurationFile { @@ -50,7 +52,7 @@ public class Events extends ConfigurationFile { this.levels = new ArrayList(); for(String string : levels.getValue()) { Level level = Level.load(string); - if(level == null) { + if(level == null || level.getValue() < 0) { continue; } @@ -94,5 +96,26 @@ public class Events extends ConfigurationFile { AntiCheat.getPlugin().getLogger().warning("Couldn't load rule '"+string+"' from config. Improper format used."); } } + + // Sort levels + Collections.sort(this.levels, new Comparator() { + public int compare(Level l1, Level l2) { + if (l1.getValue() == l2.getValue()) { + return 0; + } else if (l1.getValue() < l2.getValue()) { + return -1; + } + return 1; + } + }); + } + + public Level getUserLevel(int value) { + for(int i=0;i= levels.get(i).getValue() && value < levels.get(i+1).getValue()) return levels.get(i); + } + return null; } } diff --git a/src/main/java/net/h31ix/anticheat/event/EventListener.java b/src/main/java/net/h31ix/anticheat/event/EventListener.java index 3c0915e..3fe5947 100644 --- a/src/main/java/net/h31ix/anticheat/event/EventListener.java +++ b/src/main/java/net/h31ix/anticheat/event/EventListener.java @@ -53,7 +53,9 @@ public class EventListener implements Listener { // Ignore plugins that are creating NPCs with no names (why the hell) if (user != null && user.getName() != null) { type.logUse(user); - CONFIG.getEnterprise().logEvent(user, type); + if (CONFIG.shouldSyncEvents()) { + 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."); } diff --git a/src/main/java/net/h31ix/anticheat/event/PlayerListener.java b/src/main/java/net/h31ix/anticheat/event/PlayerListener.java index d88f2ff..aa04262 100644 --- a/src/main/java/net/h31ix/anticheat/event/PlayerListener.java +++ b/src/main/java/net/h31ix/anticheat/event/PlayerListener.java @@ -138,6 +138,8 @@ public class PlayerListener extends EventListener { @EventHandler(ignoreCancelled = true) public void onPlayerChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); + log("asdf", player, CheckType.SPRINT); + getUserManager().getUser(player.getName()).increaseLevel(CheckType.SPRINT); if (getCheckManager().willCheck(player, CheckType.SPAM) && getConfig().getConfig().blockChatSpam.getValue()) { CheckResult result = getBackend().checkSpam(player, event.getMessage()); if (result.failed()) { @@ -166,6 +168,9 @@ public class PlayerListener extends EventListener { getBackend().garbageClean(event.getPlayer()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); + if (getConfig().shouldSyncUsers()) { + getConfig().getEnterprise().database.syncTo(getUserManager().getUser(event.getPlayer().getName())); + } } @EventHandler @@ -261,7 +266,7 @@ public class PlayerListener extends EventListener { getBackend().logJoin(player); - if (getConfig().getConfig().enterprise.getValue()) { + if (!getConfig().shouldSyncUsers()) { if (getUserManager().getUser(player.getName()) == null) { getUserManager().addUser(new User(player.getName())); } else { @@ -269,6 +274,7 @@ public class PlayerListener extends EventListener { } } else { User user = new User(player.getName()); + user.setIsWaitingOnLevelSync(true); getConfig().getEnterprise().database.syncFrom(user); getUserManager().addUser(user); } diff --git a/src/main/java/net/h31ix/anticheat/manage/AnticheatManager.java b/src/main/java/net/h31ix/anticheat/manage/AnticheatManager.java index 788c67a..2461a02 100644 --- a/src/main/java/net/h31ix/anticheat/manage/AnticheatManager.java +++ b/src/main/java/net/h31ix/anticheat/manage/AnticheatManager.java @@ -176,8 +176,6 @@ public class AnticheatManager { public static void close() { fileHandler.close(); - configuration.save(); - if(configuration.getConfig().enterprise.getValue()) { configuration.getEnterprise().database.shutdown(); } diff --git a/src/main/java/net/h31ix/anticheat/manage/User.java b/src/main/java/net/h31ix/anticheat/manage/User.java index f0dbef3..1c9d623 100644 --- a/src/main/java/net/h31ix/anticheat/manage/User.java +++ b/src/main/java/net/h31ix/anticheat/manage/User.java @@ -42,6 +42,8 @@ public class User { private String [] messages = new String[2]; private Long [] messageTimes = new Long[2]; + private boolean isWaitingOnLevelSync; + /** * Initialize an AntiCheat user * @@ -60,7 +62,8 @@ public class User { public User(String name, int level) { this.name = name; this.level = level; - this.id = getPlayer().getEntityId(); + + this.id = getPlayer().isOnline() ? getPlayer().getEntityId() : -1; } /** @@ -111,23 +114,26 @@ public class User { // Prevent silent mode from increasing the level way too fast return false; } else { - level++; + if (level < config.getEvents().highestLevel) { + level++; - // Check levels - for(Level l : getLevels()) { - if(l.getValue() == level) { - AntiCheat.getManager().getUserManager().alert(this, l, type); - if(l.getValue() == config.getEvents().highestLevel) { - level = l.getValue() - 10; + // Check levels + for(Level l : getLevels()) { + if(l.getValue() == level) { + AntiCheat.getManager().getUserManager().alert(this, l, type); + if(l.getValue() == config.getEvents().highestLevel) { + level = l.getValue() - 10; + } } } - } - // Execute rules - for(Rule rule : config.getEvents().rules) { - rule.check(this, type); + // Execute rules + for(Rule rule : config.getEvents().rules) { + rule.check(this, type); + } + return true; } - return true; + return false; } } else { return false; @@ -147,9 +153,15 @@ public class User { * @return true if the level was valid and set properly */ public boolean setLevel(int level) { - if (level > 0 && level <= config.getEvents().highestLevel) { - this.level = level; - return true; + isWaitingOnLevelSync = false; + if (level >= 0) { + if (level <= config.getEvents().highestLevel) { + this.level = level; + return true; + } else { + this.level = config.getEvents().highestLevel; + return false; + } } else { return false; } @@ -310,4 +322,12 @@ public class User { private boolean silentMode() { return config.getConfig().silentMode.getValue(); } + + public void setIsWaitingOnLevelSync(boolean b) { + this.isWaitingOnLevelSync = b; + } + + public boolean isWaitingOnLevelSync() { + return isWaitingOnLevelSync; + } } diff --git a/src/main/java/net/h31ix/anticheat/util/enterprise/Database.java b/src/main/java/net/h31ix/anticheat/util/enterprise/Database.java index 13dd878..7be8fdf 100644 --- a/src/main/java/net/h31ix/anticheat/util/enterprise/Database.java +++ b/src/main/java/net/h31ix/anticheat/util/enterprise/Database.java @@ -31,9 +31,10 @@ public class Database { private static final String EVENTS_TABLE = "events"; private static final String USERS_TABLE = "users"; - private static final String SQL_LOG_EVENT = "INSERT INTO ? (server_name, user, check_type) VALUES (?, ?, ?)"; - private static final String SQL_SYNC_FROM = "SELECT level FROM ? WHERE user = ?"; - private static final String SQL_SYNC_TO = "INSERT INTO ? (user, level) VALUES (?, ?) ON DUPLICATE KEY UPDATE level = ?"; + private String sqlLogEvent; + private String sqlSyncTo; + private String sqlSyncFrom; + private String sqlCleanEvents; public enum DatabaseType { MySQL, @@ -46,10 +47,13 @@ public class Database { private String password; private String prefix; private String schema; + private String serverName; private int eventInterval; private int userInterval; + private int eventLife; + private Connection connection; private PreparedStatement eventBatch; @@ -58,7 +62,7 @@ public class Database { private BukkitTask eventTask; private BukkitTask userTask; - public Database(DatabaseType type, String hostname, int port, String username, String password, String prefix, String schema, int eventInterval, int userInterval) { + public Database(DatabaseType type, String hostname, int port, String username, String password, String prefix, String schema, String serverName, int eventInterval, int userInterval, int eventLife) { this.type = type; this.hostname = hostname; this.port = port; @@ -66,9 +70,17 @@ public class Database { this.password = password; this.prefix = prefix; this.schema = schema; + this.serverName = serverName; this.eventInterval = eventInterval; this.userInterval = userInterval; + + this.eventLife = eventLife; + + sqlLogEvent = "INSERT INTO " + prefix + EVENTS_TABLE + " (server, user, check_type) VALUES (?, ?, ?)"; + sqlSyncTo = "INSERT INTO " + prefix + USERS_TABLE + " (user, level) VALUES (?, ?) ON DUPLICATE KEY UPDATE level = ?, last_update=CURRENT_TIMESTAMP, last_update_server=?"; + sqlSyncFrom = "SELECT level FROM " + prefix + USERS_TABLE + " WHERE user = ?"; + sqlCleanEvents = "DELETE FROM " + prefix + EVENTS_TABLE + " WHERE time < (CURRENT_TIMESTAMP - INTERVAL ? DAY)"; } public DatabaseType getType() { @@ -100,12 +112,12 @@ public class Database { } public void connect() { - String url = type.toString().toLowerCase() + "://" + hostname + ":" + port + "/" + schema; + String url = "jdbc:" + type.toString().toLowerCase() + "://" + hostname + ":" + port + "/" + schema; try { connection = DriverManager.getConnection(url, username, password); - eventBatch = connection.prepareStatement(SQL_LOG_EVENT); - syncBatch = connection.prepareStatement(SQL_SYNC_TO); + eventBatch = connection.prepareStatement(sqlLogEvent); + syncBatch = connection.prepareStatement(sqlSyncTo); connection.setAutoCommit(false); @@ -114,7 +126,7 @@ public class Database { public void run() { flushEvents(); } - }, eventInterval*60*20, eventInterval*60*20); + }, eventInterval* 60 * 20, eventInterval * 60 * 20); userTask = Bukkit.getScheduler().runTaskTimerAsynchronously(AntiCheat.getPlugin(), new Runnable() { @Override @@ -149,12 +161,11 @@ public class Database { return connection; } - public void logEvent(String serverName, User user, CheckType checkType) { + public void logEvent(User user, CheckType checkType) { try { - eventBatch.setString(1, EVENTS_TABLE); - eventBatch.setString(2, serverName); - eventBatch.setString(3, user.getName()); - eventBatch.setString(4, checkType.toString()); + eventBatch.setString(1, serverName); + eventBatch.setString(2, user.getName()); + eventBatch.setString(3, checkType.toString()); eventBatch.addBatch(); } catch (SQLException e) { @@ -163,15 +174,18 @@ public class Database { } public void syncTo(User user) { - try { - syncBatch.setString(1, USERS_TABLE); - syncBatch.setString(2, user.getName()); - syncBatch.setInt(3, user.getLevel()); - syncBatch.setInt(4, user.getLevel()); + if (!user.isWaitingOnLevelSync()) { + System.out.println("Syncing to "+user.getName()+" value "+user.getLevel()); + try { + syncBatch.setString(1, user.getName()); + syncBatch.setInt(2, user.getLevel()); + syncBatch.setInt(3, user.getLevel()); + syncBatch.setString(4, serverName); - syncBatch.addBatch(); - } catch (SQLException e) { - e.printStackTrace(); + syncBatch.addBatch(); + } catch (SQLException e) { + e.printStackTrace(); + } } } @@ -180,12 +194,12 @@ public class Database { @Override public void run() { try { - PreparedStatement statement = connection.prepareStatement(SQL_SYNC_FROM); - statement.setString(1, USERS_TABLE); - statement.setString(2, user.getName()); + PreparedStatement statement = connection.prepareStatement(sqlSyncFrom); + statement.setString(1, user.getName()); ResultSet set = statement.executeQuery(); while (set.next()) { + System.out.println("Added level for " + user.getName()+":" +set.getInt("level")); user.setLevel(set.getInt("level")); } } catch (SQLException e) { @@ -200,20 +214,40 @@ public class Database { eventBatch.executeBatch(); connection.commit(); - eventBatch = connection.prepareStatement(SQL_LOG_EVENT); + eventBatch = connection.prepareStatement(sqlLogEvent); } catch (SQLException e) { e.printStackTrace(); } } public void flushSyncs() { + System.out.println("Flushing syncs"); try { syncBatch.executeBatch(); connection.commit(); - syncBatch = connection.prepareStatement(SQL_SYNC_TO); + syncBatch = connection.prepareStatement(sqlSyncTo); } catch (SQLException e) { e.printStackTrace(); } } + + public void cleanEvents() { + Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable(){ + @Override + public void run() { + try { + PreparedStatement statement = connection.prepareStatement(sqlCleanEvents); + statement.setInt(1, eventLife); + + statement.executeUpdate(); + + connection.commit(); + AntiCheat.getPlugin().verboseLog("Cleaned " + statement.getUpdateCount() + " old events from the database"); + } catch (SQLException e) { + e.printStackTrace(); + } + } + }); + } }