Rewrite configuration system

This commit refactors almost all of the configuration section to make it more friendly for further development. In addition, files being saved without comments has been fixed.

 Emphasis has been put on retaining backwards compatibility, so most actual configuration options in flatfile have stayed the same. Minor changes are automatically upgraded.
This commit is contained in:
h31ix committed 2013-09-22 15:56:36 -04:00
1 parent 1e42d58926
commit 77ab0062b8
37 files changed
+1256 -1209

No files matched your search

+1
View File
@@ -36,6 +36,7 @@
<include>lang.yml</include> <include>lang.yml</include>
<include>magic.yml</include> <include>magic.yml</include>
<include>events.yml</include> <include>events.yml</include>
<include>enterprise.yml</include>
</includes> </includes>
</resource> </resource>
</resources> </resources>
@@ -25,22 +25,22 @@ import java.io.OutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.event.*; import net.h31ix.anticheat.event.*;
import net.h31ix.anticheat.manage.AnticheatManager; import net.h31ix.anticheat.manage.AnticheatManager;
import net.h31ix.anticheat.manage.User; import net.h31ix.anticheat.manage.User;
import net.h31ix.anticheat.update.Updater; import net.h31ix.anticheat.update.Updater;
import net.h31ix.anticheat.util.Configuration;
import net.h31ix.anticheat.util.Utilities; import net.h31ix.anticheat.util.Utilities;
import net.h31ix.anticheat.xray.XRayListener; import net.h31ix.anticheat.xray.XRayListener;
import net.h31ix.anticheat.xray.XRayTracker; import net.h31ix.anticheat.xray.XRayTracker;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
public class Anticheat extends JavaPlugin { public class AntiCheat extends JavaPlugin {
private static AnticheatManager manager; private static AnticheatManager manager;
private static List<Listener> eventList = new ArrayList<Listener>(); private static List<Listener> eventList = new ArrayList<Listener>();
@@ -66,16 +66,6 @@ public class Anticheat extends JavaPlugin {
setupCommands(); setupCommands();
setupUpdater(); setupUpdater();
restoreLevels(); restoreLevels();
// Test for compatibility for 1.4.5-R1.0
try {
Material.AIR.isSolid();
} catch (NoSuchMethodError error) {
getLogger().severe("You are using an outdated version of CraftBukkit that does not contain the API required for AntiCheat to run properly.");
getLogger().severe("Please update to CraftBukkit 1.4.5-R1.0 or higher by visiting dl.bukkit.org and hitting the green download button.");
getLogger().severe("AntiCheat will now be disabled, and will not protect your server until it is updated.");
getPluginLoader().disablePlugin(this);
return;
}
// Check if NoCheatPlus is installed // Check if NoCheatPlus is installed
Bukkit.getScheduler().runTaskLater(this, new Runnable() { Bukkit.getScheduler().runTaskLater(this, new Runnable() {
public void run() { public void run() {
@@ -94,43 +84,20 @@ public class Anticheat extends JavaPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
AnticheatManager.close();
for (User user : manager.getUserManager().getUsers()) { for (User user : manager.getUserManager().getUsers()) {
config.saveLevel(user.getName(), user.getLevel()); config.getLevels().saveLevel(user.getName(), user.getLevel());
} }
config.saveLevels();
AnticheatManager.close();
getServer().getScheduler().cancelTasks(this); getServer().getScheduler().cancelTasks(this);
cleanup(); cleanup();
} }
public boolean save(InputStream in, File file) {
if (!file.exists()) {
file.getParentFile().mkdirs();
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
getLogger().severe("Unable to save files. Is the directory writable?");
}
if (verbose) {
getLogger().log(Level.INFO, file.getName() + " created.");
}
return true;
}
return false;
}
private void setupXray() { private void setupXray() {
final XRayTracker xtracker = manager.getXRayTracker(); final XRayTracker xtracker = manager.getXRayTracker();
if (config.logXRay()) { if (config.getConfig().logXRayStats.getValue()) {
eventList.add(new XRayListener()); eventList.add(new XRayListener());
if (config.alertXRay()) { if (config.getConfig().alertWhenXRayIsFound.getValue()) {
getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() { getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() {
@Override @Override
public void run() { public void run() {
@@ -171,7 +138,7 @@ public class Anticheat extends JavaPlugin {
} }
private void setupUpdater() { private void setupUpdater() {
if (config.autoUpdate()) { if (config.getConfig().autoUpdate.getValue()) {
if (verbose) { if (verbose) {
getLogger().log(Level.INFO, "Checking for a new update..."); getLogger().log(Level.INFO, "Checking for a new update...");
} }
@@ -185,9 +152,7 @@ public class Anticheat extends JavaPlugin {
private void setupConfig() { private void setupConfig() {
config = manager.getConfiguration(); config = manager.getConfiguration();
checkConfigs(); verbose = config.getConfig().verboseStartup.getValue();
config.load();
verbose = config.verboseStartup();
if (verbose) { if (verbose) {
getLogger().log(Level.INFO, "Setup the config."); getLogger().log(Level.INFO, "Setup the config.");
} }
@@ -196,23 +161,14 @@ public class Anticheat extends JavaPlugin {
private void restoreLevels() { private void restoreLevels() {
for (Player player : getServer().getOnlinePlayers()) { for (Player player : getServer().getOnlinePlayers()) {
String name = player.getName(); String name = player.getName();
manager.getUserManager().addUser(new User(player.getName(), config.getLevel(name))); manager.getUserManager().addUser(new User(player.getName(), config.getLevels().getLevel(name)));
if (verbose) { if (verbose) {
getLogger().log(Level.INFO, "Data for " + player.getName() + " re-applied from flatfile"); getLogger().log(Level.INFO, "Data for " + player.getName() + " re-applied from flatfile");
} }
} }
} }
public void checkConfigs() { public static AntiCheat getPlugin() {
save(getResource("config.yml"), new File(getDataFolder() + "/config.yml"));
save(getResource("lang.yml"), new File(getDataFolder() + "/lang.yml"));
save(getResource("magic.yml"), new File(getDataFolder() + "/magic.yml"));
if(save(getResource("events.yml"), new File(getDataFolder() + "/events.yml"))) {
config.setUpdateEvents();
}
}
public static Anticheat getPlugin() {
return manager.getPlugin(); return manager.getPlugin();
} }
@@ -251,8 +207,4 @@ public class Anticheat extends JavaPlugin {
} }
}); });
} }
public void replaceMagic() {
saveResource("magic.yml", true);
}
} }
@@ -20,6 +20,8 @@ package net.h31ix.anticheat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.manage.CheckType; import net.h31ix.anticheat.manage.CheckType;
import net.h31ix.anticheat.manage.User; import net.h31ix.anticheat.manage.User;
import net.h31ix.anticheat.manage.UserManager; import net.h31ix.anticheat.manage.UserManager;
@@ -35,9 +37,9 @@ import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.FixedMetadataValue;
public class CommandHandler implements CommandExecutor { public class CommandHandler implements CommandExecutor {
private static final Configuration CONFIG = Anticheat.getManager().getConfiguration(); private static final Configuration CONFIG = AntiCheat.getManager().getConfiguration();
private static final UserManager USER_MANAGER = Anticheat.getManager().getUserManager(); private static final UserManager USER_MANAGER = AntiCheat.getManager().getUserManager();
private static final XRayTracker XRAY_TRACKER = Anticheat.getManager().getXRayTracker(); private static final XRayTracker XRAY_TRACKER = AntiCheat.getManager().getXRayTracker();
private static final ChatColor RED = ChatColor.RED; private static final ChatColor RED = ChatColor.RED;
private static final ChatColor YELLOW = ChatColor.YELLOW; private static final ChatColor YELLOW = ChatColor.YELLOW;
private static final ChatColor GREEN = ChatColor.GREEN; private static final ChatColor GREEN = ChatColor.GREEN;
@@ -55,16 +57,18 @@ public class CommandHandler implements CommandExecutor {
public void handleLog(CommandSender cs, String[] args) { public void handleLog(CommandSender cs, String[] args) {
if (hasPermission(cs, Permission.SYSTEM_LOG)) { if (hasPermission(cs, Permission.SYSTEM_LOG)) {
if (args[1].equalsIgnoreCase("enable")) { if (args[1].equalsIgnoreCase("enable")) {
if (!CONFIG.logConsole()) { if (!CONFIG.getConfig().logToConsole.getValue()) {
CONFIG.setLog(true); CONFIG.getConfig().logToConsole.setValue(true);
cs.sendMessage(GREEN + "Console logging enabled."); cs.sendMessage(GREEN + "Console logging enabled.");
CONFIG.getConfig().reload();
} else { } else {
cs.sendMessage(GREEN + "Console logging is already enabled!"); cs.sendMessage(GREEN + "Console logging is already enabled!");
} }
} else if (args[1].equalsIgnoreCase("disable")) { } else if (args[1].equalsIgnoreCase("disable")) {
if (CONFIG.logConsole()) { if (CONFIG.getConfig().logToConsole.getValue()) {
CONFIG.setLog(false); CONFIG.getConfig().logToConsole.setValue(false);
cs.sendMessage(GREEN + "Console logging disabled."); cs.sendMessage(GREEN + "Console logging disabled.");
CONFIG.getConfig().reload();
} else { } else {
cs.sendMessage(GREEN + "Console logging is already disabled!"); cs.sendMessage(GREEN + "Console logging is already disabled!");
} }
@@ -94,7 +98,7 @@ public class CommandHandler implements CommandExecutor {
public void handleXRay(CommandSender cs, String[] args) { public void handleXRay(CommandSender cs, String[] args) {
if (hasPermission(cs, Permission.SYSTEM_XRAY)) { if (hasPermission(cs, Permission.SYSTEM_XRAY)) {
if (CONFIG.logXRay()) { if (CONFIG.getConfig().logXRayStats.getValue()) {
List<Player> list = SERVER.matchPlayer(args[1]); List<Player> list = SERVER.matchPlayer(args[1]);
if (list.size() == 1) { if (list.size() == 1) {
Player player = list.get(0); Player player = list.get(0);
@@ -128,7 +132,7 @@ public class CommandHandler implements CommandExecutor {
user.resetLevel(); user.resetLevel();
XRAY_TRACKER.reset(player.getName()); XRAY_TRACKER.reset(player.getName());
user.clearMessages(); user.clearMessages();
Anticheat.getManager().getBackend().resetChatLevel(player); AntiCheat.getManager().getBackend().resetChatLevel(player);
cs.sendMessage(player.getName() + GREEN + " has been reset."); cs.sendMessage(player.getName() + GREEN + " has been reset.");
} else { } else {
@@ -157,7 +161,7 @@ public class CommandHandler implements CommandExecutor {
if (!sender.hasMetadata(Utilities.SPY_METADATA)) // Maintain ORIGINAL location and other data if (!sender.hasMetadata(Utilities.SPY_METADATA)) // Maintain ORIGINAL location and other data
{ {
SpyState state = new SpyState(sender.getAllowFlight(), sender.isFlying(), sender.getLocation()); SpyState state = new SpyState(sender.getAllowFlight(), sender.isFlying(), sender.getLocation());
sender.setMetadata(Utilities.SPY_METADATA, new FixedMetadataValue(Anticheat.getPlugin(), state)); sender.setMetadata(Utilities.SPY_METADATA, new FixedMetadataValue(AntiCheat.getPlugin(), state));
} }
sender.setAllowFlight(true); sender.setAllowFlight(true);
sender.setFlying(true); sender.setFlying(true);
@@ -175,7 +179,7 @@ public class CommandHandler implements CommandExecutor {
sender.setAllowFlight(state.getAllowFlight()); sender.setAllowFlight(state.getAllowFlight());
sender.setFlying(state.getFlying()); sender.setFlying(state.getFlying());
sender.teleport(state.getLocation()); sender.teleport(state.getLocation());
sender.removeMetadata(Utilities.SPY_METADATA, Anticheat.getPlugin()); sender.removeMetadata(Utilities.SPY_METADATA, AntiCheat.getPlugin());
for (Player p : cs.getServer().getOnlinePlayers()) { for (Player p : cs.getServer().getOnlinePlayers()) {
p.showPlayer(sender); p.showPlayer(sender);
} }
@@ -215,11 +219,11 @@ public class CommandHandler implements CommandExecutor {
public void handleUpdate(CommandSender cs) { public void handleUpdate(CommandSender cs) {
if (hasPermission(cs, Permission.SYSTEM_UPDATE)) { if (hasPermission(cs, Permission.SYSTEM_UPDATE)) {
cs.sendMessage("Running " + GREEN + "AntiCheat " + WHITE + "v" + GREEN + Anticheat.getVersion()); cs.sendMessage("Running " + GREEN + "AntiCheat " + WHITE + "v" + GREEN + AntiCheat.getVersion());
cs.sendMessage(MENU_END); cs.sendMessage(MENU_END);
if (!Anticheat.isUpdated()) { if (!AntiCheat.isUpdated()) {
cs.sendMessage(GRAY + "There " + GREEN + "IS" + GRAY + " a newer version avaliable."); cs.sendMessage(GRAY + "There " + GREEN + "IS" + GRAY + " a newer version avaliable.");
if (CONFIG.autoUpdate()) { if (CONFIG.getConfig().autoUpdate.getValue()) {
cs.sendMessage(GRAY + "It will be installed automatically for you on next launch."); cs.sendMessage(GRAY + "It will be installed automatically for you on next launch.");
} else { } else {
cs.sendMessage(GRAY + "Due to your config settings, we " + RED + "can not" + GRAY + " auto update."); cs.sendMessage(GRAY + "Due to your config settings, we " + RED + "can not" + GRAY + " auto update.");
@@ -235,7 +239,7 @@ public class CommandHandler implements CommandExecutor {
if (cs instanceof Player) { if (cs instanceof Player) {
if (hasPermission(cs, Permission.SYSTEM_CALIBRATE)) { if (hasPermission(cs, Permission.SYSTEM_CALIBRATE)) {
Calibrator c = new Calibrator((Player) cs); Calibrator c = new Calibrator((Player) cs);
SERVER.getPluginManager().registerEvents(c, Anticheat.getPlugin()); SERVER.getPluginManager().registerEvents(c, AntiCheat.getPlugin());
c.calibrate(); c.calibrate();
} }
} }
@@ -310,10 +314,10 @@ public class CommandHandler implements CommandExecutor {
public void handlePlayerReport(CommandSender cs, String[] args) { public void handlePlayerReport(CommandSender cs, String[] args) {
if (hasPermission(cs, Permission.SYSTEM_REPORT)) { if (hasPermission(cs, Permission.SYSTEM_REPORT)) {
User user = Anticheat.getManager().getUserManager().getUser(args[1]); User user = AntiCheat.getManager().getUserManager().getUser(args[1]);
boolean cont = false; boolean cont = false;
if (user == null) { if (user == null) {
if ((user = Anticheat.getManager().getUserManager().loadUserFromFile(args[1])) == null) { if ((user = AntiCheat.getManager().getUserManager().loadUserFromFile(args[1])) == null) {
cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found."); cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found.");
} else { } else {
cont = true; cont = true;
@@ -341,15 +345,15 @@ public class CommandHandler implements CommandExecutor {
} }
public void handleDeveloper(CommandSender cs) { public void handleDeveloper(CommandSender cs) {
Anticheat.setDeveloperMode(!Anticheat.developerMode()); AntiCheat.setDeveloperMode(!AntiCheat.developerMode());
cs.sendMessage(ChatColor.GREEN + "Developer mode " + (Anticheat.developerMode() ? "ON" : "OFF")); cs.sendMessage(ChatColor.GREEN + "Developer mode " + (AntiCheat.developerMode() ? "ON" : "OFF"));
} }
public void sendPlayerReport(CommandSender cs, List<CheckType> types, User user, int page) { public void sendPlayerReport(CommandSender cs, List<CheckType> types, User user, int page) {
String name = user.getName(); String name = user.getName();
int pages = (int) Math.ceil(((float) types.size()) / 6); int pages = (int) Math.ceil(((float) types.size()) / 6);
String levelString = ChatColor.GREEN+"Low"; String levelString = ChatColor.GREEN+"Low";
for(Level level : CONFIG.getLevels()) { for(Level level : CONFIG.getEvents().levels) {
if(level.getValue() == user.getLevel()) { if(level.getValue() == user.getLevel()) {
levelString = level.getColor()+level.getName(); levelString = level.getColor()+level.getName();
} }
@@ -387,7 +391,7 @@ public class CommandHandler implements CommandExecutor {
public void handleReload(CommandSender cs) { public void handleReload(CommandSender cs) {
if (hasPermission(cs, Permission.SYSTEM_RELOAD)) { if (hasPermission(cs, Permission.SYSTEM_RELOAD)) {
CONFIG.load(); CONFIG.reload();
cs.sendMessage(GREEN + "AntiCheat configuration reloaded."); cs.sendMessage(GREEN + "AntiCheat configuration reloaded.");
} }
} }
@@ -396,7 +400,7 @@ public class CommandHandler implements CommandExecutor {
public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) { public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) {
if (args.length == 3) { if (args.length == 3) {
if (args[0].equalsIgnoreCase("report")) { if (args[0].equalsIgnoreCase("report")) {
for(Level level : CONFIG.getLevels()) { for(Level level : CONFIG.getEvents().levels) {
if(args[1].equalsIgnoreCase(level.getName())) { if(args[1].equalsIgnoreCase(level.getName())) {
handleReport(cs, args); handleReport(cs, args);
return true; return true;
@@ -18,7 +18,7 @@
package net.h31ix.anticheat.api; package net.h31ix.anticheat.api;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.manage.*; import net.h31ix.anticheat.manage.*;
import net.h31ix.anticheat.xray.XRayTracker; import net.h31ix.anticheat.xray.XRayTracker;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -29,9 +29,9 @@ import org.bukkit.entity.Player;
*/ */
public class AnticheatAPI { public class AnticheatAPI {
private static CheckManager chk = Anticheat.getManager().getCheckManager(); private static CheckManager chk = AntiCheat.getManager().getCheckManager();
private static UserManager umr = Anticheat.getManager().getUserManager(); private static UserManager umr = AntiCheat.getManager().getUserManager();
private static XRayTracker xtracker = Anticheat.getManager().getXRayTracker(); private static XRayTracker xtracker = AntiCheat.getManager().getXRayTracker();
// CheckManager API // CheckManager API
@@ -149,6 +149,6 @@ public class AnticheatAPI {
* @return the AntiCheat Manager * @return the AntiCheat Manager
*/ */
public static AnticheatManager getManager() { public static AnticheatManager getManager() {
return Anticheat.getManager(); return AntiCheat.getManager();
} }
} }
@@ -0,0 +1,104 @@
/*
* 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.h31ix.anticheat.config;
import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.files.*;
import net.h31ix.anticheat.config.files.Magic;
public class Configuration {
private final AntiCheat plugin;
private Config config;
private Events events;
private Lang lang;
private Enterprise enterprise;
private Levels levels;
private Magic magic;
public Configuration(AntiCheat plugin) {
this.plugin = plugin;
config = new Config(plugin, this);
events = new Events(plugin, this);
lang = new Lang(plugin, this);
enterprise = new Enterprise(plugin, this);
levels = new Levels(plugin, this);
magic = new Magic(plugin, this);
load();
}
public void load() {
for(ConfigurationFile file : new ConfigurationFile[]{config, events, lang, enterprise, levels, magic}) {
file.load();
checkReload(file);
}
}
public void save() {
config.save();
events.save();
lang.save();
enterprise.save();
levels.save();
magic.save();
}
private void checkReload(ConfigurationFile file) {
if(file.needsReload()) {
file.reload();
file.setNeedsReload(false);
}
}
public void reload() {
save();
load();
}
public Config getConfig() {
return config;
}
public Events getEvents() {
return events;
}
public Lang getLang() {
return lang;
}
public Enterprise getEnterprise() {
return enterprise;
}
public Levels getLevels() {
return levels;
}
public Magic getMagic() {
return magic;
}
}
@@ -0,0 +1,176 @@
/*
* 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.h31ix.anticheat.config;
import net.h31ix.anticheat.AntiCheat;
import net.h31ix.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;
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);
} 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;
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);
}
}
public String getPath() {
return path;
}
public T getValue() {
return (T) value;
}
public T setValue(T value) {
getConfigFile().set(path, value);
return value;
}
public T getDefaultValue() {
return (T) getDefaultConfigFile().get(path);
}
public boolean hasValue() {
return value != null;
}
}
}
@@ -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.h31ix.anticheat.config.files;
import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.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,73 @@
/*
* 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.h31ix.anticheat.config.files;
import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.config.ConfigurationFile;
import net.h31ix.anticheat.util.enterprise.Database;
public class Enterprise extends ConfigurationFile {
public static final String FILENAME = "enterprise.yml";
public ConfigValue<String> serverName;
public ConfigValue<String> loggingEnabled;
public ConfigValue<String> loggingLife;
public ConfigValue<String> usersEnabled;
public ConfigValue<String> usersInterval;
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<String>("logging.enable");
loggingLife = new ConfigValue<String>("logging.life");
usersEnabled = new ConfigValue<String>("users.enable");
usersInterval = new ConfigValue<String>("users.interval");
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");
// 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()
);
}
}
@@ -0,0 +1,98 @@
/*
* 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.h31ix.anticheat.config.files;
import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.config.ConfigurationFile;
import net.h31ix.anticheat.util.Level;
import net.h31ix.anticheat.util.rule.Rule;
import java.util.ArrayList;
import java.util.List;
public class Events extends ConfigurationFile {
public static final String FILENAME = "events.yml";
public List<Level> levels;
public List<Rule> rules;
public int highestLevel;
public Events(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
@Override
public void open() {
ConfigValue<List<String>> levels = new ConfigValue<List<String>>("levels");
ConfigValue<List<String>> actions = new ConfigValue<List<String>>("actions");
ConfigValue<List<String>> rules = new ConfigValue<List<String>>("rules");
// Convert levels list to Levels
this.levels = new ArrayList<Level>();
for(String string : levels.getValue()) {
Level level = Level.load(string);
if(level == null) {
continue;
}
this.levels.add(level);
highestLevel = level.getValue() > highestLevel ? level.getValue() : highestLevel;
}
// Convert actions list and add to corresponding Levels
for(String string : actions.getValue()) {
String name;
String action;
try {
name = string.split(": ")[0];
action = string.split(": ")[1];
} catch (Exception ex) {
AntiCheat.getPlugin().getLogger().warning("Couldn't load action '"+string+"' from config. Improper format used.");
break;
}
for(Level level : this.levels) {
if(level.getName().equalsIgnoreCase(name)) {
level.addAction(action);
}
}
}
// 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,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.h31ix.anticheat.config.files;
import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.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,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.h31ix.anticheat.config.files;
import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.config.ConfigurationFile;
public class Levels extends ConfigurationFile {
public static final String FILENAME = "data/levels.yml";
public Levels(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME, false);
}
public int getLevel(String name) {
ConfigValue<Integer> level = new ConfigValue<Integer>(name, false);
if(level.hasValue()) {
return level.getValue();
} else {
return -1;
}
}
public void saveLevel(String name, int level) {
new ConfigValue<Integer>(name, false).setValue(new Integer(level));
}
}
@@ -16,9 +16,11 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package net.h31ix.anticheat.util; package net.h31ix.anticheat.config.files;
import org.bukkit.configuration.file.FileConfiguration; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.config.ConfigurationFile;
/** /**
* Magic number class. Modifications to values in magic.yml will be accepted here. * Magic number class. Modifications to values in magic.yml will be accepted here.
@@ -36,445 +38,415 @@ import org.bukkit.configuration.file.FileConfiguration;
* 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. * 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 { public class Magic extends ConfigurationFile {
/** /**
* Time to exempt a player from moving because of entering/exiting a vehicle; Type=system, +Leniency=Increase. * Time to exempt a player from moving because of entering/exiting a vehicle; Type=system, +Leniency=Increase.
*/ */
public final int ENTERED_EXITED_TIME; public int ENTERED_EXITED_TIME;
/** /**
* Time to exempt a player from moving because of entering/exiting sneak mode; Type=system, +Leniency=Increase. * Time to exempt a player from moving because of entering/exiting sneak mode; Type=system, +Leniency=Increase.
*/ */
public final int SNEAK_TIME; public int SNEAK_TIME;
/** /**
* Time to exempt a player from moving because of teleporting; Type=system, +Leniency=Increase. * Time to exempt a player from moving because of teleporting; Type=system, +Leniency=Increase.
*/ */
public final int TELEPORT_TIME; public int TELEPORT_TIME;
/** /**
* Time to exempt a player from moving because of exiting fly mode; Type=system, +Leniency=Increase. * Time to exempt a player from moving because of exiting fly mode; Type=system, +Leniency=Increase.
*/ */
public final int EXIT_FLY_TIME; public int EXIT_FLY_TIME;
/** /**
* Time to exempt a player from moving because of joining the server; Type=system, +Leniency=Increase. * Time to exempt a player from moving because of joining the server; Type=system, +Leniency=Increase.
*/ */
public final int JOIN_TIME; public int JOIN_TIME;
/** /**
* Time to exempt a player from fastbreak check because of using instant break; Type=seconds, +Leniency=Increase. * Time to exempt a player from fastbreak check because of using instant break; Type=seconds, +Leniency=Increase.
*/ */
public final int INSTANT_BREAK_TIME; public int INSTANT_BREAK_TIME;
/** /**
* Time to exempt a player from moving because of taking damage; Type=system, +Leniency=Increase. * Time to exempt a player from moving because of taking damage; Type=system, +Leniency=Increase.
*/ */
public final long DAMAGE_TIME; public long DAMAGE_TIME;
/** /**
* Time to exempt a player from moving because of taking damage with knockback effects; Type=system, +Leniency=Increase. * Time to exempt a player from moving because of taking damage with knockback effects; Type=system, +Leniency=Increase.
*/ */
public final long KNOCKBACK_DAMAGE_TIME; public long KNOCKBACK_DAMAGE_TIME;
/** /**
* Time to exempt a player from moving because of taking damage from an explosion; Type=system, +Leniency=Increase. * Time to exempt a player from moving because of taking damage from an explosion; Type=system, +Leniency=Increase.
*/ */
public final long EXPLOSION_DAMAGE_TIME; public long EXPLOSION_DAMAGE_TIME;
/** /**
* Minimum time it takes to fire X projectiles; Type=system, +Leniency=Decrease. * Minimum time it takes to fire X projectiles; Type=system, +Leniency=Decrease.
*/ */
public final int PROJECTILE_TIME_MIN; public int PROJECTILE_TIME_MIN;
/** /**
* Number of projectiles to wait for before checking how long they took to fire off; Type=integer. * Number of projectiles to wait for before checking how long they took to fire off; Type=integer.
*/ */
public final int PROJECTILE_CHECK; public int PROJECTILE_CHECK;
/** /**
* Minimum time it takes to drop X items; Type=system, +Leniency=Decrease. * Minimum time it takes to drop X items; Type=system, +Leniency=Decrease.
*/ */
public final int DROP_TIME_MIN; public int DROP_TIME_MIN;
/** /**
* Number of item drops to wait for before checking how long they took to drop; Type=integer. * Number of item drops to wait for before checking how long they took to drop; Type=integer.
*/ */
public final int DROP_CHECK; public int DROP_CHECK;
/** /**
* Max number of blocks that can be broken in a given time; Type=integer, +Leniency=Increase. * Max number of blocks that can be broken in a given time; Type=integer, +Leniency=Increase.
*/ */
public final int FASTBREAK_LIMIT; public int FASTBREAK_LIMIT;
/** /**
* Time to wait before checking block breaks; Type=system, +Leniency=Increase. * Time to wait before checking block breaks; Type=system, +Leniency=Increase.
*/ */
public final int FASTBREAK_TIMEMAX; public int FASTBREAK_TIMEMAX;
/** /**
* Time to wait before checking block breaks in creative mode; Type=system, +Leniency=Increase. * Time to wait before checking block breaks in creative mode; Type=system, +Leniency=Increase.
*/ */
public final int FASTBREAK_TIMEMAX_CREATIVE; public int FASTBREAK_TIMEMAX_CREATIVE;
/** /**
* Number of times fastbreak can be observed before taking action; Type=integer, +Leniency=Increase. * Number of times fastbreak can be observed before taking action; Type=integer, +Leniency=Increase.
*/ */
public final int FASTBREAK_MAXVIOLATIONS; public int FASTBREAK_MAXVIOLATIONS;
/** /**
* Number of times fastbreak can be observed before taking action in creative mode; Type=integer, +Leniency=Increase. * Number of times fastbreak can be observed before taking action in creative mode; Type=integer, +Leniency=Increase.
*/ */
public final int FASTBREAK_MAXVIOLATIONS_CREATIVE; public int FASTBREAK_MAXVIOLATIONS_CREATIVE;
/** /**
* Time a player is forced to wait after fastbreak has been detected; Type=system, +Leniency=Decrease. * Time a player is forced to wait after fastbreak has been detected; Type=system, +Leniency=Decrease.
*/ */
public final int FASTBREAK_MAXVIOLATIONTIME; public int FASTBREAK_MAXVIOLATIONTIME;
/** /**
* Number of blocks that can be broken without being hit before taking action; Type=integer, +Leniency=Increase. * Number of blocks that can be broken without being hit before taking action; Type=integer, +Leniency=Increase.
*/ */
public final int FASTPLACE_ZEROLIMIT; public int FASTPLACE_ZEROLIMIT;
/** /**
* Minimum time in between block places; Type=system, +Leniency=Decrease. * Minimum time in between block places; Type=system, +Leniency=Decrease.
*/ */
public final int FASTPLACE_TIMEMIN; public int FASTPLACE_TIMEMIN;
/** /**
* Number of times fastplace can be observed before taking action; Type=integer, +Leniency=Increase. * Number of times fastplace can be observed before taking action; Type=integer, +Leniency=Increase.
*/ */
public final int FASTPLACE_MAXVIOLATIONS; public int FASTPLACE_MAXVIOLATIONS;
/** /**
* Number of times fastplace can be observed before taking action in creative mode; Type=integer, +Leniency=Increase. * Number of times fastplace can be observed before taking action in creative mode; Type=integer, +Leniency=Increase.
*/ */
public final int FASTPLACE_MAXVIOLATIONS_CREATIVE; public int FASTPLACE_MAXVIOLATIONS_CREATIVE;
/** /**
* Time a player is forced to wait after fastplace has been detected; Type=system, +Leniency=Decrease. * Time a player is forced to wait after fastplace has been detected; Type=system, +Leniency=Decrease.
*/ */
public final int FASTPLACE_MAXVIOLATIONTIME; public int FASTPLACE_MAXVIOLATIONTIME;
/** /**
* Number of times required to punch a block before it breaks; Type=integer, +Leniency=Decrease. * Number of times required to punch a block before it breaks; Type=integer, +Leniency=Decrease.
*/ */
public final int BLOCK_PUNCH_MIN; public int BLOCK_PUNCH_MIN;
/** /**
* Number of chat spam violations before a player is warned; Type=integer, +Leniency=Increase. * Number of chat spam violations before a player is warned; Type=integer, +Leniency=Increase.
*/ */
public final int CHAT_WARN_LEVEL; public int CHAT_WARN_LEVEL;
/** /**
* Number of chat spam violations before a player is kicked; Type=integer, +Leniency=Increase. * Number of chat spam violations before a player is kicked; Type=integer, +Leniency=Increase.
*/ */
public final int CHAT_KICK_LEVEL; public int CHAT_KICK_LEVEL;
/** /**
* Number of kicks for chat violation before a player is banned; Type=integer, +Leniency=Increase. * Number of kicks for chat violation before a player is banned; Type=integer, +Leniency=Increase.
*/ */
public final int CHAT_BAN_LEVEL; public int CHAT_BAN_LEVEL;
/** /**
* Number of times a player can be caught in-flight before action is taken; Type=integer, +Leniency=Increase. * Number of times a player can be caught in-flight before action is taken; Type=integer, +Leniency=Increase.
*/ */
public final int FLIGHT_LIMIT; public int FLIGHT_LIMIT;
/** /**
* How many blocks you can travel before action is taken; Type=integer, +Leniency=Increase. * How many blocks you can travel before action is taken; Type=integer, +Leniency=Increase.
*/ */
public final double FLIGHT_BLOCK_LIMIT; public double FLIGHT_BLOCK_LIMIT;
/** /**
* Maximum speed that a player can climb a waterfall; Type=double, +Leniency=Increase. * Maximum speed that a player can climb a waterfall; Type=double, +Leniency=Increase.
*/ */
public final double WATER_CLIMB_MAX; public double WATER_CLIMB_MAX;
/** /**
* Number of times a player can fly on the y-axis before action is taken; Type=integer, +Leniency=Increase. * Number of times a player can fly on the y-axis before action is taken; Type=integer, +Leniency=Increase.
*/ */
public final int Y_MAXVIOLATIONS; public int Y_MAXVIOLATIONS;
/** /**
* Time a player is forced to wait after flying on the y-axis; Type=system, +Leniency=Decrease. * Time a player is forced to wait after flying on the y-axis; Type=system, +Leniency=Decrease.
*/ */
public final int Y_MAXVIOTIME; public int Y_MAXVIOTIME;
/** /**
* Number of times a player can fail a velocity check before action is taken; Type=integer, +Leniency=Increase. * Number of times a player can fail a velocity check before action is taken; Type=integer, +Leniency=Increase.
*/ */
public final int VELOCITY_TIME; public int VELOCITY_TIME;
/** /**
* Time used to schedule increasing a players velocity count - probably not touching this would be good; Type=integer. * Time used to schedule increasing a players velocity count - probably not touching this would be good; Type=integer.
*/ */
public final long VELOCITY_SCHETIME; public long VELOCITY_SCHETIME;
/** /**
* Maximum time a player is considered to have a change in velocity; Type=system, +Leniency=Increase. * Maximum time a player is considered to have a change in velocity; Type=system, +Leniency=Increase.
*/ */
public final long VELOCITY_CHECKTIME; public long VELOCITY_CHECKTIME;
/** /**
* Time to extend a player's velocity count by; Type=system, +Leniency=Increase. * Time to extend a player's velocity count by; Type=system, +Leniency=Increase.
*/ */
public final long VELOCITY_PREVENT; public long VELOCITY_PREVENT;
/** /**
* Number of times a player can fail the velocity check before action is taken; Type=integer, +Leniency=Increase. * Number of times a player can fail the velocity check before action is taken; Type=integer, +Leniency=Increase.
*/ */
public final int VELOCITY_MAXTIMES; public int VELOCITY_MAXTIMES;
/** /**
* Number of times a player can fail the nofall check before action is taken; Type=integer, +Leniency=Increase. * Number of times a player can fail the nofall check before action is taken; Type=integer, +Leniency=Increase.
*/ */
public final int NOFALL_LIMIT; public int NOFALL_LIMIT;
/** /**
* Number of times a player can fail the ascension check before action is taken; Type=integer, +Leniency=Increase. * Number of times a player can fail the ascension check before action is taken; Type=integer, +Leniency=Increase.
*/ */
public final int ASCENSION_COUNT_MAX; 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. * Number of times a player can fail the ascension check while in water before action is taken; Type=integer, +Leniency=Increase.
*/ */
public final int WATER_ASCENSION_VIOLATION_MAX; 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. * Number of times a player can be caught speeding in water before action is taken; Type=integer, +Leniency=Increase.
*/ */
public final int WATER_SPEED_VIOLATION_MAX; 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. * Number of times a player can sprint without proper food level before action is taken; Type=integer, +Leniency=Increase.
*/ */
public final int SPRINT_FOOD_MIN; public int SPRINT_FOOD_MIN;
/** /**
* Minimum time between animations; Type=system, +Leniency=Increase. * Minimum time between animations; Type=system, +Leniency=Increase.
*/ */
public final int ANIMATION_MIN; public int ANIMATION_MIN;
/** /**
* Minimum time between chats; Type=system, +Leniency=Increase. * Minimum time between chats; Type=system, +Leniency=Increase.
*/ */
public final int CHAT_MIN; public int CHAT_MIN;
/** /**
* Minimum time between repeating yourself in the chat; Type=system, +Leniency=Increase. * Minimum time between repeating yourself in the chat; Type=system, +Leniency=Increase.
*/ */
public final int CHAT_REPEAT_MIN; public int CHAT_REPEAT_MIN;
/** /**
* Maximum speed you can travel while sprinting; Type=double, +Leniency=Increase. * Maximum speed you can travel while sprinting; Type=double, +Leniency=Increase.
*/ */
public final double SPRINT_MIN; public double SPRINT_MIN;
/** /**
* Minimum time in between block breaks; Type=seconds, +Leniency=Decrease. * Minimum time in between block breaks; Type=seconds, +Leniency=Decrease.
*/ */
public final double BLOCK_BREAK_MIN; public double BLOCK_BREAK_MIN;
/** /**
* Minimum time in between block placing; Type=seconds, +Leniency=Decrease. * Minimum time in between block placing; Type=seconds, +Leniency=Decrease.
*/ */
public final double BLOCK_PLACE_MIN; public double BLOCK_PLACE_MIN;
/** /**
* Minimum time in between healing; Type=system, +Leniency=Decrease. * Minimum time in between healing; Type=system, +Leniency=Decrease.
*/ */
public final long HEAL_TIME_MIN; public long HEAL_TIME_MIN;
/** /**
* Minimum time in between eating; Type=system, +Leniency=Decrease. * Minimum time in between eating; Type=system, +Leniency=Decrease.
*/ */
public final long EAT_TIME_MIN; public long EAT_TIME_MIN;
/** /**
* Maximum percent error between predicted bow force and actual bow force; Type=double, +Leniency=Increase. * Maximum percent error between predicted bow force and actual bow force; Type=double, +Leniency=Increase.
*/ */
public final double BOW_ERROR; public double BOW_ERROR;
/** /**
* Minimum distance a player can break a block from; Type=double, +Leniency=Increase. * Minimum distance a player can break a block from; Type=double, +Leniency=Increase.
*/ */
public final double BLOCK_MAX_DISTANCE; public double BLOCK_MAX_DISTANCE;
/** /**
* Minimum distance a player can break a block from in creative mode; Type=double, +Leniency=Increase. * Minimum distance a player can break a block from in creative mode; Type=double, +Leniency=Increase.
*/ */
public final double BLOCK_MAX_DISTANCE_CREATIVE; public double BLOCK_MAX_DISTANCE_CREATIVE;
/** /**
* Minimum distance a player can damage an entity from; Type=double, +Leniency=Increase. * Minimum distance a player can damage an entity from; Type=double, +Leniency=Increase.
*/ */
public final double ENTITY_MAX_DISTANCE; public double ENTITY_MAX_DISTANCE;
/** /**
* Minimum distance a player can damage an entity from in creative mode; Type=double, +Leniency=Increase. * Minimum distance a player can damage an entity from in creative mode; Type=double, +Leniency=Increase.
*/ */
public final double ENTITY_MAX_DISTANCE_CREATIVE; public double ENTITY_MAX_DISTANCE_CREATIVE;
/** /**
* Maximum speed a player on a ladder can travel; Type=double, +Leniency=Increase. * Maximum speed a player on a ladder can travel; Type=double, +Leniency=Increase.
*/ */
public final double LADDER_Y_MAX; public double LADDER_Y_MAX;
/** /**
* Minimum speed a player on a ladder can travel; Type=double, +Leniency=Decrease. * Minimum speed a player on a ladder can travel; Type=double, +Leniency=Decrease.
*/ */
public final double LADDER_Y_MIN; public double LADDER_Y_MIN;
/** /**
* Maximum speed a player can travel up; Type=double, +Leniency=Increase. * Maximum speed a player can travel up; Type=double, +Leniency=Increase.
*/ */
public final double Y_SPEED_MAX; public double Y_SPEED_MAX;
/** /**
* Maximum difference between the player's last 2 Y values when traveling up; Type=double, +Leniency=Increase. * Maximum difference between the player's last 2 Y values when traveling up; Type=double, +Leniency=Increase.
*/ */
public final double Y_MAXDIFF; public double Y_MAXDIFF;
/** /**
* Time in between Y difference measures; Type=system, +Leniency=Decrease. * Time in between Y difference measures; Type=system, +Leniency=Decrease.
*/ */
public final long Y_TIME; public long Y_TIME;
/** /**
* Maximum speed a player can travel forwards or backwards; Type=double, +Leniency=Increase. * Maximum speed a player can travel forwards or backwards; Type=double, +Leniency=Increase.
*/ */
public final double XZ_SPEED_MAX; public double XZ_SPEED_MAX;
/** /**
* Maximum speed a player can travel forwards or backwards while sprinting; Type=double, +Leniency=Increase. * Maximum speed a player can travel forwards or backwards while sprinting; Type=double, +Leniency=Increase.
*/ */
public final double XZ_SPEED_MAX_SPRINT; public double XZ_SPEED_MAX_SPRINT;
/** /**
* Maximum speed a player can travel forwards or backwards while flying; Type=double, +Leniency=Increase. * Maximum speed a player can travel forwards or backwards while flying; Type=double, +Leniency=Increase.
*/ */
public final double XZ_SPEED_MAX_FLY; public double XZ_SPEED_MAX_FLY;
/** /**
* Maximum speed a player can travel forwards or backwards while under the influence; Type=double, +Leniency=Increase. * Maximum speed a player can travel forwards or backwards while under the influence; Type=double, +Leniency=Increase.
*/ */
public final double XZ_SPEED_MAX_POTION; public double XZ_SPEED_MAX_POTION;
/** /**
* Maximum speed a player can travel forwards or backwards while sneaking; Type=double, +Leniency=Increase. * Maximum speed a player can travel forwards or backwards while sneaking; Type=double, +Leniency=Increase.
*/ */
public final double XZ_SPEED_MAX_SNEAK; public double XZ_SPEED_MAX_SNEAK;
/** /**
* Maximum speed a player can travel forwards or backwards in water; Type=double, +Leniency=Increase. * Maximum speed a player can travel forwards or backwards in water; Type=double, +Leniency=Increase.
*/ */
public final double XZ_SPEED_MAX_WATER; public double XZ_SPEED_MAX_WATER;
/** /**
* Maximum speed a player can travel forwards or backwards in water while sprinting; Type=double, +Leniency=Increase. * Maximum speed a player can travel forwards or backwards in water while sprinting; Type=double, +Leniency=Increase.
*/ */
public final double XZ_SPEED_MAX_WATER_SPRINT; public double XZ_SPEED_MAX_WATER_SPRINT;
/** /**
* Maximum speed a player can travel forwards or backwards on soul sand; Type=double, +Leniency=Increase. * Maximum speed a player can travel forwards or backwards on soul sand; Type=double, +Leniency=Increase.
*/ */
public final double XZ_SPEED_MAX_SOULSAND; public double XZ_SPEED_MAX_SOULSAND;
/** /**
* Maximum speed a player can travel forwards or backwards on soul sand while sprinting; Type=double, +Leniency=Increase. * Maximum speed a player can travel forwards or backwards on soul sand while sprinting; Type=double, +Leniency=Increase.
*/ */
public final double XZ_SPEED_MAX_SOULSAND_SPRINT; 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. * Maximum speed a player can travel forwards or backwards on soul sand while under the influence; Type=double, +Leniency=Increase.
*/ */
public final double XZ_SPEED_MAX_SOULSAND_POTION; public double XZ_SPEED_MAX_SOULSAND_POTION;
/** /**
* Maximum times a player can fail the speed check before action is taken; Type=integer, +Leniency=Increase. * Maximum times a player can fail the speed check before action is taken; Type=integer, +Leniency=Increase.
*/ */
public final int SPEED_MAX; public int SPEED_MAX;
/** /**
* The number of clicks we should wait before checking if the player has used fast inventory; Type=integer; +Leniency=Increase. * The number of clicks we should wait before checking if the player has used fast inventory; Type=integer; +Leniency=Increase.
*/ */
public final int INVENTORY_CHECK; public int INVENTORY_CHECK;
/** /**
* The minimum time it should have taken for the player to click X times; Type=integer; +Leniency=Increase. * The minimum time it should have taken for the player to click X times; Type=integer; +Leniency=Increase.
*/ */
public final long INVENTORY_TIMEMIN; public long INVENTORY_TIMEMIN;
/** /**
* The number of steps we should wait before checking if the player has used timer cheating; Type=integer; +Leniency=Increase. * The number of steps we should wait before checking if the player has used timer cheating; Type=integer; +Leniency=Increase.
*/ */
public final int TIMER_STEP_CHECK; public int TIMER_STEP_CHECK;
/** /**
* The minimum time it should have taken for the player to travel X steps; Type=system; +Leniency=Decrease. * The minimum time it should have taken for the player to travel X steps; Type=system; +Leniency=Decrease.
*/ */
public final long TIMER_TIMEMIN; public long TIMER_TIMEMIN;
/** /**
* Minimum travel distance for move to be considered a teleport and subsequently be ignored; Type=int; +Leniency=Increase. * Minimum travel distance for move to be considered a teleport and subsequently be ignored; Type=int; +Leniency=Increase.
*/ */
public final long TELEPORT_MIN; public long TELEPORT_MIN;
private FileConfiguration defaults;
private FileConfiguration magic;
private Configuration config;
private double version; private double version;
public Magic(FileConfiguration magic, Configuration config, FileConfiguration defaults, double version) { public Magic(AntiCheat plugin, Configuration config) {
this.magic = magic; super(plugin, config, "magic.yml");
this.config = config; }
this.defaults = defaults;
this.version = version;
// @Override
public void open() {
version = new ConfigValue<Double>("VERSION").getValue();
ENTERED_EXITED_TIME = getInt("ENTERED_EXITED_TIME"); if(version == 0.2D) {
SNEAK_TIME = getInt("SNEAK_TIME"); // 0.2 -> 0.3 diffs
TELEPORT_TIME = getInt("TELEPORT_TIME"); // Fix improperly stored double Y_MAXDIFF
EXIT_FLY_TIME = getInt("EXIT_FLY_TIME"); new ConfigValue<Double>("Y_MAXDIFF").setValue(new ConfigValue<Double>("Y_MAXDIFF").getDefaultValue());
JOIN_TIME = getInt("JOIN_TIME"); // Update version
INSTANT_BREAK_TIME = getInt("INSTANT_BREAK_TIME"); version = new ConfigValue<Double>("VERSION").setValue(0.3D);
DAMAGE_TIME = getLong("DAMAGE_TIME"); setNeedsReload(true);
KNOCKBACK_DAMAGE_TIME = getLong("KNOCKBACK_DAMAGE_TIME");
EXPLOSION_DAMAGE_TIME = getLong("EXPLOSION_DAMAGE_TIME"); }
PROJECTILE_TIME_MIN = getInt("PROJECTILE_TIME_MIN"); ENTERED_EXITED_TIME = new ConfigValue<Integer>("ENTERED_EXITED_TIME").getValue();
PROJECTILE_CHECK = getInt("PROJECTILE_CHECK"); SNEAK_TIME = new ConfigValue<Integer>("SNEAK_TIME").getValue();
DROP_TIME_MIN = getInt("DROP_TIME_MIN"); TELEPORT_TIME = new ConfigValue<Integer>("TELEPORT_TIME").getValue();
DROP_CHECK = getInt("DROP_CHECK"); EXIT_FLY_TIME = new ConfigValue<Integer>("EXIT_FLY_TIME").getValue();
FASTBREAK_LIMIT = getInt("FASTBREAK_LIMIT"); JOIN_TIME = new ConfigValue<Integer>("JOIN_TIME").getValue();
FASTBREAK_TIMEMAX = getInt("FASTBREAK_TIMEMAX"); INSTANT_BREAK_TIME = new ConfigValue<Integer>("INSTANT_BREAK_TIME").getValue();
FASTBREAK_TIMEMAX_CREATIVE = getInt("FASTBREAK_TIMEMAX_CREATIVE"); DAMAGE_TIME = new ConfigValue<Integer>("DAMAGE_TIME").getValue();
FASTBREAK_MAXVIOLATIONS = getInt("FASTBREAK_MAXVIOLATIONS"); KNOCKBACK_DAMAGE_TIME = new ConfigValue<Integer>("KNOCKBACK_DAMAGE_TIME").getValue();
FASTBREAK_MAXVIOLATIONS_CREATIVE = getInt("FASTBREAK_MAXVIOLATIONS_CREATIVE"); EXPLOSION_DAMAGE_TIME = new ConfigValue<Integer>("EXPLOSION_DAMAGE_TIME").getValue();
FASTBREAK_MAXVIOLATIONTIME = getInt("FASTBREAK_MAXVIOLATIONTIME"); PROJECTILE_TIME_MIN = new ConfigValue<Integer>("PROJECTILE_TIME_MIN").getValue();
FASTPLACE_ZEROLIMIT = getInt("FASTPLACE_ZEROLIMIT"); PROJECTILE_CHECK = new ConfigValue<Integer>("PROJECTILE_CHECK").getValue();
FASTPLACE_TIMEMIN = getInt("FASTPLACE_TIMEMIN"); DROP_TIME_MIN = new ConfigValue<Integer>("DROP_TIME_MIN").getValue();
FASTPLACE_MAXVIOLATIONS = getInt("FASTPLACE_MAXVIOLATIONS"); DROP_CHECK = new ConfigValue<Integer>("DROP_CHECK").getValue();
FASTPLACE_MAXVIOLATIONS_CREATIVE = getInt("FASTPLACE_MAXVIOLATIONS_CREATIVE"); FASTBREAK_LIMIT = new ConfigValue<Integer>("FASTBREAK_LIMIT").getValue();
FASTPLACE_MAXVIOLATIONTIME = getInt("FASTPLACE_MAXVIOLATIONTIME"); FASTBREAK_TIMEMAX = new ConfigValue<Integer>("FASTBREAK_TIMEMAX").getValue();
BLOCK_PUNCH_MIN = getInt("BLOCK_PUNCH_MIN"); FASTBREAK_TIMEMAX_CREATIVE = new ConfigValue<Integer>("FASTBREAK_TIMEMAX_CREATIVE").getValue();
CHAT_WARN_LEVEL = getInt("CHAT_WARN_LEVEL"); FASTBREAK_MAXVIOLATIONS = new ConfigValue<Integer>("FASTBREAK_MAXVIOLATIONS").getValue();
CHAT_KICK_LEVEL = getInt("CHAT_KICK_LEVEL"); FASTBREAK_MAXVIOLATIONS_CREATIVE = new ConfigValue<Integer>("FASTBREAK_MAXVIOLATIONS_CREATIVE").getValue();
CHAT_BAN_LEVEL = getInt("CHAT_BAN_LEVEL"); FASTBREAK_MAXVIOLATIONTIME = new ConfigValue<Integer>("FASTBREAK_MAXVIOLATIONTIME").getValue();
FLIGHT_LIMIT = getInt("FLIGHT_LIMIT"); FASTPLACE_ZEROLIMIT = new ConfigValue<Integer>("FASTPLACE_ZEROLIMIT").getValue();
FLIGHT_BLOCK_LIMIT = getDouble("FLIGHT_BLOCK_LIMIT"); FASTPLACE_TIMEMIN = new ConfigValue<Integer>("FASTPLACE_TIMEMIN").getValue();
WATER_CLIMB_MAX = getDouble("WATER_CLIMB_MAX"); FASTPLACE_MAXVIOLATIONS = new ConfigValue<Integer>("FASTPLACE_MAXVIOLATIONS").getValue();
Y_MAXVIOLATIONS = getInt("Y_MAXVIOLATIONS"); FASTPLACE_MAXVIOLATIONS_CREATIVE = new ConfigValue<Integer>("FASTPLACE_MAXVIOLATIONS_CREATIVE").getValue();
Y_MAXVIOTIME = getInt("Y_MAXVIOTIME"); FASTPLACE_MAXVIOLATIONTIME = new ConfigValue<Integer>("FASTPLACE_MAXVIOLATIONTIME").getValue();
VELOCITY_TIME = getInt("VELOCITY_TIME"); BLOCK_PUNCH_MIN = new ConfigValue<Integer>("BLOCK_PUNCH_MIN").getValue();
VELOCITY_SCHETIME = getLong("VELOCITY_SCHETIME"); CHAT_WARN_LEVEL = new ConfigValue<Integer>("CHAT_WARN_LEVEL").getValue();
VELOCITY_CHECKTIME = getLong("VELOCITY_CHECKTIME"); CHAT_KICK_LEVEL = new ConfigValue<Integer>("CHAT_KICK_LEVEL").getValue();
VELOCITY_PREVENT = getLong("VELOCITY_PREVENT"); CHAT_BAN_LEVEL = new ConfigValue<Integer>("CHAT_BAN_LEVEL").getValue();
VELOCITY_MAXTIMES = getInt("VELOCITY_MAXTIMES"); FLIGHT_LIMIT = new ConfigValue<Integer>("FLIGHT_LIMIT").getValue();
NOFALL_LIMIT = getInt("NOFALL_LIMIT"); FLIGHT_BLOCK_LIMIT = new ConfigValue<Double>("FLIGHT_BLOCK_LIMIT").getValue();
ASCENSION_COUNT_MAX = getInt("ASCENSION_COUNT_MAX"); WATER_CLIMB_MAX = new ConfigValue<Double>("WATER_CLIMB_MAX").getValue();
WATER_ASCENSION_VIOLATION_MAX = getInt("WATER_ASCENSION_VIOLATION_MAX"); Y_MAXVIOLATIONS = new ConfigValue<Integer>("Y_MAXVIOLATIONS").getValue();
WATER_SPEED_VIOLATION_MAX = getInt("WATER_SPEED_VIOLATION_MAX"); Y_MAXVIOTIME = new ConfigValue<Integer>("Y_MAXVIOTIME").getValue();
SPRINT_FOOD_MIN = getInt("SPRINT_FOOD_MIN"); VELOCITY_TIME = new ConfigValue<Integer>("VELOCITY_TIME").getValue();
ANIMATION_MIN = getInt("ANIMATION_MIN"); VELOCITY_SCHETIME = new ConfigValue<Integer>("VELOCITY_SCHETIME").getValue();
CHAT_MIN = getInt("CHAT_MIN"); VELOCITY_CHECKTIME = new ConfigValue<Integer>("VELOCITY_CHECKTIME").getValue();
CHAT_REPEAT_MIN = getInt("CHAT_REPEAT_MIN"); VELOCITY_PREVENT = new ConfigValue<Integer>("VELOCITY_PREVENT").getValue();
SPRINT_MIN = getDouble("SPRINT_MIN"); VELOCITY_MAXTIMES = new ConfigValue<Integer>("VELOCITY_MAXTIMES").getValue();
BLOCK_BREAK_MIN = getDouble("BLOCK_BREAK_MIN"); NOFALL_LIMIT = new ConfigValue<Integer>("NOFALL_LIMIT").getValue();
BLOCK_PLACE_MIN = getDouble("BLOCK_PLACE_MIN"); ASCENSION_COUNT_MAX = new ConfigValue<Integer>("ASCENSION_COUNT_MAX").getValue();
HEAL_TIME_MIN = getLong("HEAL_TIME_MIN"); WATER_ASCENSION_VIOLATION_MAX = new ConfigValue<Integer>("WATER_ASCENSION_VIOLATION_MAX").getValue();
EAT_TIME_MIN = getLong("EAT_TIME_MIN"); WATER_SPEED_VIOLATION_MAX = new ConfigValue<Integer>("WATER_SPEED_VIOLATION_MAX").getValue();
BOW_ERROR = getDouble("BOW_ERROR"); SPRINT_FOOD_MIN = new ConfigValue<Integer>("SPRINT_FOOD_MIN").getValue();
BLOCK_MAX_DISTANCE = getDouble("BLOCK_MAX_DISTANCE"); ANIMATION_MIN = new ConfigValue<Integer>("ANIMATION_MIN").getValue();
BLOCK_MAX_DISTANCE_CREATIVE = getDouble("BLOCK_MAX_DISTANCE_CREATIVE"); CHAT_MIN = new ConfigValue<Integer>("CHAT_MIN").getValue();
ENTITY_MAX_DISTANCE = getDouble("ENTITY_MAX_DISTANCE"); CHAT_REPEAT_MIN = new ConfigValue<Integer>("CHAT_REPEAT_MIN").getValue();
ENTITY_MAX_DISTANCE_CREATIVE = getDouble("ENTITY_MAX_DISTANCE_CREATIVE"); SPRINT_MIN = new ConfigValue<Double>("SPRINT_MIN").getValue();
LADDER_Y_MAX = getDouble("LADDER_Y_MAX"); BLOCK_BREAK_MIN = new ConfigValue<Double>("BLOCK_BREAK_MIN").getValue();
LADDER_Y_MIN = getDouble("LADDER_Y_MIN"); BLOCK_PLACE_MIN = new ConfigValue<Double>("BLOCK_PLACE_MIN").getValue();
Y_SPEED_MAX = getDouble("Y_SPEED_MAX"); HEAL_TIME_MIN = new ConfigValue<Integer>("HEAL_TIME_MIN").getValue();
Y_MAXDIFF = getDouble("Y_MAXDIFF"); EAT_TIME_MIN = new ConfigValue<Integer>("EAT_TIME_MIN").getValue();
Y_TIME = getLong("Y_TIME"); BOW_ERROR = new ConfigValue<Double>("BOW_ERROR").getValue();
XZ_SPEED_MAX = getDouble("XZ_SPEED_MAX"); BLOCK_MAX_DISTANCE = new ConfigValue<Double>("BLOCK_MAX_DISTANCE").getValue();
XZ_SPEED_MAX_SPRINT = getDouble("XZ_SPEED_MAX_SPRINT"); BLOCK_MAX_DISTANCE_CREATIVE = new ConfigValue<Double>("BLOCK_MAX_DISTANCE_CREATIVE").getValue();
XZ_SPEED_MAX_FLY = getDouble("XZ_SPEED_MAX_FLY"); ENTITY_MAX_DISTANCE = new ConfigValue<Double>("ENTITY_MAX_DISTANCE").getValue();
XZ_SPEED_MAX_POTION = getDouble("XZ_SPEED_MAX_POTION"); ENTITY_MAX_DISTANCE_CREATIVE = new ConfigValue<Double>("ENTITY_MAX_DISTANCE_CREATIVE").getValue();
XZ_SPEED_MAX_SNEAK = getDouble("XZ_SPEED_MAX_SNEAK"); LADDER_Y_MAX = new ConfigValue<Double>("LADDER_Y_MAX").getValue();
XZ_SPEED_MAX_WATER = getDouble("XZ_SPEED_MAX_WATER"); LADDER_Y_MIN = new ConfigValue<Double>("LADDER_Y_MIN").getValue();
XZ_SPEED_MAX_SOULSAND = getDouble("XZ_SPEED_MAX_SOULSAND"); Y_SPEED_MAX = new ConfigValue<Double>("Y_SPEED_MAX").getValue();
XZ_SPEED_MAX_SOULSAND_SPRINT = getDouble("XZ_SPEED_MAX_SOULSAND_SPRINT"); Y_MAXDIFF = new ConfigValue<Double>("Y_MAXDIFF").getValue();
XZ_SPEED_MAX_SOULSAND_POTION = getDouble("XZ_SPEED_MAX_SOULSAND_POTION"); Y_TIME = new ConfigValue<Integer>("Y_TIME").getValue();
XZ_SPEED_MAX_WATER_SPRINT = getDouble("XZ_SPEED_MAX_WATER_SPRINT"); XZ_SPEED_MAX = new ConfigValue<Double>("XZ_SPEED_MAX").getValue();
SPEED_MAX = getInt("SPEED_MAX"); XZ_SPEED_MAX_SPRINT = new ConfigValue<Double>("XZ_SPEED_MAX_SPRINT").getValue();
INVENTORY_CHECK = getInt("INVENTORY_CHECK"); XZ_SPEED_MAX_FLY = new ConfigValue<Double>("XZ_SPEED_MAX_FLY").getValue();
INVENTORY_TIMEMIN = getInt("INVENTORY_TIMEMIN"); XZ_SPEED_MAX_POTION = new ConfigValue<Double>("XZ_SPEED_MAX_POTION").getValue();
TIMER_STEP_CHECK = getInt("TIMER_STEP_CHECK"); XZ_SPEED_MAX_SNEAK = new ConfigValue<Double>("XZ_SPEED_MAX_SNEAK").getValue();
TIMER_TIMEMIN = getLong("TIMER_TIMEMIN"); XZ_SPEED_MAX_WATER = new ConfigValue<Double>("XZ_SPEED_MAX_WATER").getValue();
TELEPORT_MIN = getLong("TELEPORT_MIN"); 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();
} }
public double getVersion() { public double getVersion() {
return version; return version;
} }
public FileConfiguration getDefaults() {
return defaults;
}
private int getInt(String path) {
if (magic.contains(path)) {
return magic.getInt(path);
} else {
int i = defaults.getInt(path);
magic.set(path, i);
config.saveMagic(magic);
return i;
}
}
private double getDouble(String path) {
if (magic.contains(path)) {
return magic.getDouble(path);
} else {
double i = defaults.getDouble(path);
magic.set(path, i);
config.saveMagic(magic);
return i;
}
}
private long getLong(String path) {
if (magic.contains(path)) {
return magic.getLong(path);
} else {
long i = defaults.getLong(path);
magic.set(path, i);
config.saveMagic(magic);
return i;
}
}
} }
@@ -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.h31ix.anticheat.config.yaml;
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.Queue;
import java.util.logging.Level;
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;
/**
* An implementation of {@link org.bukkit.configuration.file.YamlConfiguration} which preserves comments.
* Note that this implementation is not synchronized.
* Some overridden code has been moved to this file from its implementation.
*/
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;
}
}
@@ -18,7 +18,7 @@
package net.h31ix.anticheat.event; package net.h31ix.anticheat.event;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.manage.CheckType; import net.h31ix.anticheat.manage.CheckType;
import net.h31ix.anticheat.util.CheckResult; import net.h31ix.anticheat.util.CheckResult;
import net.h31ix.anticheat.util.Distance; import net.h31ix.anticheat.util.Distance;
@@ -47,7 +47,7 @@ public class BlockListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
@@ -64,7 +64,7 @@ public class BlockListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
@@ -18,7 +18,7 @@
package net.h31ix.anticheat.event; package net.h31ix.anticheat.event;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.manage.CheckType; import net.h31ix.anticheat.manage.CheckType;
import net.h31ix.anticheat.util.CheckResult; import net.h31ix.anticheat.util.CheckResult;
import net.h31ix.anticheat.util.Distance; import net.h31ix.anticheat.util.Distance;
@@ -49,7 +49,7 @@ public class EntityListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -68,7 +68,7 @@ public class EntityListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -87,7 +87,7 @@ public class EntityListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
@@ -170,6 +170,6 @@ public class EntityListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
} }
@@ -21,27 +21,28 @@ package net.h31ix.anticheat.event;
import java.util.EnumMap; import java.util.EnumMap;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import net.h31ix.anticheat.Anticheat;
import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.manage.*; import net.h31ix.anticheat.manage.*;
import net.h31ix.anticheat.util.Configuration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
public class EventListener implements Listener { public class EventListener implements Listener {
private static final Map<CheckType, Integer> USAGE_LIST = new EnumMap<CheckType, Integer>(CheckType.class); 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 Map<String, Integer> DECREASE_LIST = new HashMap<String, Integer>();
private static final CheckManager CHECK_MANAGER = Anticheat.getManager().getCheckManager(); private static final CheckManager CHECK_MANAGER = AntiCheat.getManager().getCheckManager();
private static final Backend BACKEND = Anticheat.getManager().getBackend(); private static final Backend BACKEND = AntiCheat.getManager().getBackend();
private static final Anticheat PLUGIN = Anticheat.getManager().getPlugin(); private static final AntiCheat PLUGIN = AntiCheat.getManager().getPlugin();
private static final UserManager USER_MANAGER = Anticheat.getManager().getUserManager(); private static final UserManager USER_MANAGER = AntiCheat.getManager().getUserManager();
private static final Configuration CONFIG = Anticheat.getManager().getConfiguration(); private static final Configuration CONFIG = AntiCheat.getManager().getConfiguration();
public static void log(String message, Player player, CheckType type) { public static void log(String message, Player player, CheckType type) {
User user = getUserManager().getUser(player.getName()); User user = getUserManager().getUser(player.getName());
if(user != null) { // npc if(user != null) { // npc
logCheat(type, user); logCheat(type, user);
if (user.increaseLevel(type) && message != null) { if (user.increaseLevel(type) && message != null) {
Anticheat.getManager().log(message); AntiCheat.getManager().log(message);
} }
removeDecrease(user); removeDecrease(user);
} }
@@ -52,8 +53,8 @@ public class EventListener implements Listener {
// Ignore plugins that are creating NPCs with no names (why the hell) // Ignore plugins that are creating NPCs with no names (why the hell)
if (user != null && user.getName() != null) { if (user != null && user.getName() != null) {
type.logUse(user); type.logUse(user);
if (Anticheat.getManager().getConfiguration().getFileLogLevel() == 2 && type.getUses(user.getName()) % 10 == 0) { if (CONFIG.getConfig().fileLogLevel.getValue() == 2 && type.getUses(user.getName()) % 10 == 0) {
Anticheat.getManager().fileLog(user.getName() + " has triggered multiple " + type + " checks."); AntiCheat.getManager().fileLog(user.getName() + " has triggered multiple " + type + " checks.");
} }
} }
} }
@@ -110,7 +111,7 @@ public class EventListener implements Listener {
} }
public static AnticheatManager getManager() { public static AnticheatManager getManager() {
return Anticheat.getManager(); return AntiCheat.getManager();
} }
public static Backend getBackend() { public static Backend getBackend() {
@@ -121,7 +122,7 @@ public class EventListener implements Listener {
return USER_MANAGER; return USER_MANAGER;
} }
public static Anticheat getPlugin() { public static AntiCheat getPlugin() {
return PLUGIN; return PLUGIN;
} }
@@ -130,6 +131,6 @@ public class EventListener implements Listener {
} }
public static boolean silentMode() { public static boolean silentMode() {
return CONFIG.silentMode(); return CONFIG.getConfig().silentMode.getValue();
} }
} }
@@ -18,7 +18,7 @@
package net.h31ix.anticheat.event; package net.h31ix.anticheat.event;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.manage.CheckType; import net.h31ix.anticheat.manage.CheckType;
import net.h31ix.anticheat.manage.User; import net.h31ix.anticheat.manage.User;
import net.h31ix.anticheat.util.CheckResult; import net.h31ix.anticheat.util.CheckResult;
@@ -50,7 +50,7 @@ public class InventoryListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -18,7 +18,7 @@
package net.h31ix.anticheat.event; package net.h31ix.anticheat.event;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.manage.CheckType; import net.h31ix.anticheat.manage.CheckType;
import net.h31ix.anticheat.manage.User; import net.h31ix.anticheat.manage.User;
import net.h31ix.anticheat.util.CheckResult; import net.h31ix.anticheat.util.CheckResult;
@@ -45,7 +45,7 @@ public class PlayerListener extends EventListener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if (getCheckManager().willCheck(player, CheckType.SPAM) && getConfig().commandSpam()) { if (getCheckManager().willCheck(player, CheckType.SPAM) && getConfig().getConfig().blockCommandSpam.getValue()) {
CheckResult result = getBackend().checkSpam(player, event.getMessage()); CheckResult result = getBackend().checkSpam(player, event.getMessage());
if (result.failed()) { if (result.failed()) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
@@ -55,7 +55,7 @@ public class PlayerListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -64,7 +64,7 @@ public class PlayerListener extends EventListener {
getBackend().logEnterExit(event.getPlayer()); getBackend().logEnterExit(event.getPlayer());
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -73,7 +73,7 @@ public class PlayerListener extends EventListener {
getBackend().logEnterExit(event.getPlayer()); getBackend().logEnterExit(event.getPlayer());
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -92,7 +92,7 @@ public class PlayerListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -101,14 +101,14 @@ public class PlayerListener extends EventListener {
getBackend().logTeleport(event.getPlayer()); getBackend().logTeleport(event.getPlayer());
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
public void onPlayerChangeWorlds(PlayerChangedWorldEvent event) { public void onPlayerChangeWorlds(PlayerChangedWorldEvent event) {
getBackend().logTeleport(event.getPlayer()); getBackend().logTeleport(event.getPlayer());
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -117,7 +117,7 @@ public class PlayerListener extends EventListener {
getBackend().logToggleSneak(event.getPlayer()); getBackend().logToggleSneak(event.getPlayer());
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -132,13 +132,13 @@ public class PlayerListener extends EventListener {
getBackend().logVelocity(player); getBackend().logVelocity(player);
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) { public void onPlayerChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if (getCheckManager().willCheck(player, CheckType.SPAM) && getConfig().chatSpam()) { if (getCheckManager().willCheck(player, CheckType.SPAM) && getConfig().getConfig().blockChatSpam.getValue()) {
CheckResult result = getBackend().checkSpam(player, event.getMessage()); CheckResult result = getBackend().checkSpam(player, event.getMessage());
if (result.failed()) { if (result.failed()) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
@@ -148,7 +148,7 @@ public class PlayerListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -156,14 +156,14 @@ public class PlayerListener extends EventListener {
getBackend().clearChatLevel(event.getPlayer()); getBackend().clearChatLevel(event.getPlayer());
getBackend().garbageClean(event.getPlayer()); getBackend().garbageClean(event.getPlayer());
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
public void onPlayerQuit(PlayerQuitEvent event) { public void onPlayerQuit(PlayerQuitEvent event) {
getBackend().garbageClean(event.getPlayer()); getBackend().garbageClean(event.getPlayer());
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -179,7 +179,7 @@ public class PlayerListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -201,7 +201,7 @@ public class PlayerListener extends EventListener {
getBackend().checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference()); getBackend().checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference());
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
@@ -215,21 +215,21 @@ public class PlayerListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onPlayerEnterBed(PlayerBedEnterEvent event) { public void onPlayerEnterBed(PlayerBedEnterEvent event) {
getBackend().logEnterExit(event.getPlayer()); getBackend().logEnterExit(event.getPlayer());
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onPlayerExitBed(PlayerBedLeaveEvent event) { public void onPlayerExitBed(PlayerBedLeaveEvent event) {
getBackend().logEnterExit(event.getPlayer()); getBackend().logEnterExit(event.getPlayer());
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -237,7 +237,7 @@ public class PlayerListener extends EventListener {
Player player = event.getPlayer(); Player player = event.getPlayer();
getBackend().logAnimation(player); getBackend().logAnimation(player);
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler @EventHandler
@@ -269,7 +269,7 @@ public class PlayerListener extends EventListener {
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
@@ -409,7 +409,7 @@ public class PlayerListener extends EventListener {
} }
} }
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
@@ -18,7 +18,7 @@
package net.h31ix.anticheat.event; package net.h31ix.anticheat.event;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.vehicle.VehicleDestroyEvent;
@@ -33,7 +33,7 @@ public class VehicleListener extends EventListener {
getBackend().logEnterExit((Player) event.getEntered()); getBackend().logEnterExit((Player) event.getEntered());
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
@@ -42,7 +42,7 @@ public class VehicleListener extends EventListener {
getBackend().logEnterExit((Player) event.getExited()); getBackend().logEnterExit((Player) event.getExited());
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
@@ -52,6 +52,6 @@ public class VehicleListener extends EventListener {
getBackend().logEnterExit((Player) event.getVehicle().getPassenger()); getBackend().logEnterExit((Player) event.getVehicle().getPassenger());
} }
Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
} }
} }
@@ -28,8 +28,9 @@ import java.util.logging.FileHandler;
import java.util.logging.Handler; import java.util.logging.Handler;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import net.h31ix.anticheat.Anticheat;
import net.h31ix.anticheat.util.Configuration; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.util.FileFormatter; import net.h31ix.anticheat.util.FileFormatter;
import net.h31ix.anticheat.xray.XRayTracker; import net.h31ix.anticheat.xray.XRayTracker;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -37,12 +38,11 @@ import org.bukkit.ChatColor;
import org.bukkit.plugin.RegisteredListener; import org.bukkit.plugin.RegisteredListener;
/** /**
* <p>
* The internal hub for all managers. * The internal hub for all managers.
*/ */
public class AnticheatManager { public class AnticheatManager {
private static Anticheat plugin = null; private static AntiCheat plugin = null;
private static Configuration configuration; private static Configuration configuration;
private static XRayTracker xrayTracker = null; private static XRayTracker xrayTracker = null;
private static UserManager userManager = null; private static UserManager userManager = null;
@@ -55,17 +55,17 @@ public class AnticheatManager {
private static Handler fileHandler; private static Handler fileHandler;
private static final int LOG_LEVEL_HIGH = 3; private static final int LOG_LEVEL_HIGH = 3;
public AnticheatManager(Anticheat instance, Logger logger) { public AnticheatManager(AntiCheat instance, Logger logger) {
plugin = instance; plugin = instance;
// now load all the others!!!!! // now load all the others!!!!!
fileLogger = Logger.getLogger("net.h31ix.anticheat.Anticheat"); fileLogger = Logger.getLogger("net.h31ix.anticheat.AntiCheat");
configuration = new Configuration(plugin, this); configuration = new Configuration(plugin);
xrayTracker = new XRayTracker(); xrayTracker = new XRayTracker();
userManager = new UserManager(configuration); userManager = new UserManager(configuration);
checkManager = new CheckManager(this); checkManager = new CheckManager(this, configuration);
backend = new Backend(this); backend = new Backend(this);
try { try {
File file = new File(plugin.getDataFolder() + "/log"); File file = new File(plugin.getDataFolder(), "log");
if (!file.exists()) { if (!file.exists()) {
file.mkdir(); file.mkdir();
} }
@@ -83,13 +83,13 @@ public class AnticheatManager {
} }
public void log(String message, int i) { public void log(String message, int i) {
if (i != 1 && getConfiguration().logConsole()) { if (i != 1 && getConfiguration().getConfig().logToConsole.getValue()) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + message); Bukkit.getConsoleSender().sendMessage(ChatColor.RED + message);
} }
if (i == 0 && getConfiguration().getFileLogLevel() == LOG_LEVEL_HIGH) // Not an alert, normal log message if (i == 0 && getConfiguration().getConfig().fileLogLevel.getValue() == LOG_LEVEL_HIGH) // Not an alert, normal log message
{ {
fileLog(message); fileLog(message);
} else if (getConfiguration().getFileLogLevel() != 0) { // alert } else if (getConfiguration().getConfig().fileLogLevel.getValue() != 0) { // alert
fileLog(message); fileLog(message);
} }
logs.add(ChatColor.stripColor(message)); logs.add(ChatColor.stripColor(message));
@@ -110,7 +110,7 @@ public class AnticheatManager {
} }
public void addEvent(String e, RegisteredListener[] arr) { public void addEvent(String e, RegisteredListener[] arr) {
if (!configuration.eventChains()) if (!configuration.getConfig().eventChains.getValue())
return; return;
if (!eventcache.containsKey(e) || eventcache.get(e) > 30000L) { if (!eventcache.containsKey(e) || eventcache.get(e) > 30000L) {
eventchains.put(e, arr); eventchains.put(e, arr);
@@ -120,7 +120,7 @@ public class AnticheatManager {
public String getEventChainReport() { public String getEventChainReport() {
String gen = ""; String gen = "";
if (!configuration.eventChains()) { if (!configuration.getConfig().eventChains.getValue()) {
return "Event Chains is disabled by the configuration." + '\n'; return "Event Chains is disabled by the configuration." + '\n';
} }
@@ -149,7 +149,7 @@ public class AnticheatManager {
return gen; return gen;
} }
public Anticheat getPlugin() { public AntiCheat getPlugin() {
return plugin; return plugin;
} }
@@ -175,5 +175,7 @@ public class AnticheatManager {
public static void close() { public static void close() {
fileHandler.close(); fileHandler.close();
configuration.save();
} }
} }
@@ -24,12 +24,12 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.files.Lang;
import net.h31ix.anticheat.util.CheckResult; import net.h31ix.anticheat.util.CheckResult;
import net.h31ix.anticheat.util.CheckResult.Result; import net.h31ix.anticheat.util.CheckResult.Result;
import net.h31ix.anticheat.util.Distance; import net.h31ix.anticheat.util.Distance;
import net.h31ix.anticheat.util.Language; import net.h31ix.anticheat.config.files.Magic;
import net.h31ix.anticheat.util.Magic;
import net.h31ix.anticheat.util.Utilities; import net.h31ix.anticheat.util.Utilities;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.GameMode; import org.bukkit.GameMode;
@@ -94,11 +94,11 @@ public class Backend {
private Magic magic; private Magic magic;
private AnticheatManager manager = null; private AnticheatManager manager = null;
private Language lang = null; private Lang lang = null;
private static final CheckResult PASS = new CheckResult(Result.PASSED); private static final CheckResult PASS = new CheckResult(Result.PASSED);
public Backend(AnticheatManager instance) { public Backend(AnticheatManager instance) {
magic = instance.getConfiguration().getMagicInstance(); magic = instance.getConfiguration().getMagic();
manager = instance; manager = instance;
lang = manager.getConfiguration().getLang(); lang = manager.getConfiguration().getLang();
transparent.add((byte) -1); transparent.add((byte) -1);
@@ -462,7 +462,7 @@ public class Backend {
Location g = player.getLocation(); Location g = player.getLocation();
yAxisViolations.put(name, yAxisViolations.get(name) + 1); yAxisViolations.put(name, yAxisViolations.get(name) + 1);
yAxisLastViolation.put(name, System.currentTimeMillis()); yAxisLastViolation.put(name, System.currentTimeMillis());
if (!manager.getConfiguration().silentMode()) { if (!silentMode()) {
g.setY(lastYcoord.get(name)); g.setY(lastYcoord.get(name));
player.sendMessage(ChatColor.RED + "[AntiCheat] Fly hacking on the y-axis detected. Please wait 5 seconds to prevent getting damage."); player.sendMessage(ChatColor.RED + "[AntiCheat] Fly hacking on the y-axis detected. Please wait 5 seconds to prevent getting damage.");
if (g.getBlock().getTypeId() == 0) { if (g.getBlock().getTypeId() == 0) {
@@ -482,7 +482,7 @@ public class Backend {
Location g = player.getLocation(); Location g = player.getLocation();
yAxisViolations.put(name, yAxisViolations.get(name) + 1); yAxisViolations.put(name, yAxisViolations.get(name) + 1);
yAxisLastViolation.put(name, System.currentTimeMillis()); yAxisLastViolation.put(name, System.currentTimeMillis());
if (!manager.getConfiguration().silentMode()) { if (!silentMode()) {
g.setY(lastYcoord.get(name)); g.setY(lastYcoord.get(name));
if (g.getBlock().getTypeId() == 0) { if (g.getBlock().getTypeId() == 0) {
player.teleport(g); player.teleport(g);
@@ -656,7 +656,7 @@ public class Backend {
int i = fastBreakViolation.get(name); int i = fastBreakViolation.get(name);
if (i > violations && math < magic.FASTBREAK_MAXVIOLATIONTIME) { if (i > violations && math < magic.FASTBREAK_MAXVIOLATIONTIME) {
lastBlockBroken.put(name, System.currentTimeMillis()); lastBlockBroken.put(name, System.currentTimeMillis());
if (!manager.getConfiguration().silentMode()) { if (!silentMode()) {
player.sendMessage(ChatColor.RED + "[AntiCheat] Fastbreaking detected. Please wait 10 seconds before breaking blocks."); player.sendMessage(ChatColor.RED + "[AntiCheat] Fastbreaking detected. Please wait 10 seconds before breaking blocks.");
} }
return new CheckResult(Result.FAILED, player.getName()+" broke blocks too fast "+i+" times in a row (max="+violations+")"); return new CheckResult(Result.FAILED, player.getName()+" broke blocks too fast "+i+" times in a row (max="+violations+")");
@@ -715,17 +715,17 @@ public class Backend {
fastPlaceViolation.put(name, 0); fastPlaceViolation.put(name, 0);
} }
} else if (fastPlaceViolation.containsKey(name) && fastPlaceViolation.get(name) > violations) { } else if (fastPlaceViolation.containsKey(name) && fastPlaceViolation.get(name) > violations) {
Anticheat.debugLog("Noted that fastPlaceViolation contains key "+name+" with value "+fastPlaceViolation.get(name)); AntiCheat.debugLog("Noted that fastPlaceViolation contains key " + name + " with value " + fastPlaceViolation.get(name));
Long math = System.currentTimeMillis() - lastBlockPlaced.get(name); Long math = System.currentTimeMillis() - lastBlockPlaced.get(name);
Anticheat.debugLog("Player lastBlockPlaced value = "+lastBlockPlaced+", diff="+math); AntiCheat.debugLog("Player lastBlockPlaced value = " + lastBlockPlaced + ", diff=" + math);
if (lastBlockPlaced.get(name) > 0 && math < magic.FASTPLACE_MAXVIOLATIONTIME) { if (lastBlockPlaced.get(name) > 0 && math < magic.FASTPLACE_MAXVIOLATIONTIME) {
lastBlockPlaced.put(name, time); lastBlockPlaced.put(name, time);
if (!manager.getConfiguration().silentMode()) { if (!silentMode()) {
player.sendMessage(ChatColor.RED + "[AntiCheat] Fastplacing detected. Please wait 10 seconds before placing blocks."); player.sendMessage(ChatColor.RED + "[AntiCheat] Fastplacing detected. Please wait 10 seconds before placing blocks.");
} }
return new CheckResult(Result.FAILED, player.getName()+" placed blocks too fast "+fastBreakViolation.get(name)+" times in a row (max="+violations+")"); return new CheckResult(Result.FAILED, player.getName()+" placed blocks too fast "+fastBreakViolation.get(name)+" times in a row (max="+violations+")");
} else if (lastBlockPlaced.get(name) > 0 && math > magic.FASTPLACE_MAXVIOLATIONTIME) { } else if (lastBlockPlaced.get(name) > 0 && math > magic.FASTPLACE_MAXVIOLATIONTIME) {
Anticheat.debugLog("Reset facePlaceViolation for "+name); AntiCheat.debugLog("Reset facePlaceViolation for " + name);
fastPlaceViolation.put(name, 0); fastPlaceViolation.put(name, 0);
} }
} else if (lastBlockPlaced.containsKey(name)) { } else if (lastBlockPlaced.containsKey(name)) {
@@ -772,7 +772,7 @@ public class Backend {
user.clearMessages(); user.clearMessages();
break; break;
} else if((m.equalsIgnoreCase(msg) && i == 1) || System.currentTimeMillis() - user.getLastMessageTime() < magic.CHAT_MIN * 2) { } else if((m.equalsIgnoreCase(msg) && i == 1) || System.currentTimeMillis() - user.getLastMessageTime() < magic.CHAT_MIN * 2) {
return new CheckResult(Result.FAILED, lang.getChatWarning()); return new CheckResult(Result.FAILED, lang.spamWarning.getValue());
} }
} }
} }
@@ -1044,8 +1044,8 @@ public class Backend {
chatKicks.put(name, kick); chatKicks.put(name, kick);
} }
String event = kick <= magic.CHAT_BAN_LEVEL ? manager.getConfiguration().chatActionKick() : manager.getConfiguration().chatActionBan(); String event = kick <= magic.CHAT_BAN_LEVEL ? manager.getConfiguration().getConfig().spamKickAction.getValue() : manager.getConfiguration().getConfig().spamBanAction.getValue();
manager.getUserManager().execute(manager.getUserManager().getUser(player.getName()), Utilities.stringToList(event), CheckType.SPAM, lang.getChatKickReason() + "(" + kick + "/3)", Utilities.stringToList(lang.getChatWarning()), lang.getChatBanReason()); manager.getUserManager().execute(manager.getUserManager().getUser(player.getName()), Utilities.stringToList(event), CheckType.SPAM, lang.spamKickReason.getValue() + "(" + kick + "/3)", Utilities.stringToList(lang.spamWarning.getValue()), lang.spamBanReason.getValue());
} }
} else { } else {
increment(player, chatLevel, magic.CHAT_KICK_LEVEL); increment(player, chatLevel, magic.CHAT_KICK_LEVEL);
@@ -1068,4 +1068,8 @@ public class Backend {
} }
} }
} }
public boolean silentMode() {
return manager.getConfiguration().getConfig().silentMode.getValue();
}
} }
@@ -23,8 +23,8 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.util.Configuration; import net.h31ix.anticheat.config.Configuration;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -41,9 +41,9 @@ public class CheckManager {
private static int disabled = 0; private static int disabled = 0;
private static int exempt = 0; private static int exempt = 0;
public CheckManager(AnticheatManager instance) { public CheckManager(AnticheatManager instance, Configuration config) {
manager = instance; manager = instance;
config = manager.getConfiguration(); this.config = config;
} }
/** /**
@@ -127,7 +127,7 @@ public class CheckManager {
* @param player The player * @param player The player
*/ */
public boolean isOpExempt(Player player) { public boolean isOpExempt(Player player) {
return (this.manager.getConfiguration().opExempt() && player.isOp()); return (this.manager.getConfiguration().getConfig().exemptOp.getValue() && player.isOp());
} }
/** /**
@@ -137,7 +137,7 @@ public class CheckManager {
* @return true if the player's world is enabled * @return true if the player's world is enabled
*/ */
public boolean checkInWorld(Player player) { public boolean checkInWorld(Player player) {
return config.checkInWorld(player.getWorld()); return config.getConfig().exemptedWorlds.getValue().contains(player.getWorld());
} }
/** /**
@@ -163,11 +163,11 @@ public class CheckManager {
*/ */
public boolean willCheck(Player player, CheckType type) { public boolean willCheck(Player player, CheckType type) {
boolean check = isActive(type) boolean check = isActive(type)
&& config.checkInWorld(player.getWorld()) && checkInWorld(player)
&& !isExempt(player, type) && !isExempt(player, type)
&& !type.checkPermission(player) && !type.checkPermission(player)
&& !isOpExempt(player); && !isOpExempt(player);
Anticheat.debugLog("Check " + type + (check ? " run " : " not run ") + "on " + player.getName()); AntiCheat.debugLog("Check " + type + (check ? " run " : " not run ") + "on " + player.getName());
return check; return check;
} }
@@ -18,14 +18,13 @@
package net.h31ix.anticheat.manage; package net.h31ix.anticheat.manage;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.util.Configuration; import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.util.Level; import net.h31ix.anticheat.util.Level;
import net.h31ix.anticheat.util.Utilities; import net.h31ix.anticheat.util.Utilities;
import net.h31ix.anticheat.util.rule.Rule; import net.h31ix.anticheat.util.rule.Rule;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@@ -36,10 +35,8 @@ public class User {
private final String name; private final String name;
private int level = 0; private int level = 0;
private Location goodLocation; private Location goodLocation;
private boolean silentMode;
private List<ItemStack> inventorySnapshot = null; private List<ItemStack> inventorySnapshot = null;
private Configuration config = Anticheat.getManager().getConfiguration(); private Configuration config = AntiCheat.getManager().getConfiguration();
private List<Level> levels = new ArrayList<Level>();
private int toX, toY, toZ; private int toX, toY, toZ;
private String [] messages = new String[2]; private String [] messages = new String[2];
private Long [] messageTimes = new Long[2]; private Long [] messageTimes = new Long[2];
@@ -50,8 +47,7 @@ public class User {
* @param name Player's name * @param name Player's name
*/ */
public User(String name) { public User(String name) {
this.name = name; this(name, 0);
getConfigInfo();
} }
/** /**
@@ -63,13 +59,6 @@ public class User {
public User(String name, int level) { public User(String name, int level) {
this.name = name; this.name = name;
this.level = level; this.level = level;
getConfigInfo();
}
private void getConfigInfo() {
config = Anticheat.getManager().getConfiguration();
silentMode = config.silentMode();
levels = config.getLevels();
} }
/** /**
@@ -107,24 +96,24 @@ public class User {
*/ */
public boolean increaseLevel(CheckType type) { public boolean increaseLevel(CheckType type) {
if (getPlayer() != null && getPlayer().isOnline()) { if (getPlayer() != null && getPlayer().isOnline()) {
if (silentMode && type.getUses(name) % 4 != 0) { if (silentMode() && type.getUses(name) % 4 != 0) {
// Prevent silent mode from increasing the level way too fast // Prevent silent mode from increasing the level way too fast
return false; return false;
} else { } else {
level++; level++;
// Check levels // Check levels
for(Level l : levels) { for(Level l : getLevels()) {
if(l.getValue() == level) { if(l.getValue() == level) {
Anticheat.getManager().getUserManager().alert(this, l, type); AntiCheat.getManager().getUserManager().alert(this, l, type);
if(l.getValue() == config.getHighestLevel()) { if(l.getValue() == config.getEvents().highestLevel) {
level = l.getValue() - 10; level = l.getValue() - 10;
} }
} }
} }
// Execute rules // Execute rules
for(Rule rule : config.getRules()) { for(Rule rule : config.getEvents().rules) {
rule.check(this, type); rule.check(this, type);
} }
return true; return true;
@@ -147,7 +136,7 @@ public class User {
* @return true if the level was valid and set properly * @return true if the level was valid and set properly
*/ */
public boolean setLevel(int level) { public boolean setLevel(int level) {
if (level > 0 && level <= config.getHighestLevel()) { if (level > 0 && level <= config.getEvents().highestLevel) {
this.level = level; this.level = level;
return true; return true;
} else { } else {
@@ -302,4 +291,12 @@ public class User {
public Long getLastMessageTime() { public Long getLastMessageTime() {
return getMessageTime(0) == null ? -1 : getMessageTime(0); return getMessageTime(0) == null ? -1 : getMessageTime(0);
} }
private List<Level> getLevels() {
return config.getEvents().levels;
}
private boolean silentMode() {
return config.getConfig().silentMode.getValue();
}
} }
@@ -21,8 +21,8 @@ package net.h31ix.anticheat.manage;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.util.Configuration; import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.util.Level; import net.h31ix.anticheat.util.Level;
import net.h31ix.anticheat.util.Utilities; import net.h31ix.anticheat.util.Utilities;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -44,7 +44,7 @@ public class UserManager {
*/ */
public UserManager(Configuration conf) { public UserManager(Configuration conf) {
config = conf; config = conf;
alert = config.getLang().getAlert(); alert = config.getLang().alert.getValue();
} }
/** /**
@@ -84,7 +84,7 @@ public class UserManager {
* @param user User to remove * @param user User to remove
*/ */
public void remove(User user) { public void remove(User user) {
config.saveLevel(user.getName(), user.getLevel()); config.getLevels().saveLevel(user.getName(), user.getLevel());
users.remove(user); users.remove(user);
} }
@@ -150,7 +150,7 @@ public class UserManager {
* @return the user if found, null otherwise * @return the user if found, null otherwise
*/ */
public User loadUserFromFile(String name) { public User loadUserFromFile(String name) {
int level = config.getLevel(name); int level = config.getLevels().getLevel(name);
if (level == -1) { if (level == -1) {
return null; return null;
} else { } else {
@@ -185,7 +185,7 @@ public class UserManager {
* @param type The CheckType that triggered the alert * @param type The CheckType that triggered the alert
*/ */
public void execute(User user, List<String> actions, CheckType type) { public void execute(User user, List<String> actions, CheckType type) {
execute(user, actions, type, config.getLang().getKickReason(), config.getLang().getWarning(), config.getLang().getBanReason()); execute(user, actions, type, config.getLang().kickReason.getValue(), config.getLang().playerWarning.getValue(), config.getLang().banReason.getValue());
} }
/** /**
@@ -200,7 +200,7 @@ public class UserManager {
*/ */
public void execute(final User user, final List<String> actions, final CheckType type, final String kickReason, final List<String> warning, final String banReason) { 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 // Execute synchronously for thread safety when called from AsyncPlayerChatEvent
Bukkit.getScheduler().scheduleSyncDelayedTask(Anticheat.getPlugin(), new Runnable() { Bukkit.getScheduler().scheduleSyncDelayedTask(AntiCheat.getPlugin(), new Runnable() {
@Override @Override
public void run() { public void run() {
final String name = user.getName(); final String name = user.getName();
@@ -213,7 +213,7 @@ public class UserManager {
} }
} else if (event.equalsIgnoreCase("KICK")) { } else if (event.equalsIgnoreCase("KICK")) {
user.getPlayer().kickPlayer(RED + kickReason); user.getPlayer().kickPlayer(RED + kickReason);
String msg = RED + config.getLang().getKickBroadcast().replaceAll("&player", name); String msg = RED + config.getLang().kickBroadcast.getValue().replaceAll("&player", name);
if (!msg.equals("")) { if (!msg.equals("")) {
Bukkit.broadcastMessage(msg); Bukkit.broadcastMessage(msg);
} }
@@ -225,7 +225,7 @@ public class UserManager {
} else if (event.equalsIgnoreCase("BAN")) { } else if (event.equalsIgnoreCase("BAN")) {
user.getPlayer().setBanned(true); user.getPlayer().setBanned(true);
user.getPlayer().kickPlayer(RED + banReason); user.getPlayer().kickPlayer(RED + banReason);
String msg = RED + config.getLang().getBanBroadcast().replaceAll("&player", name); String msg = RED + config.getLang().banBroadcast.getValue().replaceAll("&player", name);
if (!msg.equals("")) { if (!msg.equals("")) {
Bukkit.broadcastMessage(msg); Bukkit.broadcastMessage(msg);
} }
@@ -1,444 +0,0 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.h31ix.anticheat.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import net.h31ix.anticheat.Anticheat;
import net.h31ix.anticheat.manage.AnticheatManager;
import net.h31ix.anticheat.util.rule.Rule;
import net.h31ix.anticheat.util.yaml.CommentedConfiguration;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
public class Configuration {
private AnticheatManager micromanage = null;
private Anticheat plugin;
private File configFile = null;
private File levelFile = null;
private File langFile = null;
private File magicFile = null;
private File eventsFile = null;
private File enterpriseFile = null;
private CommentedConfiguration config;
private FileConfiguration level;
private FileConfiguration magic;
private FileConfiguration events;
private FileConfiguration enterprise;
private boolean logConsole;
private boolean logXRay;
private boolean alertXRay;
private boolean autoUpdate;
private boolean verboseStartup;
private boolean chatSpam;
private boolean commandSpam;
private boolean silentMode;
private boolean opExempt;
private boolean trackCreativeXRay;
private boolean eventChains;
private boolean isEnterprise;
private int fileLogLevel = 0;
private String updateFolder;
private String chatActionKick;
private String chatActionBan;
private static Language language;
private List<String> exemptWorlds = new ArrayList<String>();
private List<Level> levels = new ArrayList<Level>();
private List<Rule> rules = new ArrayList<Rule>();
private Magic magicInstance;
private int highestLevel;
private boolean updateEvents = false;
public Configuration(Anticheat plugin, AnticheatManager instance) {
this.plugin = plugin;
micromanage = instance;
configFile = new File(micromanage.getPlugin().getDataFolder() + "/config.yml");
levelFile = new File(micromanage.getPlugin().getDataFolder() + "/data/level.yml");
langFile = new File(micromanage.getPlugin().getDataFolder() + "/lang.yml");
magicFile = new File(micromanage.getPlugin().getDataFolder() + "/magic.yml");
eventsFile = new File(micromanage.getPlugin().getDataFolder() + "/events.yml");
enterpriseFile = new File(micromanage.getPlugin().getDataFolder() + "/enterprise.yml");
//
language = new Language(YamlConfiguration.loadConfiguration(langFile), langFile);
}
private void save() {
try {
config.save(configFile);
events.save(eventsFile);
level.save(levelFile);
magic.save(magicFile);
if(isEnterprise) {
enterprise.save(enterpriseFile);
}
} catch (IOException ex) {
Logger.getLogger(Configuration.class.getName()).severe(ex.getMessage());
}
}
public boolean logConsole() {
return logConsole;
}
public boolean logXRay() {
return logXRay;
}
public boolean alertXRay() {
return alertXRay;
}
public boolean autoUpdate() {
return autoUpdate;
}
public boolean verboseStartup() {
return verboseStartup;
}
public boolean chatSpam() {
return chatSpam;
}
public boolean commandSpam() {
return commandSpam;
}
public String updateFolder() {
return updateFolder;
}
public boolean silentMode() {
return silentMode;
}
public boolean opExempt() {
return opExempt;
}
public boolean trackCreativeXRay() {
return trackCreativeXRay;
}
public boolean eventChains() {
return eventChains;
}
public boolean enterprise() {
return isEnterprise;
}
public String chatActionKick() {
return chatActionKick;
}
public String chatActionBan() {
return chatActionBan;
}
public int getFileLogLevel() {
return fileLogLevel;
}
public Language getLang() {
return language;
}
public List<Level> getLevels() {
return levels;
}
public int getHighestLevel() {
// TODO: setup
return highestLevel = -99;
}
public List<Rule> getRules() {
return rules;
}
public void setUpdateEvents() {
updateEvents = true;
}
public void updateEvents() {
// Update the old event system to events.yml
CommentedConfiguration config = CommentedConfiguration.loadConfig(configFile);
events = YamlConfiguration.loadConfiguration(Anticheat.getPlugin().getResource("events.yml"));
String medium = config.getString("Events.Level Medium");
String high = config.getString("Events.Level High");
int medValue = config.getString("Events.Medium threshold") != null ? config.getInt("Events.Medium threshold") : -1;
int highValue = config.getString("Events.High threshold") != null ? config.getInt("Events.High threshold") : -1;
config.set("Events", null);
Level mediumLevel = new Level("Medium", medValue != -1 ? medValue : 20, ChatColor.YELLOW);
Level highLevel = new Level("High", highValue != -1 ? highValue : 50, ChatColor.RED);
Level customLevel = new Level("Custom", -1, ChatColor.GREEN);
mediumLevel.addAction(medium != null ? medium : "WARN");
highLevel.addAction(high != null ? high : "KICK");
customLevel.addAction("COMMAND[ban &player;say hello world]");
levels.add(mediumLevel);
levels.add(highLevel);
levels.add(customLevel);
writeEvents();
updateEvents = false;
}
private void writeEvents() {
List<String> list = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
for(Level level : levels) {
list.add(level.toString());
for(String string : level.getActions()) {
list2.add(level.getName()+": "+string);
}
}
events.set("levels", list);
events.set("actions", list2);
save();
}
private void readEvents() {
levels = new ArrayList<Level>();
for(String string : events.getStringList("levels")) {
Level level = Level.load(string);
if(level == null) {
continue;
}
levels.add(level);
highestLevel = level.getValue() > highestLevel ? level.getValue() : highestLevel;
}
for(String string : events.getStringList("actions")) {
String name;
String action;
try {
name = string.split(": ")[0];
action = string.split(": ")[1];
} catch (Exception ex) {
Anticheat.getPlugin().getLogger().warning("Couldn't load action '"+string+"' from config. Improper formatting used.");
break;
}
for(Level level : levels) {
if(level.getName().equalsIgnoreCase(name)) {
level.addAction(action);
}
}
}
rules = new ArrayList<Rule>();
List<String> tempRules = events.getStringList("rules");
for(int i=0;i<tempRules.size();i++) {
String string = tempRules.get(i);
// Old default. Isn't valid anymore.
if (string.equals("Check:SPIDER > 0 ? Level=20 : none")) {
tempRules.set(i, "Check_SPIDER < 0 ? Player.KICK : null");
events.set("rules", tempRules);
continue;
} else if (string.equals("Check_SPIDER < 0 ? Player.KICK : null")) {
// New 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) {
rules.add(rule);
} else {
Anticheat.getPlugin().getLogger().warning("Couldn't load rule '"+string+"' from config. Improper formatting used.");
}
}
}
public final void load() {
config = CommentedConfiguration.loadConfig(configFile);
level = YamlConfiguration.loadConfiguration(levelFile);
magic = YamlConfiguration.loadConfiguration(magicFile);
events = YamlConfiguration.loadConfiguration(eventsFile);
language = new Language(YamlConfiguration.loadConfiguration(langFile), langFile);
updateFolder = Bukkit.getUpdateFolder();
// Begin pulling values from config.
logConsole = getBoolean("System.Log to console", false);
logXRay = getBoolean("XRay.Log xray stats", true);
autoUpdate = getBoolean("System.Auto update", true);
verboseStartup = getBoolean("System.Verbose startup", false);
alertXRay = getBoolean("XRay.Alert when xray is found", false);
fileLogLevel = getInt("System.File log level", 1);
silentMode = getBoolean("System.Silent mode", false);
opExempt = getBoolean("System.Exempt op", false);
trackCreativeXRay = getBoolean("XRay.Track creative", true);
eventChains = getBoolean("System.Event Chains", true);
isEnterprise = getBoolean("System.Enterprise", false);
chatActionKick = getString("Chat.Kick Action", "KICK");
chatActionBan = getString("Chat.Ban Action", "BAN");
chatSpam = getBoolean("Chat.Block chat spam", true);
commandSpam = getBoolean("Chat.Block command spam", false);
// Cleanup old values
if (config.getString("System.Block command spam") != null) {
config.set("System.Block command spam", null);
}
if (config.getString("System.Block chat spam") != null) {
config.set("System.Block chat spam", null);
}
// Worlds
List<String> list = new ArrayList<String>();
list.add("example-world");
list.add("example-world-2");
if (config.getList("Enable in") != null) {
List<String> list2 = config.getStringList("Enable in");
List<String> list3 = new ArrayList<String>();
for (World world : micromanage.getPlugin().getServer().getWorlds()) {
if (!list2.contains(world.getName())) {
list3.add(world.getName());
}
}
if (!list3.isEmpty()) {
list = list3;
}
config.set("Enable in", null);
}
if (config.getList("Disable in") == null) {
config.set("Disable in", list);
}
exemptWorlds = config.getStringList("Disable in");
if(updateEvents) {
updateEvents();
}
readEvents();
// End pulling values from config
String version = magic.getString("VERSION");
if(version == null) {
micromanage.log("Replacing Magic.yml file");
// Magic file needs a reset
magicFile.delete();
plugin.replaceMagic();
magic = YamlConfiguration.loadConfiguration(magicFile);
version = magic.getString("VERSION");
}
if(isEnterprise) {
if(!enterpriseFile.exists()) {
micromanage.getPlugin().save(micromanage.getPlugin().getResource("enterprise.yml"), enterpriseFile);
}
enterprise = YamlConfiguration.loadConfiguration(enterpriseFile);
}
save();
magicInstance = new Magic(getMagic(), this, CommentedConfiguration.loadConfiguration(micromanage.getPlugin().getResource("magic.yml")), Double.parseDouble(version));
if(micromanage.getBackend() != null) { // If this is first run, backend may not be setup yet (this is for reloads)
micromanage.getBackend().updateMagic(magicInstance);
}
}
private boolean getBoolean(String entry, boolean d) {
if (config.getString(entry) == null) {
config.set(entry, d);
return d;
} else {
return config.getBoolean(entry);
}
}
private int getInt(String entry, int d) {
if (config.getString(entry) == null) {
config.set(entry, d);
return d;
} else {
return config.getInt(entry);
}
}
private String getString(String entry, String d) {
if (config.getString(entry) == null) {
config.set(entry, d);
return d;
} else {
return config.getString(entry);
}
}
public void setLog(boolean b) {
config.set("System.Log to console", b);
this.logConsole = b;
try {
config.save(configFile);
} catch (IOException ex) {
Logger.getLogger(Configuration.class.getName()).severe(ex.toString());
}
}
public FileConfiguration getMagic() {
return magic;
}
public boolean checkInWorld(World world) {
return !exemptWorlds.contains(world.getName());
}
public int getLevel(String player) {
int x = -1;
if (level.getString(player) != null) {
x = level.getInt(player);
}
return x;
}
public void saveLevel(String user, int x) {
level.set(user, x);
}
public void saveLevels() {
try {
level.save(levelFile);
} catch (IOException ex) {
Logger.getLogger(Configuration.class.getName()).severe(ex.toString());
}
}
public void saveMagic(FileConfiguration newMagic) {
try {
newMagic.save(magicFile);
} catch (IOException ex) {
Logger.getLogger(Configuration.class.getName()).severe(ex.toString());
}
}
public Magic getMagicInstance() {
return magicInstance;
}
}
@@ -1,164 +0,0 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.h31ix.anticheat.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
public class Language {
private static List<String> alert = null;
private static List<String> warning = null;
private static String banReason = null;
private static String banBroadcast = null;
private static String kickReason = null;
private static String kickBroadcast = null;
private static String chatWarning = null;
private static String chatKickBroadcast = null;
private static String chatKickReason = null;
private static String chatBanBroadcast = null;
private static String chatBanReason = null;
private static final ChatColor GOLD = ChatColor.GOLD;
private static final ChatColor GRAY = ChatColor.GRAY;
private FileConfiguration file;
private File f;
public Language(FileConfiguration file, File f) {
this.file = file;
this.f = f;
// Begin medium_alert / high_alert -> alert swap
// We're doing it this way to preserve *most* changes the user might have made to the alert
List<String> list = file.getStringList("alert.medium_alert");
if(list != null && list.size() > 0) {
list.set(0, "&player has just entered the &level hack level.");
file.set("alert.medium_alert", null);
file.set("alert.high_alert", null);
file.set("alert", list);
save();
}
// End swap
List<String> defAlert = new ArrayList<String>();
defAlert.add("&player has just entered the &level hack level.");
defAlert.add("&player's last failed check was: &check.");
defAlert.add("Type '/anticheat report &player' for more information.");
List<String> temp = getStringList("alert", defAlert);
alert = new ArrayList<String>();
alert.add(GOLD + "----------------------[" + GRAY + "AntiCheat" + GOLD + "]----------------------");
for (int i = 0; i < temp.size(); i++) {
alert.add(GRAY + temp.get(i));
}
alert.add(GOLD + "-----------------------------------------------------");
List<String> defWarning = new ArrayList<String>();
defWarning.add("[AntiCheat] Hacking is not permitted.");
defWarning.add("[AntiCheat] If you continue to hack, action will be taken.");
warning = getStringList("warning.player_warning", defWarning);
banReason = getString("ban.ban_reason", "Banned by AntiCheat");
banBroadcast = getString("ban.ban_broadcast", "[AntiCheat] &player was banned for hacking.");
kickReason = getString("kick.kick_reason", "Kicked by AntiCheat");
kickBroadcast = getString("kick.kick_broadcast", "[AntiCheat] &player was kicked for hacking.");
chatWarning = getString("chat.warning", "Stop spamming the server or you will be kicked!");
chatKickReason = getString("chat.kick_reason", "Kicked for spamming");
chatBanReason = getString("chat.ban_reason", "Banned for spamming");
chatKickBroadcast = getString("chat.kick_broadcast", "[AntiCheat] &player was kicked for spamming");
chatBanBroadcast = getString("chat.ban_broadcast", "[AntiCheat] &player was banned for spamming");
save();
}
private void save() {
try {
file.save(f);
} catch (IOException ex) {
Logger.getLogger(Language.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<String> getAlert() {
return alert;
}
public List<String> getWarning() {
return warning;
}
public String getBanReason() {
return banReason;
}
public String getBanBroadcast() {
return banBroadcast;
}
public String getKickReason() {
return kickReason;
}
public String getKickBroadcast() {
return kickBroadcast;
}
public String getChatKickReason() {
return chatKickReason;
}
public String getChatKickBroadcast() {
return chatKickBroadcast;
}
public String getChatBanReason() {
return chatBanReason;
}
public String getChatBanBroadcast() {
return chatBanBroadcast;
}
public String getChatWarning() {
return chatWarning;
}
private String getString(String entry, String d) {
if (file.getString(entry) == null) {
file.set(entry, d);
return d;
} else {
return file.getString(entry);
}
}
private List<String> getStringList(String entry, List<String> d) {
if (file.getString(entry) == null) {
file.set(entry, d);
return d;
} else {
return file.getStringList(entry);
}
}
}
@@ -20,7 +20,8 @@ package net.h31ix.anticheat.util;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import net.h31ix.anticheat.Anticheat;
import net.h31ix.anticheat.AntiCheat;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
public class Level { public class Level {
@@ -46,8 +47,8 @@ public class Level {
this(name, value); this(name, value);
ChatColor c = ChatColor.valueOf(color); ChatColor c = ChatColor.valueOf(color);
if(c == null) { if(c == null) {
Anticheat.getPlugin().getLogger().warning("Event '"+name+"' was initialized with the color '"+color+"' which is invalid."); 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"); 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 { } else {
this.color = c; this.color = c;
customColor = true; customColor = true;
@@ -90,9 +91,9 @@ public class Level {
return new Level(name, level); return new Level(name, level);
} }
} catch (Exception ex) { } catch (Exception ex) {
Anticheat.getPlugin().getLogger().warning("An event was initialized with an invalid string: '"+string+"'"); AntiCheat.getPlugin().getLogger().warning("An event was initialized with an invalid string: '"+string+"'");
Anticheat.getPlugin().getLogger().warning("The proper format is: 'name: threshold : color' such as 'High : 50 : RED'"); AntiCheat.getPlugin().getLogger().warning("The proper format is: 'name: threshold : color' such as 'High : 50 : RED'");
Anticheat.getPlugin().getLogger().warning("This event will NOT run. ("+ex.getMessage()+")"); AntiCheat.getPlugin().getLogger().warning("This event will NOT run. ("+ex.getMessage()+")");
return null; return null;
} }
} }
@@ -25,13 +25,11 @@ import java.net.URL;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.files.Magic;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -101,7 +99,7 @@ public class PastebinReport {
} }
private void appendLogs() { private void appendLogs() {
List<String> logs = Anticheat.getManager().getLastLogs(); List<String> logs = AntiCheat.getManager().getLastLogs();
if(logs.size() == 0) { if(logs.size() == 0) {
append("No recent logs."); append("No recent logs.");
return; return;
@@ -113,7 +111,7 @@ public class PastebinReport {
private void appendSystemInfo() { private void appendSystemInfo() {
Runtime runtime = Runtime.getRuntime(); Runtime runtime = Runtime.getRuntime();
append("AntiCheat Version: " + Anticheat.getVersion() + (Anticheat.isUpdated() ? "" : " (OUTDATED)")); append("AntiCheat Version: " + AntiCheat.getVersion() + (AntiCheat.isUpdated() ? "" : " (OUTDATED)"));
append("Server Version: " + Bukkit.getVersion()); append("Server Version: " + Bukkit.getVersion());
append("Server Implementation: " + Bukkit.getName()); append("Server Implementation: " + Bukkit.getName());
append("Server ID: " + Bukkit.getServerId()); append("Server ID: " + Bukkit.getServerId());
@@ -129,8 +127,8 @@ public class PastebinReport {
private void appendMagicDiff() { private void appendMagicDiff() {
// This is hacky, and I like it // This is hacky, and I like it
Magic magic = Anticheat.getManager().getConfiguration().getMagicInstance(); Magic magic = AntiCheat.getManager().getConfiguration().getMagic();
FileConfiguration file = magic.getDefaults(); FileConfiguration file = magic.getDefaultConfigFile();
append("Version: " + magic.getVersion()); append("Version: " + magic.getVersion());
boolean changed = false; boolean changed = false;
for(Field field : Magic.class.getFields()) { for(Field field : Magic.class.getFields()) {
@@ -157,11 +155,11 @@ public class PastebinReport {
} }
private void appendEventHandlers() { private void appendEventHandlers() {
report.append(Anticheat.getManager().getEventChainReport()); report.append(AntiCheat.getManager().getEventChainReport());
} }
private void writeReport() throws IOException { private void writeReport() throws IOException {
File f = new File(Anticheat.getPlugin().getDataFolder() + "/report.txt"); File f = new File(AntiCheat.getPlugin().getDataFolder() + "/report.txt");
FileWriter r = new FileWriter(f); FileWriter r = new FileWriter(f);
BufferedWriter writer = new BufferedWriter(r); BufferedWriter writer = new BufferedWriter(r);
writer.write(report.toString()); writer.write(report.toString());
@@ -23,7 +23,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
@@ -44,6 +44,7 @@ public final class Utilities {
private static final List<Material> SHOVELS = new ArrayList<Material>(); private static final List<Material> SHOVELS = new ArrayList<Material>();
private static final List<Material> ANY = new ArrayList<Material>(); private static final List<Material> ANY = new ArrayList<Material>();
private static final Map<Material, Material> COMBO = new HashMap<Material, Material>(); private static final Map<Material, Material> COMBO = new HashMap<Material, Material>();
public static final String SPY_METADATA = "ac-spydata"; public static final String SPY_METADATA = "ac-spydata";
/** /**
@@ -60,14 +61,14 @@ public final class Utilities {
} }
} }
} }
if (Anticheat.getManager().getConfiguration().logConsole()) { if (AntiCheat.getManager().getConfiguration().getConfig().logToConsole.getValue()) {
for (String msg : message) { for (String msg : message) {
Anticheat.getManager().log(msg); AntiCheat.getManager().log(msg);
} }
} }
if (Anticheat.getManager().getConfiguration().getFileLogLevel() != 0) { if (AntiCheat.getManager().getConfiguration().getConfig().fileLogLevel.getValue() != 0) {
for (String msg : message) { for (String msg : message) {
Anticheat.getManager().log(msg, 1); AntiCheat.getManager().log(msg, 1);
} }
} }
} }
@@ -21,7 +21,7 @@ package net.h31ix.anticheat.util.enterprise;
public class Database { public class Database {
public enum DatabaseType { public enum DatabaseType {
MYSQL, MySQL,
} }
private DatabaseType type; private DatabaseType type;
@@ -29,16 +29,44 @@ public class Database {
private int port; private int port;
private String username; private String username;
private String password; private String password;
private String schema;
private String prefix; private String prefix;
private String schema;
public Database(DatabaseType type, String hostname, int port, String username, String password, String schema, String prefix) { public Database(DatabaseType type, String hostname, int port, String username, String password, String prefix, String schema) {
this.type = type; this.type = type;
this.hostname = hostname; this.hostname = hostname;
this.port = port; this.port = port;
this.username = username; this.username = username;
this.password = password; this.password = password;
this.schema = schema;
this.prefix = prefix; this.prefix = prefix;
this.schema = schema;
}
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;
} }
} }
@@ -18,7 +18,7 @@
package net.h31ix.anticheat.util.rule; package net.h31ix.anticheat.util.rule;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.manage.CheckType; import net.h31ix.anticheat.manage.CheckType;
import net.h31ix.anticheat.manage.User; import net.h31ix.anticheat.manage.User;
import net.h31ix.anticheat.util.Utilities; import net.h31ix.anticheat.util.Utilities;
@@ -84,7 +84,7 @@ public class Rule {
} }
public Rule(String string, Type type) { public Rule(String string, Type type) {
this.string = string = Utilities.removeWhitespace(string).toLowerCase(); this.string = Utilities.removeWhitespace(string).toLowerCase();
this.type = type; this.type = type;
} }
@@ -156,7 +156,7 @@ public class Rule {
text = text.split("\\.")[1]; text = text.split("\\.")[1];
List<String> action = new ArrayList<String>(); List<String> action = new ArrayList<String>();
action.add(text); action.add(text);
Anticheat.getManager().getUserManager().execute(user, action, type); AntiCheat.getManager().getUserManager().execute(user, action, type);
} }
} }
@@ -1,132 +0,0 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.h31ix.anticheat.util.yaml;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
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.representer.Representer;
public class CommentedConfiguration extends YamlConfiguration {
private Map<String, String> comments = new HashMap<String, String>();
private final DumperOptions yamlOptions = new DumperOptions();
private final Representer yamlRepresenter = new YamlRepresenter();
private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
private String lastLine = null;
public CommentedConfiguration() {
// Val 1 = line comment should be under
// Val 2 = comment
comments.put("XRay:", " # Should AntiCheat use calculations to try and find xrayers?");
comments.put("Log xray stats:", " # Should a warning be sent to admins when a person is found that could be xraying?");
comments.put("Alert when xray is found:", " # Should players in creative mode be tracked for possible xray usage?");
comments.put("Chat:", " # Should AntiCheat block players spamming messages in chat?");
comments.put("Block chat spam:", " # Should AntiCheat block players spamming commands in chat?");
comments.put("Block command spam:", " # Valid actions = NONE,KICK,BAN,COMMAND[command]");
comments.put("System:", " # Turning auto-update off is a _BAD_ idea. You will no longer be protected by the latest hacks/cheats if you do so, and will have to update manually.");
comments.put("# Turning auto-update off is a _BAD_ idea. You will no longer be protected by the latest hacks/cheats if you do so, and will have to update manually.", " # Should AntiCheat log ALL failed checks to console?");
comments.put("Log to console:", " # Should AntiCheat log to files?");
comments.put("# Should AntiCheat log to files?", " # 0 = off, 1 = log only when an event takes place, 2 = more detailed logs, 3 = most detailed logs");
comments.put("File log level:", " # Should AntiCheat display extra debug information when starting?");
comments.put("Verbose startup:", " # If silent mode is on, players will not be stopped when they try to hack, and AntiCheat will do everything possible to keep them unaware of their rising hack level.");
comments.put("# If silent mode is on, players will not be stopped when they try to hack, and AntiCheat will do everything possible to keep them unaware of their rising hack level.", " # However, alerts will still be sent to console and to admins online, and events will still take place.");
comments.put("Silent mode:", " # Should ops be exempt from all checks?");
comments.put("Exempt op:", " # Should AntiCheat track plugins in its own registered events?");
}
@Override
public String saveToString() {
yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
String dump = yaml.dump(getValues(false));
if (dump.equals(BLANK_CONFIG)) {
dump = "";
} else {
StringBuilder builder = new StringBuilder();
String[] lines = dump.split("\n");
int i = 0;
while (i < lines.length) {
if (containsLine(lines[i])) {
builder.append(lines[i]);
builder.append("\n");
builder.append(getComment(lines[i]));
builder.append("\n");
lastLine = getComment(getComment(lines[i]));
i++;
} else if (containsLine(lastLine)) {
builder.append(getComment(lastLine));
builder.append("\n");
lastLine = getComment(lastLine);
} else {
builder.append(lines[i]);
builder.append("\n");
i++;
}
}
dump = "# AntiCheat configuration file\n# Please report any bugs: http://dev.bukkit.org/server-mods/anticheat/\n" + builder.toString();
}
return dump;
}
private boolean containsLine(String line) {
if (line != null) {
for (String string : comments.keySet()) {
if (string.replaceAll(" ", "").split(":")[0].equalsIgnoreCase(line.replaceAll(" ", "").split(":")[0])) { return true; }
}
}
return false;
}
private String getComment(String line) {
for (String string : comments.keySet()) {
if (string.replaceAll(" ", "").split(":")[0].equalsIgnoreCase(line.replaceAll(" ", "").split(":")[0])) { return comments.get(string); }
}
return null;
}
public static CommentedConfiguration loadConfig(File file) {
CommentedConfiguration config = new CommentedConfiguration();
try {
config.load(file);
} catch (FileNotFoundException ex) {} catch (IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex);
} catch (InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex);
}
return config;
}
}
@@ -18,10 +18,10 @@
package net.h31ix.anticheat.xray; package net.h31ix.anticheat.xray;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.manage.CheckManager; import net.h31ix.anticheat.manage.CheckManager;
import net.h31ix.anticheat.manage.CheckType; import net.h31ix.anticheat.manage.CheckType;
import net.h31ix.anticheat.util.Configuration;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -30,15 +30,15 @@ import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
public class XRayListener implements Listener { public class XRayListener implements Listener {
private XRayTracker tracker = Anticheat.getManager().getXRayTracker(); private XRayTracker tracker = AntiCheat.getManager().getXRayTracker();
private Configuration config = Anticheat.getManager().getConfiguration(); private Configuration config = AntiCheat.getManager().getConfiguration();
private CheckManager checkManager = Anticheat.getManager().getCheckManager(); private CheckManager checkManager = AntiCheat.getManager().getCheckManager();
@EventHandler @EventHandler
public void onBlockBreak(BlockBreakEvent event) { public void onBlockBreak(BlockBreakEvent event) {
if (config.logXRay()) { if (config.getConfig().logXRayStats.getValue()) {
Player p = event.getPlayer(); Player p = event.getPlayer();
if (p.getGameMode() == GameMode.CREATIVE && !config.trackCreativeXRay()) { return; } if (p.getGameMode() == GameMode.CREATIVE && !config.getConfig().trackCreativeXRay.getValue()) { return; }
String player = p.getName(); String player = p.getName();
if (checkManager.willCheck(p, CheckType.XRAY)) { if (checkManager.willCheck(p, CheckType.XRAY)) {
Material m = event.getBlock().getType(); Material m = event.getBlock().getType();
+3
View File
@@ -34,3 +34,6 @@ System:
Event Chains: true Event Chains: true
# Should Enterprise options be enabled? Only set this to true if you're an advanced user. # Should Enterprise options be enabled? Only set this to true if you're an advanced user.
Enterprise: false Enterprise: false
Disable in:
- example-world
- example-world-2
+14 -24
View File
@@ -1,40 +1,30 @@
# AntiCheat configuration file # AntiCheat configuration file
# Please report any bugs: http://dev.bukkit.org/server-mods/anticheat/ # Please report any bugs: http://dev.bukkit.org/server-mods/anticheat/
# Server-specific settings # Server-specific settings
server: server:
# An identifiable name for this server # An identifiable name for this server
name: 'server-1' name: 'server-1'
# Database settings # Database settings
database: database:
# Type of database. # Type of database.
type: MySQL type: MySQL
# Address of the server
# Address of the server hostname: ''
hostname: '' # Port of the server
port: 3306
# Port of the server # Username to connect with
port: 3306 username: ''
# Password for the user
# Username to connect with password: ''
username: '' # Prefix for the tables
prefix: 'ac_'
# Password for the user # Database/Schema to use
password: '' database: 'minecraft'
# Prefix for the tables
prefix: 'ac_'
# Database/Schema to use
database: 'minecraft'
logging: logging:
# Keep events in the database? # Keep events in the database?
enable: true enable: true
# Time for actions logged to stay in the database (in days) # Time for actions logged to stay in the database (in days)
life: 2 life: 2
users: users:
# Synchronize user's levels in the database? # Synchronize user's levels in the database?
enable: true enable: true
+2 -3
View File
@@ -74,10 +74,9 @@ XZ_SPEED_MAX_SOULSAND_POTION: 0.16
XZ_SPEED_MAX_SPRINT: 0.65 XZ_SPEED_MAX_SPRINT: 0.65
XZ_SPEED_MAX_WATER: 0.19 XZ_SPEED_MAX_WATER: 0.19
XZ_SPEED_MAX_WATER_SPRINT: 0.3 XZ_SPEED_MAX_WATER_SPRINT: 0.3
Y_MAXDIFF: 5 Y_MAXDIFF: 5.0
Y_MAXVIOLATIONS: 1 Y_MAXVIOLATIONS: 1
Y_MAXVIOTIME: 5000 Y_MAXVIOTIME: 5000
Y_SPEED_MAX: 0.5 Y_SPEED_MAX: 0.5
Y_TIME: 1000 Y_TIME: 1000
VERSION: 0.3
VERSION: 0.2
+1 -1
View File
@@ -1,7 +1,7 @@
author: H31IX author: H31IX
database: false database: false
description: Prevention of hacks and other malicious tinkering on a Minecraft server. description: Prevention of hacks and other malicious tinkering on a Minecraft server.
main: net.h31ix.anticheat.Anticheat main: net.h31ix.anticheat.AntiCheat
name: AntiCheat name: AntiCheat
softdepend: [AntiCheat] softdepend: [AntiCheat]
startup: postworld startup: postworld