Sanity clean up

This commit is contained in:
h31ix committed 2013-10-11 11:16:15 -04:00
1 parent ca4406809b
commit 9486e18c4f
42 files changed
+524 -598

No files matched your search

+3 -2
View File
@@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>net.h31ix.anticheat</groupId> <groupId>net.h31ix.anticheat</groupId>
<artifactId>AntiCheat</artifactId> <artifactId>AntiCheat</artifactId>
@@ -52,7 +53,7 @@
<version>2.2</version> <version>2.2</version>
</extension> </extension>
</extensions> </extensions>
</build> </build>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
@@ -18,10 +18,6 @@
package net.h31ix.anticheat; package net.h31ix.anticheat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolLibrary;
import net.h31ix.anticheat.config.Configuration; import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.event.*; import net.h31ix.anticheat.event.*;
@@ -38,6 +34,9 @@ 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;
import java.util.ArrayList;
import java.util.List;
public class AntiCheat extends JavaPlugin { public class AntiCheat extends JavaPlugin {
private static AnticheatManager manager; private static AnticheatManager manager;
@@ -157,8 +156,8 @@ public class AntiCheat extends JavaPlugin {
} }
private void setupEnterprise() { private void setupEnterprise() {
if(config.getConfig().enterprise.getValue()) { if (config.getConfig().enterprise.getValue()) {
if(config.getEnterprise().loggingEnabled.getValue()) { if (config.getEnterprise().loggingEnabled.getValue()) {
config.getEnterprise().database.cleanEvents(); config.getEnterprise().database.cleanEvents();
} }
} }
@@ -214,7 +213,7 @@ public class AntiCheat extends JavaPlugin {
public static void debugLog(final String string) { public static void debugLog(final String string) {
Bukkit.getScheduler().runTask(getPlugin(), new Runnable() { Bukkit.getScheduler().runTask(getPlugin(), new Runnable() {
public void run() { public void run() {
if(developer) { if (developer) {
manager.log("[DEBUG] " + string); manager.log("[DEBUG] " + string);
} }
} }
@@ -18,9 +18,6 @@
package net.h31ix.anticheat; package net.h31ix.anticheat;
import java.util.ArrayList;
import java.util.List;
import net.h31ix.anticheat.config.Configuration; 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;
@@ -36,6 +33,9 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.FixedMetadataValue;
import java.util.ArrayList;
import java.util.List;
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();
@@ -128,7 +128,7 @@ public class CommandHandler implements CommandExecutor {
if (list.size() == 1) { if (list.size() == 1) {
Player player = list.get(0); Player player = list.get(0);
User user = USER_MANAGER.getUser(player.getName()); User user = USER_MANAGER.getUser(player.getName());
if(user != null) { if (user != null) {
user.resetLevel(); user.resetLevel();
XRAY_TRACKER.reset(player.getName()); XRAY_TRACKER.reset(player.getName());
user.clearMessages(); user.clearMessages();
@@ -197,7 +197,7 @@ public class CommandHandler implements CommandExecutor {
public void handleHelp(CommandSender cs) { public void handleHelp(CommandSender cs) {
if (hasPermission(cs, Permission.SYSTEM_HELP)) { if (hasPermission(cs, Permission.SYSTEM_HELP)) {
String base = "/AntiCheat "; String base = "/AntiCheat ";
String [] lines = { String[] lines = {
"log [Enable/Disable]" + WHITE + " - toggle logging", "log [Enable/Disable]" + WHITE + " - toggle logging",
"report [low/medium/high]" + WHITE + " - show users in groups", "report [low/medium/high]" + WHITE + " - show users in groups",
"report [user]" + WHITE + " - get a player's cheat report", "report [user]" + WHITE + " - get a player's cheat report",
@@ -211,7 +211,7 @@ public class CommandHandler implements CommandExecutor {
}; };
cs.sendMessage("----------------------[" + GREEN + "AntiCheat" + WHITE + "]----------------------"); cs.sendMessage("----------------------[" + GREEN + "AntiCheat" + WHITE + "]----------------------");
for(String s : lines) { for (String s : lines) {
cs.sendMessage(base + GREEN + s); cs.sendMessage(base + GREEN + s);
} }
} }
@@ -356,7 +356,7 @@ public class CommandHandler implements CommandExecutor {
Level level = user.getNamedLevel(); Level level = user.getNamedLevel();
String levelString = ChatColor.GREEN + "Low"; String levelString = ChatColor.GREEN + "Low";
if(level != null) { if (level != null) {
levelString = level.getColor() + level.getName(); levelString = level.getColor() + level.getName();
} }
levelString += " (" + user.getLevel() + ")"; levelString += " (" + user.getLevel() + ")";
@@ -403,8 +403,8 @@ 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.getEvents().getLevels()) { for (Level level : CONFIG.getEvents().getLevels()) {
if(args[1].equalsIgnoreCase(level.getName())) { if (args[1].equalsIgnoreCase(level.getName())) {
handleReport(cs, args); handleReport(cs, args);
return true; return true;
} }
@@ -479,7 +479,7 @@ public class CommandHandler implements CommandExecutor {
} }
public boolean hasPermission(CommandSender cs, Permission perm) { public boolean hasPermission(CommandSender cs, Permission perm) {
if(perm.get(cs)) { if (perm.get(cs)) {
return true; return true;
} else { } else {
cs.sendMessage(PERMISSIONS_ERROR + " (" + WHITE + perm.toString() + RED + ")"); cs.sendMessage(PERMISSIONS_ERROR + " (" + WHITE + perm.toString() + RED + ")");
@@ -19,12 +19,14 @@
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.AnticheatManager;
import net.h31ix.anticheat.manage.CheckManager;
import net.h31ix.anticheat.manage.CheckType;
import net.h31ix.anticheat.manage.UserManager;
import net.h31ix.anticheat.xray.XRayTracker; import net.h31ix.anticheat.xray.XRayTracker;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
/** /**
* <p>
* Developer's interface for all things AntiCheat. * Developer's interface for all things AntiCheat.
*/ */
@@ -67,7 +69,7 @@ public class AnticheatAPI {
* Allow a player to skip a certain check * Allow a player to skip a certain check
* *
* @param player Player to stop watching * @param player Player to stop watching
* @param type Check to stop watching for * @param type Check to stop watching for
*/ */
public static void exemptPlayer(Player player, CheckType type) { public static void exemptPlayer(Player player, CheckType type) {
chk.exemptPlayer(player, type); chk.exemptPlayer(player, type);
@@ -77,7 +79,7 @@ public class AnticheatAPI {
* Stop allowing a player to skip a certain check * Stop allowing a player to skip a certain check
* *
* @param player Player to start watching * @param player Player to start watching
* @param type Check to start watching for * @param type Check to start watching for
*/ */
public static void unexemptPlayer(Player player, CheckType type) { public static void unexemptPlayer(Player player, CheckType type) {
chk.unexemptPlayer(player, type); chk.unexemptPlayer(player, type);
@@ -87,7 +89,7 @@ public class AnticheatAPI {
* Find out if a player is currently exempt from a certain check * Find out if a player is currently exempt from a certain check
* *
* @param player Player to check * @param player Player to check
* @param type Type to check * @param type Type to check
* @return true if plugin is ignoring this check on this player * @return true if plugin is ignoring this check on this player
*/ */
public static boolean isExempt(Player player, CheckType type) { public static boolean isExempt(Player player, CheckType type) {
@@ -98,7 +100,7 @@ public class AnticheatAPI {
* Find out if a check will occur for a player. This checks if they are being tracked, the check is active, the player isn't exempt from the check, and the player doesn't have override permission. * Find out if a check will occur for a player. This checks if they are being tracked, the check is active, the player isn't exempt from the check, and the player doesn't have override permission.
* *
* @param player Player to check * @param player Player to check
* @param type Type to check * @param type Type to check
* @return true if plugin will check this player, and that all things allow it to happen. * @return true if plugin will check this player, and that all things allow it to happen.
*/ */
public boolean willCheck(Player player, CheckType type) { public boolean willCheck(Player player, CheckType type) {
@@ -122,7 +124,7 @@ public class AnticheatAPI {
* Set a player's hack level (Min = 0, Max = 50) * Set a player's hack level (Min = 0, Max = 50)
* *
* @param player Player to set * @param player Player to set
* @param level Level to set to * @param level Level to set to
*/ */
public static void setLevel(Player player, int level) { public static void setLevel(Player player, int level) {
umr.safeSetLevel(player.getName(), level); umr.safeSetLevel(player.getName(), level);
@@ -50,6 +50,7 @@ public class CheckFailEvent extends Event {
/** /**
* Get the {@link net.h31ix.anticheat.manage.CheckType} failed * Get the {@link net.h31ix.anticheat.manage.CheckType} failed
*
* @return a {@link net.h31ix.anticheat.manage.CheckType} * @return a {@link net.h31ix.anticheat.manage.CheckType}
*/ */
public CheckType getCheck() { public CheckType getCheck() {
@@ -19,13 +19,15 @@
package net.h31ix.anticheat.config; package net.h31ix.anticheat.config;
import net.h31ix.anticheat.AntiCheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.files.*; import net.h31ix.anticheat.config.files.Config;
import net.h31ix.anticheat.config.files.Enterprise;
import net.h31ix.anticheat.config.files.Lang;
import net.h31ix.anticheat.config.files.Magic; import net.h31ix.anticheat.config.files.Magic;
import net.h31ix.anticheat.config.holders.mysql.MySQLEventsHolder; import net.h31ix.anticheat.config.holders.mysql.MySQLEventsHolder;
import net.h31ix.anticheat.config.holders.mysql.MySQLLevelsHolder; import net.h31ix.anticheat.config.holders.mysql.MySQLLevelsHolder;
import net.h31ix.anticheat.config.holders.mysql.MySQLRulesHolder; import net.h31ix.anticheat.config.holders.mysql.MySQLRulesHolder;
import net.h31ix.anticheat.config.holders.yaml.YamlLevelsHolder;
import net.h31ix.anticheat.config.holders.yaml.YamlEventsHolder; import net.h31ix.anticheat.config.holders.yaml.YamlEventsHolder;
import net.h31ix.anticheat.config.holders.yaml.YamlLevelsHolder;
import net.h31ix.anticheat.config.holders.yaml.YamlRulesHolder; import net.h31ix.anticheat.config.holders.yaml.YamlRulesHolder;
import net.h31ix.anticheat.config.providers.Events; import net.h31ix.anticheat.config.providers.Events;
import net.h31ix.anticheat.config.providers.Levels; import net.h31ix.anticheat.config.providers.Levels;
@@ -54,53 +56,59 @@ public class Configuration {
lang = new Lang(plugin, this); lang = new Lang(plugin, this);
magic = new Magic(plugin, this); magic = new Magic(plugin, this);
flatfiles = new ArrayList<ConfigurationFile>(){{ add(config); add(enterprise); add(lang); add(magic); }}; flatfiles = new ArrayList<ConfigurationFile>() {{
add(config);
add(enterprise);
add(lang);
add(magic);
}};
dbfiles = new ArrayList<ConfigurationTable>(); dbfiles = new ArrayList<ConfigurationTable>();
// The following values can be configuration from a database, or from flatfile. // The following values can be configuration from a database, or from flatfile.
if(config.enterprise.getValue() && enterprise.configEvents.getValue()) { if (config.enterprise.getValue() && enterprise.configEvents.getValue()) {
events = new MySQLEventsHolder(this); events = new MySQLEventsHolder(this);
dbfiles.add((MySQLEventsHolder)events); dbfiles.add((MySQLEventsHolder) events);
} else { } else {
events = new YamlEventsHolder(plugin, this); events = new YamlEventsHolder(plugin, this);
flatfiles.add((YamlEventsHolder)events); flatfiles.add((YamlEventsHolder) events);
} }
if(config.enterprise.getValue() && enterprise.configRules.getValue()) { if (config.enterprise.getValue() && enterprise.configRules.getValue()) {
rules = new MySQLRulesHolder(this); rules = new MySQLRulesHolder(this);
dbfiles.add((MySQLRulesHolder)rules); dbfiles.add((MySQLRulesHolder) rules);
} else { } else {
rules = new YamlRulesHolder(plugin, this); rules = new YamlRulesHolder(plugin, this);
flatfiles.add((YamlRulesHolder)rules); flatfiles.add((YamlRulesHolder) rules);
} }
if(config.enterprise.getValue() && enterprise.configEvents.getValue()) { if (config.enterprise.getValue() && enterprise.configEvents.getValue()) {
levels = new MySQLLevelsHolder(this); levels = new MySQLLevelsHolder(this);
dbfiles.add((MySQLLevelsHolder)levels); dbfiles.add((MySQLLevelsHolder) levels);
} else { } else {
levels = new YamlLevelsHolder(plugin, this); levels = new YamlLevelsHolder(plugin, this);
flatfiles.add((YamlLevelsHolder)levels); flatfiles.add((YamlLevelsHolder) levels);
} }
// End // End
for(ConfigurationFile file : flatfiles) { for (ConfigurationFile file : flatfiles) {
file.save(); file.save();
checkReload(file); checkReload(file);
} }
} }
public void load() { public void load() {
for(ConfigurationFile file : flatfiles) { for (ConfigurationFile file : flatfiles) {
file.load(); file.load();
checkReload(file); checkReload(file);
} }
for(ConfigurationTable table : dbfiles) { for (ConfigurationTable table : dbfiles) {
table.load(); table.load();
} }
} }
private void checkReload(ConfigurationFile file) { private void checkReload(ConfigurationFile file) {
if(file.needsReload()) { if (file.needsReload()) {
file.reload(); file.reload();
file.setNeedsReload(false); file.setNeedsReload(false);
} }
@@ -57,7 +57,7 @@ public class ConfigurationFile {
this.rawFile = rawFile; this.rawFile = rawFile;
this.saveDefault = saveDefault; this.saveDefault = saveDefault;
if(saveDefault) { if (saveDefault) {
defaultConfigFile = YamlConfiguration.loadConfiguration(plugin.getResource(fileName)); defaultConfigFile = YamlConfiguration.loadConfiguration(plugin.getResource(fileName));
} }
load(); load();
@@ -65,11 +65,11 @@ public class ConfigurationFile {
public void load() { public void load() {
// Can change with user editing // Can change with user editing
if(!rawFile.exists()) { if (!rawFile.exists()) {
if(saveDefault) { if (saveDefault) {
plugin.saveResource(fileName, true); plugin.saveResource(fileName, true);
} else { } else {
if(!rawFile.getParentFile().exists()) { if (!rawFile.getParentFile().exists()) {
rawFile.getParentFile().mkdir(); rawFile.getParentFile().mkdir();
} }
try { try {
@@ -144,9 +144,9 @@ public class ConfigurationFile {
public ConfigValue(String path, boolean loadDefault) { public ConfigValue(String path, boolean loadDefault) {
this.path = path; this.path = path;
if(getConfigFile().contains(path)) { if (getConfigFile().contains(path)) {
value = getConfigFile().get(path); value = getConfigFile().get(path);
} else if(loadDefault) { } else if (loadDefault) {
getConfigFile().set(path, getDefaultConfigFile().get(path)); getConfigFile().set(path, getDefaultConfigFile().get(path));
value = getDefaultConfigFile().get(path); value = getDefaultConfigFile().get(path);
getConfigFile().set(path, value); getConfigFile().set(path, value);
@@ -21,6 +21,7 @@ package net.h31ix.anticheat.config.files;
import net.h31ix.anticheat.AntiCheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration; import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.config.ConfigurationFile; import net.h31ix.anticheat.config.ConfigurationFile;
import java.util.List; import java.util.List;
public class Config extends ConfigurationFile { public class Config extends ConfigurationFile {
@@ -67,16 +67,16 @@ public class Enterprise extends ConfigurationFile {
// Convert database values to Database // Convert database values to Database
database = new Database( database = new Database(
Database.DatabaseType.valueOf(databaseType.getValue()), Database.DatabaseType.valueOf(databaseType.getValue()),
databaseHostname.getValue(), databaseHostname.getValue(),
databasePort.getValue(), databasePort.getValue(),
databaseUsername.getValue(), databaseUsername.getValue(),
databasePassword.getValue(), databasePassword.getValue(),
databasePrefix.getValue(), databasePrefix.getValue(),
databaseSchema.getValue(), databaseSchema.getValue(),
serverName.getValue(), serverName.getValue(),
loggingInterval.getValue(), loggingInterval.getValue(),
loggingLife.getValue() loggingLife.getValue()
); );
database.connect(); database.connect();
@@ -24,16 +24,16 @@ 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.
* <p> * <p/>
* Note that although each value is documented, changing it may have unintended side-effects. For instance, setting something to 0 that the plugin then uses as a dividend will result in an error. <br> * Note that although each value is documented, changing it may have unintended side-effects. For instance, setting something to 0 that the plugin then uses as a dividend will result in an error. <br>
* Also realize that the smaller a value is, the less you should change it; it's probably small for a reason. The larger a value is, the safer it is to probably change it. * Also realize that the smaller a value is, the less you should change it; it's probably small for a reason. The larger a value is, the safer it is to probably change it.
* <p> * <p/>
* <b>How to read the value documentation:</b> <br> * <b>How to read the value documentation:</b> <br>
* First, you will see a description of the value. Then, you will see a type: <br> * First, you will see a description of the value. Then, you will see a type: <br>
* <b>Type SYSTEM:</b> This is a 'long' value, measured in milliseconds, used to compare past and future events with the current system time. Remember, 1000 ms = 1 second. <br> * <b>Type SYSTEM:</b> This is a 'long' value, measured in milliseconds, used to compare past and future events with the current system time. Remember, 1000 ms = 1 second. <br>
* <b>Type INTEGER:</b> This is a regular number. It's typically used as something trivial, such as how many times X event can occur. <br> * <b>Type INTEGER:</b> This is a regular number. It's typically used as something trivial, such as how many times X event can occur. <br>
* <b>Type DOUBLE:</b> This is a number that has a decimal in it. It's typically used to evaluate speed or distance. * <b>Type DOUBLE:</b> This is a number that has a decimal in it. It's typically used to evaluate speed or distance.
* <p> * <p/>
* After the type, you may see a recommendation labeled as '+Leniency'. This means 'In order to add leniency to this value, do X' <br> * After the type, you may see a recommendation labeled as '+Leniency'. This means 'In order to add leniency to this value, do X' <br>
* The suggestion for adding leniency will either be to INCREASE or DECREASE the variable. Doing what it suggests will cause the system to not judge the people being checked so vigorously. * 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.
*/ */
@@ -358,7 +358,7 @@ public class Magic extends ConfigurationFile {
public void open() { public void open() {
version = new ConfigValue<Double>("VERSION").getValue(); version = new ConfigValue<Double>("VERSION").getValue();
if(version == 0.2D) { if (version == 0.2D) {
// 0.2 -> 0.3 diffs // 0.2 -> 0.3 diffs
// Fix improperly stored double Y_MAXDIFF // Fix improperly stored double Y_MAXDIFF
new ConfigValue<Double>("Y_MAXDIFF").setValue(new ConfigValue<Double>("Y_MAXDIFF").getDefaultValue()); new ConfigValue<Double>("Y_MAXDIFF").setValue(new ConfigValue<Double>("Y_MAXDIFF").getDefaultValue());
@@ -45,7 +45,7 @@ public class MySQLEventsHolder extends ConfigurationTable implements Events {
highestLevel = 0; highestLevel = 0;
levels = new ArrayList<Level>(); levels = new ArrayList<Level>();
String sqlCreate= "CREATE TABLE IF NOT EXISTS " + getFullTable() + "(" + String sqlCreate = "CREATE TABLE IF NOT EXISTS " + getFullTable() + "(" +
" `id` INT NOT NULL," + " `id` INT NOT NULL," +
" `name` VARCHAR(45) NOT NULL," + " `name` VARCHAR(45) NOT NULL," +
" `level` INT NOT NULL," + " `level` INT NOT NULL," +
@@ -59,14 +59,14 @@ public class MySQLEventsHolder extends ConfigurationTable implements Events {
getConnection().commit(); getConnection().commit();
ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery(); ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery();
while(set.next()) { while (set.next()) {
String name = set.getString("name"); String name = set.getString("name");
int level = set.getInt("level"); int level = set.getInt("level");
String color = set.getString("color"); String color = set.getString("color");
List<String> actions = Arrays.asList(set.getString("actions").split(",")); List<String> actions = Arrays.asList(set.getString("actions").split(","));
levels.add(new Level(name, level, color, actions)); levels.add(new Level(name, level, color, actions));
if(level > highestLevel) { if (level > highestLevel) {
highestLevel = level; highestLevel = level;
} }
} }
@@ -71,11 +71,11 @@ public class MySQLLevelsHolder extends ConfigurationTable implements Levels {
@Override @Override
public void saveLevelFromUser(final User user) { public void saveLevelFromUser(final User user) {
Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable(){ Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override @Override
public void run() { public void run() {
if (!user.isWaitingOnLevelSync()) { if (!user.isWaitingOnLevelSync()) {
AntiCheat.debugLog("Syncing to "+user.getName()+" value "+user.getLevel()); AntiCheat.debugLog("Syncing to " + user.getName() + " value " + user.getLevel());
try { try {
PreparedStatement statement = getConnection().prepareStatement(sqlSave); PreparedStatement statement = getConnection().prepareStatement(sqlSave);
statement.setString(1, user.getName()); statement.setString(1, user.getName());
@@ -98,7 +98,7 @@ public class MySQLLevelsHolder extends ConfigurationTable implements Levels {
@Override @Override
public void loadLevelToUser(final User user) { public void loadLevelToUser(final User user) {
Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable(){ Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
@@ -108,13 +108,13 @@ public class MySQLLevelsHolder extends ConfigurationTable implements Levels {
ResultSet set = statement.executeQuery(); ResultSet set = statement.executeQuery();
boolean has = false; boolean has = false;
while(set.next()) { while (set.next()) {
has = true; has = true;
AntiCheat.debugLog("Syncing from "+user.getName()+" value "+set.getInt("level")); AntiCheat.debugLog("Syncing from " + user.getName() + " value " + set.getInt("level"));
user.setLevel(set.getInt("level")); user.setLevel(set.getInt("level"));
user.setLevelSyncTimestamp(set.getTimestamp("last_update")); user.setLevelSyncTimestamp(set.getTimestamp("last_update"));
} }
if(!has) user.setLevel(0); if (!has) user.setLevel(0);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -126,7 +126,7 @@ public class MySQLLevelsHolder extends ConfigurationTable implements Levels {
public void saveLevelsFromUsers(List<User> users) { public void saveLevelsFromUsers(List<User> users) {
try { try {
PreparedStatement statement = getConnection().prepareStatement(sqlSave); PreparedStatement statement = getConnection().prepareStatement(sqlSave);
for(User user : users) { for (User user : users) {
if (!user.isWaitingOnLevelSync()) { if (!user.isWaitingOnLevelSync()) {
try { try {
statement.setString(1, user.getName()); statement.setString(1, user.getName());
@@ -54,13 +54,13 @@ public class MySQLRulesHolder extends ConfigurationTable implements Rules {
this.rules = new ArrayList<Rule>(); this.rules = new ArrayList<Rule>();
ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery(); ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery();
while(set.next()) { while (set.next()) {
String string = set.getString("rule"); String string = set.getString("rule");
Rule rule = Rule.load(string); Rule rule = Rule.load(string);
if(rule != null) { if (rule != null) {
this.rules.add(rule); this.rules.add(rule);
} else { } else {
AntiCheat.getPlugin().getLogger().warning("Couldn't load rule '"+string+"' from the database. Improper format used."); AntiCheat.getPlugin().getLogger().warning("Couldn't load rule '" + string + "' from the database. Improper format used.");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
@@ -22,9 +22,7 @@ import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration; import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.config.ConfigurationFile; import net.h31ix.anticheat.config.ConfigurationFile;
import net.h31ix.anticheat.config.providers.Events; import net.h31ix.anticheat.config.providers.Events;
import net.h31ix.anticheat.config.providers.Rules;
import net.h31ix.anticheat.util.Level; import net.h31ix.anticheat.util.Level;
import net.h31ix.anticheat.util.rule.Rule;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@@ -59,9 +57,9 @@ public class YamlEventsHolder extends ConfigurationFile implements Events {
// Convert levels list to Levels // Convert levels list to Levels
this.levels = new ArrayList<Level>(); this.levels = new ArrayList<Level>();
for(String string : levels.getValue()) { for (String string : levels.getValue()) {
Level level = Level.load(string); Level level = Level.load(string);
if(level == null || level.getValue() < 0) { if (level == null || level.getValue() < 0) {
continue; continue;
} }
@@ -47,14 +47,14 @@ public class YamlLevelsHolder extends ConfigurationFile implements Levels {
@Override @Override
public void saveLevelsFromUsers(List<User> users) { public void saveLevelsFromUsers(List<User> users) {
for(User user : users) { for (User user : users) {
saveLevelFromUser(user); saveLevelFromUser(user);
} }
} }
private int getLevel(String name) { private int getLevel(String name) {
ConfigValue<Integer> level = new ConfigValue<Integer>(name, false); ConfigValue<Integer> level = new ConfigValue<Integer>(name, false);
if(level.hasValue()) { if (level.hasValue()) {
return level.getValue(); return level.getValue();
} else { } else {
return 0; return 0;
@@ -21,14 +21,10 @@ package net.h31ix.anticheat.config.holders.yaml;
import net.h31ix.anticheat.AntiCheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration; import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.config.ConfigurationFile; import net.h31ix.anticheat.config.ConfigurationFile;
import net.h31ix.anticheat.config.providers.Events;
import net.h31ix.anticheat.config.providers.Rules; import net.h31ix.anticheat.config.providers.Rules;
import net.h31ix.anticheat.util.Level;
import net.h31ix.anticheat.util.rule.Rule; import net.h31ix.anticheat.util.rule.Rule;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; import java.util.List;
public class YamlRulesHolder extends ConfigurationFile implements Rules { public class YamlRulesHolder extends ConfigurationFile implements Rules {
@@ -53,19 +49,19 @@ public class YamlRulesHolder extends ConfigurationFile implements Rules {
// Convert rules list to Rules // Convert rules list to Rules
this.rules = new ArrayList<Rule>(); this.rules = new ArrayList<Rule>();
List<String> tempRules = rules.getValue(); List<String> tempRules = rules.getValue();
for(int i=0;i<tempRules.size();i++) { for (int i = 0; i < tempRules.size(); i++) {
String string = tempRules.get(i); String string = tempRules.get(i);
if(string.equals("Check_SPIDER < 0 ? Player.KICK : null")) { 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 // Default rule, won't ever run so we shouldn't load it; only used as example
continue; continue;
} }
Rule rule = Rule.load(string); Rule rule = Rule.load(string);
if(rule != null) { if (rule != null) {
this.rules.add(rule); this.rules.add(rule);
} else { } else {
AntiCheat.getPlugin().getLogger().warning("Couldn't load rule '"+string+"' from config. Improper format used."); AntiCheat.getPlugin().getLogger().warning("Couldn't load rule '" + string + "' from config. Improper format used.");
} }
} }
} }
@@ -18,16 +18,6 @@
package net.h31ix.anticheat.config.yaml; 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.apache.commons.lang.Validate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.InvalidConfigurationException;
@@ -39,6 +29,15 @@ import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.representer.Representer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
/** /**
* An extension of {@link org.bukkit.configuration.file.YamlConfiguration} which preserves comments. * An extension of {@link org.bukkit.configuration.file.YamlConfiguration} which preserves comments.
* Note that this implementation is not synchronized. * Note that this implementation is not synchronized.
@@ -66,11 +65,11 @@ public class CommentedConfiguration extends YamlConfiguration {
} }
/** - CommentedConfiguration /** - CommentedConfiguration
String header = parseHeader(contents); String header = parseHeader(contents);
if (header.length() > 0) { if (header.length() > 0) {
options().header(header); options().header(header);
} }
**/ **/
if (input != null) { if (input != null) {
convertMapsToSections(input, this); convertMapsToSections(input, this);
@@ -80,14 +79,14 @@ public class CommentedConfiguration extends YamlConfiguration {
int i = 0; int i = 0;
int blank = 0; int blank = 0;
String[] lines = contents.split("\n"); String[] lines = contents.split("\n");
while(i < lines.length) { while (i < lines.length) {
if(lines[i].trim().equalsIgnoreCase("")) { if (lines[i].trim().equalsIgnoreCase("")) {
i++; i++;
blank++; blank++;
continue; continue;
} }
if(lines[i].contains(COMMENT_PREFIX)) { if (lines[i].contains(COMMENT_PREFIX)) {
comments.put(i-blank, lines[i]); comments.put(i - blank, lines[i]);
} }
i++; i++;
} }
@@ -112,7 +111,7 @@ public class CommentedConfiguration extends YamlConfiguration {
String[] lines = dump.split("\n"); String[] lines = dump.split("\n");
ArrayDeque<String> queue = new ArrayDeque<String>(); ArrayDeque<String> queue = new ArrayDeque<String>();
for(String string : lines) { for (String string : lines) {
queue.add(string); queue.add(string);
} }
@@ -148,7 +147,7 @@ public class CommentedConfiguration extends YamlConfiguration {
/** /**
* Creates a new {@link CommentedConfiguration}, loading from the given file. * Creates a new {@link CommentedConfiguration}, loading from the given file.
* <p> * <p/>
* Any errors loading the Configuration will be logged and then ignored. * 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. * If the specified input is not a valid config, a blank config will be returned.
* *
@@ -167,7 +166,7 @@ public class CommentedConfiguration extends YamlConfiguration {
} catch (IOException ex) { } catch (IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex);
} catch (InvalidConfigurationException ex) { } catch (InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file , ex); Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex);
} }
return config; return config;
@@ -175,7 +174,7 @@ public class CommentedConfiguration extends YamlConfiguration {
/** /**
* Creates a new {@link CommentedConfiguration}, loading from the given stream. * Creates a new {@link CommentedConfiguration}, loading from the given stream.
* <p> * <p/>
* Any errors loading the Configuration will be logged and then ignored. * 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. * If the specified input is not a valid config, a blank config will be returned.
* *
@@ -41,7 +41,7 @@ public class BlockListener extends EventListener {
} }
if (getCheckManager().willCheck(player, CheckType.AUTOTOOL)) { if (getCheckManager().willCheck(player, CheckType.AUTOTOOL)) {
CheckResult result = getBackend().checkAutoTool(player); CheckResult result = getBackend().checkAutoTool(player);
if(result.failed()) { if (result.failed()) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.AUTOTOOL); log(result.getMessage(), player, CheckType.AUTOTOOL);
} }
@@ -76,7 +76,7 @@ public class BlockListener extends EventListener {
CheckResult result; CheckResult result;
if (getCheckManager().willCheck(player, CheckType.FAST_BREAK)) { if (getCheckManager().willCheck(player, CheckType.FAST_BREAK)) {
result = getBackend().checkFastBreak(player, block); result = getBackend().checkFastBreak(player, block);
if(result.failed()) { if (result.failed()) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FAST_BREAK); log(result.getMessage(), player, CheckType.FAST_BREAK);
noHack = false; noHack = false;
@@ -84,7 +84,7 @@ public class BlockListener extends EventListener {
} }
if (getCheckManager().willCheck(player, CheckType.NO_SWING)) { if (getCheckManager().willCheck(player, CheckType.NO_SWING)) {
result = getBackend().checkSwing(player, block); result = getBackend().checkSwing(player, block);
if(result.failed()) { if (result.failed()) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.NO_SWING); log(result.getMessage(), player, CheckType.NO_SWING);
noHack = false; noHack = false;
@@ -134,7 +134,7 @@ public class EntityListener extends EventListener {
getBackend().logDamage(player, 1); getBackend().logDamage(player, 1);
if (getCheckManager().willCheck(player, CheckType.AUTOTOOL)) { if (getCheckManager().willCheck(player, CheckType.AUTOTOOL)) {
CheckResult result = getBackend().checkAutoTool(player); CheckResult result = getBackend().checkAutoTool(player);
if(result.failed()) { if (result.failed()) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.AUTOTOOL); log(result.getMessage(), player, CheckType.AUTOTOOL);
noHack = false; noHack = false;
@@ -142,7 +142,7 @@ public class EntityListener extends EventListener {
} }
if (getCheckManager().willCheck(player, CheckType.FORCEFIELD)) { if (getCheckManager().willCheck(player, CheckType.FORCEFIELD)) {
CheckResult result = getBackend().checkSprintDamage(player); CheckResult result = getBackend().checkSprintDamage(player);
if(result.failed()) { if (result.failed()) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FORCEFIELD); log(result.getMessage(), player, CheckType.FORCEFIELD);
noHack = false; noHack = false;
@@ -150,7 +150,7 @@ public class EntityListener extends EventListener {
} }
if (getCheckManager().willCheck(player, CheckType.NO_SWING)) { if (getCheckManager().willCheck(player, CheckType.NO_SWING)) {
CheckResult result = getBackend().checkAnimation(player, event.getEntity()); CheckResult result = getBackend().checkAnimation(player, event.getEntity());
if(result.failed()) { if (result.failed()) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.NO_SWING); log(result.getMessage(), player, CheckType.NO_SWING);
noHack = false; noHack = false;
@@ -158,7 +158,7 @@ public class EntityListener extends EventListener {
} }
if (getCheckManager().willCheck(player, CheckType.FORCEFIELD)) { if (getCheckManager().willCheck(player, CheckType.FORCEFIELD)) {
CheckResult result = getBackend().checkSight(player, e.getEntity()); CheckResult result = getBackend().checkSight(player, e.getEntity());
if(result.failed()) { if (result.failed()) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FORCEFIELD); log(result.getMessage(), player, CheckType.FORCEFIELD);
noHack = false; noHack = false;
@@ -18,16 +18,16 @@
package net.h31ix.anticheat.event; package net.h31ix.anticheat.event;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import net.h31ix.anticheat.AntiCheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration; import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.manage.*; import net.h31ix.anticheat.manage.*;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
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>();
@@ -39,7 +39,7 @@ public class EventListener implements Listener {
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);
@@ -75,17 +75,17 @@ public class EventListener implements Listener {
} }
private static void removeDecrease(User user) { private static void removeDecrease(User user) {
int x = 0; int x = 0;
// Ignore plugins that are creating NPCs with no names // Ignore plugins that are creating NPCs with no names
if (user.getName() != null) { if (user.getName() != null) {
if (DECREASE_LIST.get(user.getName()) != null) { if (DECREASE_LIST.get(user.getName()) != null) {
x = DECREASE_LIST.get(user.getName()); x = DECREASE_LIST.get(user.getName());
x -= 2; x -= 2;
if (x < 0) { if (x < 0) {
x = 0; x = 0;
}
} }
} DECREASE_LIST.put(user.getName(), x);
DECREASE_LIST.put(user.getName(), x);
} }
} }
@@ -55,7 +55,7 @@ public class InventoryListener extends EventListener {
@EventHandler @EventHandler
public void onInventoryOpen(InventoryOpenEvent event) { public void onInventoryOpen(InventoryOpenEvent event) {
if(event.getInventory().getType() != InventoryType.BEACON) { if (event.getInventory().getType() != InventoryType.BEACON) {
getUserManager().getUser(event.getPlayer().getName()).setInventorySnapshot(event.getInventory().getContents()); getUserManager().getUser(event.getPlayer().getName()).setInventorySnapshot(event.getInventory().getContents());
} }
} }
@@ -63,7 +63,7 @@ public class InventoryListener extends EventListener {
@EventHandler @EventHandler
public void onInventoryClose(InventoryCloseEvent event) { public void onInventoryClose(InventoryCloseEvent event) {
User user = getUserManager().getUser(event.getPlayer().getName()); User user = getUserManager().getUser(event.getPlayer().getName());
if(user != null) { if (user != null) {
user.removeInventorySnapshot(); user.removeInventorySnapshot();
} }
} }
@@ -81,11 +81,13 @@ public class PlayerListener extends EventListener {
if (event.getEntity().getShooter() instanceof Player) { if (event.getEntity().getShooter() instanceof Player) {
Player player = (Player) event.getEntity().getShooter(); Player player = (Player) event.getEntity().getShooter();
if (event.getEntity() instanceof Arrow) { return; } if (event.getEntity() instanceof Arrow) {
return;
}
if (getCheckManager().willCheck(player, CheckType.FAST_PROJECTILE)) { if (getCheckManager().willCheck(player, CheckType.FAST_PROJECTILE)) {
CheckResult result = getBackend().checkProjectile(player); CheckResult result = getBackend().checkProjectile(player);
if(result.failed()) { if (result.failed()) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FAST_PROJECTILE); log(result.getMessage(), player, CheckType.FAST_PROJECTILE);
} }
@@ -123,8 +125,7 @@ public class PlayerListener extends EventListener {
@EventHandler @EventHandler
public void onPlayerVelocity(PlayerVelocityEvent event) { public void onPlayerVelocity(PlayerVelocityEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if (getCheckManager().willCheck(player, CheckType.FLY)) if (getCheckManager().willCheck(player, CheckType.FLY)) {
{
if (getBackend().justVelocity(player) && getBackend().extendVelocityTime(player)) { if (getBackend().justVelocity(player) && getBackend().extendVelocityTime(player)) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
return; // don't log it lol. return; // don't log it lol.
@@ -143,7 +144,7 @@ public class PlayerListener extends EventListener {
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());
if(!result.getMessage().equals("")) { if (!result.getMessage().equals("")) {
player.sendMessage(ChatColor.RED + result.getMessage()); player.sendMessage(ChatColor.RED + result.getMessage());
} }
getBackend().processChatSpammer(player); getBackend().processChatSpammer(player);
@@ -176,7 +177,7 @@ public class PlayerListener extends EventListener {
@EventHandler @EventHandler
public void onPlayerToggleSprint(PlayerToggleSprintEvent event) { public void onPlayerToggleSprint(PlayerToggleSprintEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if(!event.isSprinting()) { if (!event.isSprinting()) {
getBackend().logEnterExit(player); getBackend().logEnterExit(player);
} }
if (getCheckManager().willCheck(player, CheckType.SPRINT)) { if (getCheckManager().willCheck(player, CheckType.SPRINT)) {
@@ -219,7 +220,7 @@ public class PlayerListener extends EventListener {
Player player = event.getPlayer(); Player player = event.getPlayer();
if (getCheckManager().willCheck(player, CheckType.ITEM_SPAM)) { if (getCheckManager().willCheck(player, CheckType.ITEM_SPAM)) {
CheckResult result = getBackend().checkFastDrop(player); CheckResult result = getBackend().checkFastDrop(player);
if(result.failed()) { if (result.failed()) {
event.setCancelled(!silentMode()); event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.ITEM_SPAM); log(result.getMessage(), player, CheckType.ITEM_SPAM);
} }
@@ -285,7 +286,7 @@ public class PlayerListener extends EventListener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerMove(PlayerMoveEvent event) { public void onPlayerMove(PlayerMoveEvent event) {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
if(getCheckManager().checkInWorld(player) && !getCheckManager().isOpExempt(player)) { if (getCheckManager().checkInWorld(player) && !getCheckManager().isOpExempt(player)) {
final Location from = event.getFrom(); final Location from = event.getFrom();
final Location to = event.getTo(); final Location to = event.getTo();
@@ -298,9 +299,9 @@ public class PlayerListener extends EventListener {
if (getCheckManager().willCheckQuick(player, CheckType.SPEED)) { if (getCheckManager().willCheckQuick(player, CheckType.SPEED)) {
CheckResult result = getBackend().checkFreeze(player, from.getY(), to.getY()); CheckResult result = getBackend().checkFreeze(player, from.getY(), to.getY());
if(result.failed()) { if (result.failed()) {
log(result.getMessage(), player, CheckType.SPEED); log(result.getMessage(), player, CheckType.SPEED);
if(!silentMode()) { if (!silentMode()) {
player.kickPlayer("Freezing client"); player.kickPlayer("Freezing client");
} }
} }
@@ -314,7 +315,7 @@ public class PlayerListener extends EventListener {
} }
if (getCheckManager().willCheckQuick(player, CheckType.FLY) && !player.isFlying()) { if (getCheckManager().willCheckQuick(player, CheckType.FLY) && !player.isFlying()) {
CheckResult result = getBackend().checkFlight(player, distance); CheckResult result = getBackend().checkFlight(player, distance);
if(result.failed()) { if (result.failed()) {
if (!silentMode()) { if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone())); event.setTo(user.getGoodLocation(from.clone()));
} }
@@ -339,7 +340,7 @@ public class PlayerListener extends EventListener {
} }
if (getCheckManager().willCheckQuick(player, CheckType.NOFALL) && getCheckManager().willCheck(player, CheckType.FLY) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && event.getFrom().getY() > event.getTo().getY()) { if (getCheckManager().willCheckQuick(player, CheckType.NOFALL) && getCheckManager().willCheck(player, CheckType.FLY) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && event.getFrom().getY() > event.getTo().getY()) {
CheckResult result = getBackend().checkNoFall(player, y); CheckResult result = getBackend().checkNoFall(player, y);
if(result.failed()) { if (result.failed()) {
if (!silentMode()) { if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone())); event.setTo(user.getGoodLocation(from.clone()));
player.damage(1); // I added this in here so the player would still receive damage. player.damage(1); // I added this in here so the player would still receive damage.
@@ -355,7 +356,7 @@ public class PlayerListener extends EventListener {
if (getCheckManager().willCheckQuick(player, CheckType.SPEED) && getCheckManager().willCheck(player, CheckType.FLY)) { if (getCheckManager().willCheckQuick(player, CheckType.SPEED) && getCheckManager().willCheck(player, CheckType.FLY)) {
if (event.getFrom().getY() < event.getTo().getY()) { if (event.getFrom().getY() < event.getTo().getY()) {
CheckResult result = getBackend().checkYSpeed(player, y); CheckResult result = getBackend().checkYSpeed(player, y);
if(result.failed()) { if (result.failed()) {
if (!silentMode()) { if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone())); event.setTo(user.getGoodLocation(from.clone()));
} }
@@ -385,7 +386,7 @@ public class PlayerListener extends EventListener {
} }
if (getCheckManager().willCheckQuick(player, CheckType.WATER_WALK)) { if (getCheckManager().willCheckQuick(player, CheckType.WATER_WALK)) {
CheckResult result = getBackend().checkWaterWalk(player, x, y, z); CheckResult result = getBackend().checkWaterWalk(player, x, y, z);
if(result.failed()) { if (result.failed()) {
if (!silentMode()) { if (!silentMode()) {
player.teleport(user.getGoodLocation(player.getLocation().add(0, -1, 0))); player.teleport(user.getGoodLocation(player.getLocation().add(0, -1, 0)));
} }
@@ -395,7 +396,7 @@ public class PlayerListener extends EventListener {
} }
if (getCheckManager().willCheckQuick(player, CheckType.SNEAK)) { if (getCheckManager().willCheckQuick(player, CheckType.SNEAK)) {
CheckResult result = getBackend().checkSneak(player, x, z); CheckResult result = getBackend().checkSneak(player, x, z);
if(result.failed()) { if (result.failed()) {
if (!silentMode()) { if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone())); event.setTo(user.getGoodLocation(from.clone()));
player.setSneaking(false); player.setSneaking(false);
@@ -406,7 +407,7 @@ public class PlayerListener extends EventListener {
} }
if (getCheckManager().willCheckQuick(player, CheckType.SPIDER)) { if (getCheckManager().willCheckQuick(player, CheckType.SPIDER)) {
CheckResult result = getBackend().checkSpider(player, y); CheckResult result = getBackend().checkSpider(player, y);
if(result.failed()) { if (result.failed()) {
if (!silentMode()) { if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone())); event.setTo(user.getGoodLocation(from.clone()));
} }
@@ -430,7 +431,7 @@ public class PlayerListener extends EventListener {
final Location from = event.getFrom(); final Location from = event.getFrom();
final Location to = event.getTo(); final Location to = event.getTo();
if(!user.checkTo(to.getX(), to.getY(), to.getZ())) { if (!user.checkTo(to.getX(), to.getY(), to.getZ())) {
// The to value has been modified by another plugin // The to value has been modified by another plugin
return; return;
} }
@@ -439,7 +440,7 @@ public class PlayerListener extends EventListener {
CheckResult result1 = getBackend().checkYAxis(player, new Distance(from, to)); CheckResult result1 = getBackend().checkYAxis(player, new Distance(from, to));
CheckResult result2 = getBackend().checkAscension(player, from.getY(), to.getY()); CheckResult result2 = getBackend().checkAscension(player, from.getY(), to.getY());
String log = result1.failed() ? result1.getMessage() : result2.failed() ? result2.getMessage() : ""; String log = result1.failed() ? result1.getMessage() : result2.failed() ? result2.getMessage() : "";
if(!log.equals("")) { if (!log.equals("")) {
if (!silentMode()) { if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone())); event.setTo(user.getGoodLocation(from.clone()));
} }
@@ -48,7 +48,7 @@ public class VehicleListener extends EventListener {
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onVehicleDestroy(VehicleDestroyEvent event) { public void onVehicleDestroy(VehicleDestroyEvent event) {
if (event.getVehicle().getPassenger() != null && event.getVehicle().getPassenger() instanceof Player) { if (event.getVehicle().getPassenger() != null && event.getVehicle().getPassenger() instanceof Player) {
getBackend().logEnterExit((Player) event.getVehicle().getPassenger()); getBackend().logEnterExit((Player) event.getVehicle().getPassenger());
} }
@@ -18,6 +18,14 @@
package net.h31ix.anticheat.manage; package net.h31ix.anticheat.manage;
import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.util.FileFormatter;
import net.h31ix.anticheat.xray.XRayTracker;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.RegisteredListener;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -29,14 +37,6 @@ 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.config.Configuration;
import net.h31ix.anticheat.util.FileFormatter;
import net.h31ix.anticheat.xray.XRayTracker;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.RegisteredListener;
/** /**
* The internal hub for all managers. * The internal hub for all managers.
*/ */
@@ -101,7 +101,9 @@ public class AnticheatManager {
public List<String> getLastLogs() { public List<String> getLastLogs() {
List<String> log = new CopyOnWriteArrayList<String>(); List<String> log = new CopyOnWriteArrayList<String>();
if (logs.size() < 30) { return logs; } if (logs.size() < 30) {
return logs;
}
for (int i = logs.size() - 1; i >= 0; i--) { for (int i = logs.size() - 1; i >= 0; i--) {
log.add(logs.get(i)); log.add(logs.get(i));
} }
@@ -124,7 +126,7 @@ public class AnticheatManager {
return "Event Chains is disabled by the configuration." + '\n'; return "Event Chains is disabled by the configuration." + '\n';
} }
if(eventchains.entrySet().size() == 0) { if (eventchains.entrySet().size() == 0) {
return "No event chains found." + '\n'; return "No event chains found." + '\n';
} }
@@ -135,7 +137,7 @@ public class AnticheatManager {
toadd += ename + ":" + '\n'; toadd += ename + ":" + '\n';
RegisteredListener[] reg = e.getValue(); RegisteredListener[] reg = e.getValue();
for(RegisteredListener plug : reg) { for (RegisteredListener plug : reg) {
String pluginname = plug.getPlugin().getName(); String pluginname = plug.getPlugin().getName();
if (pluginname.equals("AntiCheat")) if (pluginname.equals("AntiCheat"))
pluginname = "self"; pluginname = "self";
@@ -176,7 +178,7 @@ public class AnticheatManager {
public static void close() { public static void close() {
fileHandler.close(); fileHandler.close();
if(configuration.getConfig().enterprise.getValue()) { if (configuration.getConfig().enterprise.getValue()) {
configuration.getEnterprise().database.shutdown(); configuration.getEnterprise().database.shutdown();
} }
} }
@@ -18,18 +18,12 @@
package net.h31ix.anticheat.manage; package net.h31ix.anticheat.manage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
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.config.files.Lang;
import net.h31ix.anticheat.config.files.Magic;
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.config.files.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;
@@ -39,11 +33,12 @@ import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerToggleSprintEvent; import org.bukkit.event.player.PlayerToggleSprintEvent;
import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionEffectType;
import java.util.*;
public class Backend { public class Backend {
private List<String> isInWater = new ArrayList<String>(); private List<String> isInWater = new ArrayList<String>();
private List<String> isInWaterCache = new ArrayList<String>(); private List<String> isInWaterCache = new ArrayList<String>();
@@ -183,8 +178,8 @@ public class Backend {
float f = (float) ticks / 20.0F; float f = (float) ticks / 20.0F;
f = (f * f + f * 2.0F) / 3.0F; f = (f * f + f * 2.0F) / 3.0F;
f = f > 1.0F ? 1.0F : f; f = f > 1.0F ? 1.0F : f;
if(Math.abs(force - f) > magic.BOW_ERROR) { if (Math.abs(force - f) > magic.BOW_ERROR) {
return new CheckResult(Result.FAILED, player.getName()+" fired their bow too fast (actual force="+force+", calculated force="+f+")"); return new CheckResult(Result.FAILED, player.getName() + " fired their bow too fast (actual force=" + force + ", calculated force=" + f + ")");
} else { } else {
return PASS; return PASS;
} }
@@ -199,8 +194,8 @@ public class Backend {
long time = System.currentTimeMillis() - projectileTime.get(player.getName()); long time = System.currentTimeMillis() - projectileTime.get(player.getName());
projectileTime.remove(player.getName()); projectileTime.remove(player.getName());
projectilesShot.remove(player.getName()); projectilesShot.remove(player.getName());
if(time < magic.PROJECTILE_TIME_MIN) { if (time < magic.PROJECTILE_TIME_MIN) {
return new CheckResult(Result.FAILED, player.getName()+" wound up a bow too fast (actual time="+time+", min time="+magic.PROJECTILE_TIME_MIN+")"); return new CheckResult(Result.FAILED, player.getName() + " wound up a bow too fast (actual time=" + time + ", min time=" + magic.PROJECTILE_TIME_MIN + ")");
} }
} }
return PASS; return PASS;
@@ -215,8 +210,8 @@ public class Backend {
long time = System.currentTimeMillis() - blockTime.get(player.getName()); long time = System.currentTimeMillis() - blockTime.get(player.getName());
blockTime.remove(player.getName()); blockTime.remove(player.getName());
blocksDropped.remove(player.getName()); blocksDropped.remove(player.getName());
if(time < magic.DROP_TIME_MIN) { if (time < magic.DROP_TIME_MIN) {
return new CheckResult(Result.FAILED, player.getName()+" dropped an item too fast (actual time="+time+", min time="+magic.DROP_TIME_MIN+")"); return new CheckResult(Result.FAILED, player.getName() + " dropped an item too fast (actual time=" + time + ", min time=" + magic.DROP_TIME_MIN + ")");
} }
} }
return PASS; return PASS;
@@ -226,14 +221,14 @@ public class Backend {
if (isInstantBreakExempt(player)) { if (isInstantBreakExempt(player)) {
return new CheckResult(Result.PASSED); return new CheckResult(Result.PASSED);
} else { } else {
String string = player.getName()+" reached too far for a block"; String string = player.getName() + " reached too far for a block";
double distance = double distance =
player.getGameMode() == GameMode.CREATIVE ? magic.BLOCK_MAX_DISTANCE_CREATIVE player.getGameMode() == GameMode.CREATIVE ? magic.BLOCK_MAX_DISTANCE_CREATIVE
: player.getLocation().getDirection().getY() > 0.9 ? magic.BLOCK_MAX_DISTANCE_CREATIVE : player.getLocation().getDirection().getY() > 0.9 ? magic.BLOCK_MAX_DISTANCE_CREATIVE
: magic.BLOCK_MAX_DISTANCE; : magic.BLOCK_MAX_DISTANCE;
double i = x >= distance ? x : y > distance ? y : z > distance ? z : -1; double i = x >= distance ? x : y > distance ? y : z > distance ? z : -1;
if(i != -1) { if (i != -1) {
return new CheckResult(Result.FAILED, string+" (distance="+i+", max="+magic.BLOCK_MAX_DISTANCE+")"); return new CheckResult(Result.FAILED, string + " (distance=" + i + ", max=" + magic.BLOCK_MAX_DISTANCE + ")");
} else { } else {
return PASS; return PASS;
} }
@@ -241,26 +236,26 @@ public class Backend {
} }
public CheckResult checkLongReachDamage(Player player, double x, double y, double z) { public CheckResult checkLongReachDamage(Player player, double x, double y, double z) {
String string = player.getName()+" reached too far for an entity"; String string = player.getName() + " reached too far for an entity";
double i = x >= magic.ENTITY_MAX_DISTANCE ? x : y > magic.ENTITY_MAX_DISTANCE ? y : z > magic.ENTITY_MAX_DISTANCE ? z : -1; double i = x >= magic.ENTITY_MAX_DISTANCE ? x : y > magic.ENTITY_MAX_DISTANCE ? y : z > magic.ENTITY_MAX_DISTANCE ? z : -1;
if(i != -1) { if (i != -1) {
return new CheckResult(Result.FAILED, string+" (distance="+i+", max="+magic.ENTITY_MAX_DISTANCE+")"); return new CheckResult(Result.FAILED, string + " (distance=" + i + ", max=" + magic.ENTITY_MAX_DISTANCE + ")");
} else { } else {
return PASS; return PASS;
} }
} }
public CheckResult checkSpider(Player player, double y) { public CheckResult checkSpider(Player player, double y) {
if(y <= magic.LADDER_Y_MAX && y >= magic.LADDER_Y_MIN && !Utilities.isClimbableBlock(player.getLocation().getBlock())) { if (y <= magic.LADDER_Y_MAX && y >= magic.LADDER_Y_MIN && !Utilities.isClimbableBlock(player.getLocation().getBlock())) {
return new CheckResult(Result.FAILED, player.getName()+" tried to climb a non-ladder ("+player.getLocation().getBlock().getType()+")"); return new CheckResult(Result.FAILED, player.getName() + " tried to climb a non-ladder (" + player.getLocation().getBlock().getType() + ")");
} else { } else {
return PASS; return PASS;
} }
} }
public CheckResult checkYSpeed(Player player, double y) { public CheckResult checkYSpeed(Player player, double y) {
if(!isMovingExempt(player) && !player.isInsideVehicle() && !player.isSleeping() && y > magic.Y_SPEED_MAX && !isDoing(player, velocitized, magic.VELOCITY_TIME) && !player.hasPotionEffect(PotionEffectType.JUMP)) { if (!isMovingExempt(player) && !player.isInsideVehicle() && !player.isSleeping() && y > magic.Y_SPEED_MAX && !isDoing(player, velocitized, magic.VELOCITY_TIME) && !player.hasPotionEffect(PotionEffectType.JUMP)) {
return new CheckResult(Result.FAILED, player.getName()+"'s y speed was too high (speed="+y+", max="+magic.Y_SPEED_MAX+")"); return new CheckResult(Result.FAILED, player.getName() + "'s y speed was too high (speed=" + y + ", max=" + magic.Y_SPEED_MAX + ")");
} else { } else {
return PASS; return PASS;
} }
@@ -279,7 +274,7 @@ public class Backend {
int i = nofallViolation.get(name); int i = nofallViolation.get(name);
if (i >= magic.NOFALL_LIMIT) { if (i >= magic.NOFALL_LIMIT) {
nofallViolation.put(player.getName(), 1); nofallViolation.put(player.getName(), 1);
return new CheckResult(Result.FAILED, player.getName()+" tried to avoid fall damage (fall distance = 0 "+i+" times in a row, max="+magic.NOFALL_LIMIT+")"); return new CheckResult(Result.FAILED, player.getName() + " tried to avoid fall damage (fall distance = 0 " + i + " times in a row, max=" + magic.NOFALL_LIMIT + ")");
} else { } else {
return PASS; return PASS;
} }
@@ -300,8 +295,8 @@ public class Backend {
reason = "on soulsand while sprinting "; reason = "on soulsand while sprinting ";
max = magic.XZ_SPEED_MAX_SOULSAND_SPRINT; max = magic.XZ_SPEED_MAX_SOULSAND_SPRINT;
} else if (player.hasPotionEffect(PotionEffectType.SPEED)) { } else if (player.hasPotionEffect(PotionEffectType.SPEED)) {
reason = "on soulsand with speed potion "; reason = "on soulsand with speed potion ";
max = magic.XZ_SPEED_MAX_SOULSAND_POTION; max = magic.XZ_SPEED_MAX_SOULSAND_POTION;
} else { } else {
reason = "on soulsand "; reason = "on soulsand ";
max = magic.XZ_SPEED_MAX_SOULSAND; max = magic.XZ_SPEED_MAX_SOULSAND;
@@ -322,8 +317,8 @@ public class Backend {
if (x > max || z > max) { if (x > max || z > max) {
int num = this.increment(player, speedViolation, magic.SPEED_MAX); int num = this.increment(player, speedViolation, magic.SPEED_MAX);
if(num >= magic.SPEED_MAX) { if (num >= magic.SPEED_MAX) {
return new CheckResult(Result.FAILED, player.getName()+"'s speed was too high "+reason+num+" times in a row (max="+magic.SPEED_MAX+", speed="+(x > z ? x : z)+", max speed="+max+")"); return new CheckResult(Result.FAILED, player.getName() + "'s speed was too high " + reason + num + " times in a row (max=" + magic.SPEED_MAX + ", speed=" + (x > z ? x : z) + ", max speed=" + max + ")");
} else { } else {
return PASS; return PASS;
} }
@@ -339,8 +334,8 @@ public class Backend {
public CheckResult checkSneak(Player player, double x, double z) { public CheckResult checkSneak(Player player, double x, double z) {
if (player.isSneaking() && !player.isFlying() && !isMovingExempt(player) && !player.isInsideVehicle()) { if (player.isSneaking() && !player.isFlying() && !isMovingExempt(player) && !player.isInsideVehicle()) {
double i = x > magic.XZ_SPEED_MAX_SNEAK ? x : z > magic.XZ_SPEED_MAX_SNEAK ? z : -1; double i = x > magic.XZ_SPEED_MAX_SNEAK ? x : z > magic.XZ_SPEED_MAX_SNEAK ? z : -1;
if(i != -1) { if (i != -1) {
return new CheckResult(Result.FAILED, player.getName()+" was sneaking too fast (speed="+i+", max="+magic.XZ_SPEED_MAX_SNEAK+")"); return new CheckResult(Result.FAILED, player.getName() + " was sneaking too fast (speed=" + i + ", max=" + magic.XZ_SPEED_MAX_SNEAK + ")");
} else { } else {
return PASS; return PASS;
} }
@@ -352,7 +347,7 @@ public class Backend {
public CheckResult checkSprintHungry(PlayerToggleSprintEvent event) { public CheckResult checkSprintHungry(PlayerToggleSprintEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if (event.isSprinting() && player.getGameMode() != GameMode.CREATIVE && player.getFoodLevel() <= magic.SPRINT_FOOD_MIN) { if (event.isSprinting() && player.getGameMode() != GameMode.CREATIVE && player.getFoodLevel() <= magic.SPRINT_FOOD_MIN) {
return new CheckResult(Result.FAILED, player.getName()+" sprinted while hungry (food="+player.getFoodLevel()+", min="+magic.SPRINT_FOOD_MIN+")"); return new CheckResult(Result.FAILED, player.getName() + " sprinted while hungry (food=" + player.getFoodLevel() + ", min=" + magic.SPRINT_FOOD_MIN + ")");
} else { } else {
return PASS; return PASS;
} }
@@ -378,7 +373,8 @@ public class Backend {
b = x > magic.XZ_SPEED_MAX_WATER || z > magic.XZ_SPEED_MAX_WATER; b = x > magic.XZ_SPEED_MAX_WATER || z > magic.XZ_SPEED_MAX_WATER;
} else { } else {
b = x > magic.XZ_SPEED_MAX_WATER_SPRINT || z > magic.XZ_SPEED_MAX_WATER_SPRINT; b = x > magic.XZ_SPEED_MAX_WATER_SPRINT || z > magic.XZ_SPEED_MAX_WATER_SPRINT;
} if (!b && !Utilities.isFullyInWater(player.getLocation()) && Utilities.isHoveringOverWater(player.getLocation(), 1) && y == 0D && !block.getType().equals(Material.WATER_LILY)) { }
if (!b && !Utilities.isFullyInWater(player.getLocation()) && Utilities.isHoveringOverWater(player.getLocation(), 1) && y == 0D && !block.getType().equals(Material.WATER_LILY)) {
b = true; b = true;
} }
if (b) { if (b) {
@@ -386,7 +382,7 @@ public class Backend {
int v = waterSpeedViolation.get(player.getName()); int v = waterSpeedViolation.get(player.getName());
if (v >= magic.WATER_SPEED_VIOLATION_MAX) { if (v >= magic.WATER_SPEED_VIOLATION_MAX) {
waterSpeedViolation.put(player.getName(), 0); waterSpeedViolation.put(player.getName(), 0);
return new CheckResult(Result.FAILED, player.getName()+" stood on water "+v+" times (can't stand on "+block.getType()+" or "+block.getRelative(BlockFace.DOWN).getType()+")"); return new CheckResult(Result.FAILED, player.getName() + " stood on water " + v + " times (can't stand on " + block.getType() + " or " + block.getRelative(BlockFace.DOWN).getType() + ")");
} else { } else {
waterSpeedViolation.put(player.getName(), v + 1); waterSpeedViolation.put(player.getName(), v + 1);
} }
@@ -411,7 +407,7 @@ public class Backend {
} else { } else {
waterAscensionViolation.put(player.getName(), v + 1); waterAscensionViolation.put(player.getName(), v + 1);
} }
return new CheckResult(Result.FAILED, player.getName()+" stood on water "+v+" times (can't stand on "+block.getType()+" or "+block.getRelative(BlockFace.DOWN).getType()+")"); return new CheckResult(Result.FAILED, player.getName() + " stood on water " + v + " times (can't stand on " + block.getType() + " or " + block.getRelative(BlockFace.DOWN).getType() + ")");
} else { } else {
waterAscensionViolation.put(player.getName(), 1); waterAscensionViolation.put(player.getName(), 1);
} }
@@ -434,7 +430,7 @@ public class Backend {
for (int i = 0; i < (Math.round(distance.getYDifference())) + 1; i++) { for (int i = 0; i < (Math.round(distance.getYDifference())) + 1; i++) {
Block block = new Location(player.getWorld(), player.getLocation().getX(), to + i, player.getLocation().getZ()).getBlock(); Block block = new Location(player.getWorld(), player.getLocation().getX(), to + i, player.getLocation().getZ()).getBlock();
if (block.getTypeId() != 0 && block.getType().isSolid()) { if (block.getTypeId() != 0 && block.getType().isSolid()) {
return new CheckResult(Result.FAILED, player.getName()+" tried to move through a solid block", (int)from + 3); return new CheckResult(Result.FAILED, player.getName() + " tried to move through a solid block", (int) from + 3);
} }
} }
@@ -466,7 +462,7 @@ public class Backend {
player.teleport(g); player.teleport(g);
} }
} }
return new CheckResult(Result.FAILED, player.getName()+" tried to fly on y-axis "+yAxisViolations.get(name)+" times (max ="+magic.Y_MAXVIOLATIONS+")"); return new CheckResult(Result.FAILED, player.getName() + " tried to fly on y-axis " + yAxisViolations.get(name) + " times (max =" + magic.Y_MAXVIOLATIONS + ")");
} else { } else {
if (yAxisViolations.get(name) > magic.Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) > magic.Y_MAXVIOTIME) { if (yAxisViolations.get(name) > magic.Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) > magic.Y_MAXVIOTIME) {
yAxisViolations.put(name, 0); yAxisViolations.put(name, 0);
@@ -485,7 +481,7 @@ public class Backend {
player.teleport(g); player.teleport(g);
} }
} }
return new CheckResult(Result.FAILED, player.getName()+" tried to fly on y-axis in "+i+" ms (min ="+magic.Y_TIME+")"); return new CheckResult(Result.FAILED, player.getName() + " tried to fly on y-axis in " + i + " ms (min =" + magic.Y_TIME + ")");
} else { } else {
if ((y1 - lastYcoord.get(name)) > magic.Y_MAXDIFF + 1 || (System.currentTimeMillis() - lastYtime.get(name)) > magic.Y_TIME) { if ((y1 - lastYcoord.get(name)) > magic.Y_MAXDIFF + 1 || (System.currentTimeMillis() - lastYtime.get(name)) > magic.Y_TIME) {
lastYtime.put(name, System.currentTimeMillis()); lastYtime.put(name, System.currentTimeMillis());
@@ -511,8 +507,8 @@ public class Backend {
if (step == magic.TIMER_STEP_CHECK) { if (step == magic.TIMER_STEP_CHECK) {
long time = System.currentTimeMillis() - stepTime.get(name); long time = System.currentTimeMillis() - stepTime.get(name);
steps.put(name, 0); steps.put(name, 0);
if(time < magic.TIMER_TIMEMIN) { if (time < magic.TIMER_TIMEMIN) {
return new CheckResult(Result.FAILED, player.getName()+" tried to alter their timer, took "+step+" steps in "+time+" ms (min = "+magic.TIMER_TIMEMIN+" ms)"); return new CheckResult(Result.FAILED, player.getName() + " tried to alter their timer, took " + step + " steps in " + time + " ms (min = " + magic.TIMER_TIMEMIN + " ms)");
} }
} }
return PASS; return PASS;
@@ -562,7 +558,7 @@ public class Backend {
final String name = player.getName(); final String name = player.getName();
final double y1 = distance.fromY(); final double y1 = distance.fromY();
final double y2 = distance.toY(); final double y2 = distance.toY();
if (!isMovingExempt(player) && !Utilities.isHoveringOverWater(player.getLocation(), 1) && Utilities.cantStandAtExp(player.getLocation()) && Utilities.blockIsnt(player.getLocation().getBlock().getRelative(BlockFace.DOWN), new Material [] {Material.FENCE, Material.FENCE_GATE, Material.COBBLE_WALL})) { if (!isMovingExempt(player) && !Utilities.isHoveringOverWater(player.getLocation(), 1) && Utilities.cantStandAtExp(player.getLocation()) && Utilities.blockIsnt(player.getLocation().getBlock().getRelative(BlockFace.DOWN), new Material[]{Material.FENCE, Material.FENCE_GATE, Material.COBBLE_WALL})) {
if (!blocksOverFlight.containsKey(name)) { if (!blocksOverFlight.containsKey(name)) {
blocksOverFlight.put(name, 0D); blocksOverFlight.put(name, 0D);
@@ -575,7 +571,7 @@ public class Backend {
} }
if (blocksOverFlight.get(name) > magic.FLIGHT_BLOCK_LIMIT && (y1 <= y2)) { if (blocksOverFlight.get(name) > magic.FLIGHT_BLOCK_LIMIT && (y1 <= y2)) {
return new CheckResult(Result.FAILED, player.getName()+" flew over "+blocksOverFlight.get(name)+" blocks (max="+magic.FLIGHT_BLOCK_LIMIT+")"); return new CheckResult(Result.FAILED, player.getName() + " flew over " + blocksOverFlight.get(name) + " blocks (max=" + magic.FLIGHT_BLOCK_LIMIT + ")");
} }
} else { } else {
blocksOverFlight.put(name, 0D); blocksOverFlight.put(name, 0D);
@@ -607,7 +603,7 @@ public class Backend {
if (!block.getRelative(BlockFace.NORTH).isLiquid() && !block.getRelative(BlockFace.SOUTH).isLiquid() && !block.getRelative(BlockFace.EAST).isLiquid() && !block.getRelative(BlockFace.WEST).isLiquid()) { if (!block.getRelative(BlockFace.NORTH).isLiquid() && !block.getRelative(BlockFace.SOUTH).isLiquid() && !block.getRelative(BlockFace.EAST).isLiquid() && !block.getRelative(BlockFace.WEST).isLiquid()) {
increment(player, ascensionCount, max); increment(player, ascensionCount, max);
if (ascensionCount.get(name) >= max) { if (ascensionCount.get(name) >= max) {
return new CheckResult(Result.FAILED, player.getName()+" ascended "+ascensionCount.get(name)+" times in a row (max = "+max+string+")"); return new CheckResult(Result.FAILED, player.getName() + " ascended " + ascensionCount.get(name) + " times in a row (max = " + max + string + ")");
} }
} }
} else { } else {
@@ -624,7 +620,7 @@ public class Backend {
if (blockPunches.get(name) != null && player.getGameMode() != GameMode.CREATIVE) { if (blockPunches.get(name) != null && player.getGameMode() != GameMode.CREATIVE) {
int i = blockPunches.get(name); int i = blockPunches.get(name);
if (i < magic.BLOCK_PUNCH_MIN) { if (i < magic.BLOCK_PUNCH_MIN) {
return new CheckResult(Result.FAILED, player.getName()+" tried to break a block of "+block.getType()+" after only "+i+" punches (min="+magic.BLOCK_PUNCH_MIN+")"); return new CheckResult(Result.FAILED, player.getName() + " tried to break a block of " + block.getType() + " after only " + i + " punches (min=" + magic.BLOCK_PUNCH_MIN + ")");
} else { } else {
blockPunches.put(name, 0); // it should reset after EACH block break. blockPunches.put(name, 0); // it should reset after EACH block break.
} }
@@ -652,7 +648,7 @@ public class Backend {
if (!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 + ")");
} else if (fastBreakViolation.get(name) > 0 && math > magic.FASTBREAK_MAXVIOLATIONTIME) { } else if (fastBreakViolation.get(name) > 0 && math > magic.FASTBREAK_MAXVIOLATIONTIME) {
fastBreakViolation.put(name, 0); fastBreakViolation.put(name, 0);
} }
@@ -666,7 +662,7 @@ public class Backend {
} }
} else { } else {
Long math = System.currentTimeMillis() - lastBlockBroken.get(name); Long math = System.currentTimeMillis() - lastBlockBroken.get(name);
if((math != 0L && timemax != 0L)) { if ((math != 0L && timemax != 0L)) {
if (math < timemax) { if (math < timemax) {
if (fastBreakViolation.containsKey(name) && fastBreakViolation.get(name) > 0) { if (fastBreakViolation.containsKey(name) && fastBreakViolation.get(name) > 0) {
fastBreakViolation.put(name, fastBreakViolation.get(name) + 1); fastBreakViolation.put(name, fastBreakViolation.get(name) + 1);
@@ -679,7 +675,7 @@ public class Backend {
int i = fastBreaks.get(name); int i = fastBreaks.get(name);
fastBreaks.put(name, 0); fastBreaks.put(name, 0);
fastBreakViolation.put(name, fastBreakViolation.get(name) + 1); fastBreakViolation.put(name, fastBreakViolation.get(name) + 1);
return new CheckResult(Result.FAILED, player.getName()+" tried to break "+i+" blocks in "+math+" ms (max="+magic.FASTBREAK_LIMIT+" in "+timemax+" ms)"); return new CheckResult(Result.FAILED, player.getName() + " tried to break " + i + " blocks in " + math + " ms (max=" + magic.FASTBREAK_LIMIT + " in " + timemax + " ms)");
} else if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT || fastBreakViolation.get(name) > 0) { } else if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT || fastBreakViolation.get(name) > 0) {
if (!blockBreakHolder.containsKey(name) || !blockBreakHolder.get(name)) { if (!blockBreakHolder.containsKey(name) || !blockBreakHolder.get(name)) {
blockBreakHolder.put(name, true); blockBreakHolder.put(name, true);
@@ -716,7 +712,7 @@ public class Backend {
if (!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);
@@ -730,7 +726,7 @@ public class Backend {
lastBlockPlaceTime.put(name, (time - last)); lastBlockPlaceTime.put(name, (time - last));
lastBlockPlaced.put(name, time); lastBlockPlaced.put(name, time);
fastPlaceViolation.put(name, fastPlaceViolation.get(name) + 1); fastPlaceViolation.put(name, fastPlaceViolation.get(name) + 1);
return new CheckResult(Result.FAILED, player.getName()+" tried to place a block "+thisTime+" ms after the last one (min="+magic.FASTPLACE_TIMEMIN+" ms)"); return new CheckResult(Result.FAILED, player.getName() + " tried to place a block " + thisTime + " ms after the last one (min=" + magic.FASTPLACE_TIMEMIN + " ms)");
} }
lastBlockPlaceTime.put(name, (time - last)); lastBlockPlaceTime.put(name, (time - last));
} }
@@ -753,18 +749,18 @@ public class Backend {
public CheckResult checkSpam(Player player, String msg) { public CheckResult checkSpam(Player player, String msg) {
String name = player.getName(); String name = player.getName();
User user = manager.getUserManager().getUser(name); User user = manager.getUserManager().getUser(name);
if(user.getLastMessageTime() != -1) { if (user.getLastMessageTime() != -1) {
for(int i=0;i<2;i++) { for (int i = 0; i < 2; i++) {
String m = user.getMessage(i); String m = user.getMessage(i);
if(m == null) { if (m == null) {
break; break;
} }
Long l = user.getMessageTime(i); Long l = user.getMessageTime(i);
if(System.currentTimeMillis() - l > magic.CHAT_REPEAT_MIN * 100) { if (System.currentTimeMillis() - l > magic.CHAT_REPEAT_MIN * 100) {
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.spamWarning.getValue()); return new CheckResult(Result.FAILED, lang.spamWarning.getValue());
} }
} }
@@ -788,8 +784,8 @@ public class Backend {
} else if (clicks == magic.INVENTORY_CHECK) { } else if (clicks == magic.INVENTORY_CHECK) {
long time = System.currentTimeMillis() - inventoryTime.get(name); long time = System.currentTimeMillis() - inventoryTime.get(name);
inventoryClicks.put(name, 0); inventoryClicks.put(name, 0);
if(time < magic.INVENTORY_TIMEMIN) { if (time < magic.INVENTORY_TIMEMIN) {
return new CheckResult(Result.FAILED, player.getName()+" clicked inventory slots "+clicks+" times in "+time+" ms (max="+magic.INVENTORY_CHECK+" in "+magic.INVENTORY_TIMEMIN+" ms)"); return new CheckResult(Result.FAILED, player.getName() + " clicked inventory slots " + clicks + " times in " + time + " ms (max=" + magic.INVENTORY_CHECK + " in " + magic.INVENTORY_TIMEMIN + " ms)");
} }
} }
return PASS; return PASS;
@@ -797,23 +793,23 @@ public class Backend {
public CheckResult checkAutoTool(Player player) { public CheckResult checkAutoTool(Player player) {
if (itemInHand.containsKey(player.getName()) && itemInHand.get(player.getName()) != player.getItemInHand().getType()) { if (itemInHand.containsKey(player.getName()) && itemInHand.get(player.getName()) != player.getItemInHand().getType()) {
return new CheckResult(Result.FAILED, player.getName()+" switched tools too fast (had "+itemInHand.get(player.getName())+", has "+player.getItemInHand().getType()+")"); return new CheckResult(Result.FAILED, player.getName() + " switched tools too fast (had " + itemInHand.get(player.getName()) + ", has " + player.getItemInHand().getType() + ")");
} else { } else {
return PASS; return PASS;
} }
} }
public CheckResult checkSprintDamage(Player player) { public CheckResult checkSprintDamage(Player player) {
if(isDoing(player, sprinted, magic.SPRINT_MIN)) { if (isDoing(player, sprinted, magic.SPRINT_MIN)) {
return new CheckResult(Result.FAILED, player.getName()+" sprinted and damaged an entity too fast (min sprint="+magic.SPRINT_MIN+" ms)"); return new CheckResult(Result.FAILED, player.getName() + " sprinted and damaged an entity too fast (min sprint=" + magic.SPRINT_MIN + " ms)");
} else { } else {
return PASS; return PASS;
} }
} }
public CheckResult checkAnimation(Player player, Entity e) { public CheckResult checkAnimation(Player player, Entity e) {
if(!justAnimated(player)) { if (!justAnimated(player)) {
return new CheckResult(Result.FAILED, player.getName()+" didn't animate before damaging a "+e.getType()); return new CheckResult(Result.FAILED, player.getName() + " didn't animate before damaging a " + e.getType());
} else { } else {
return PASS; return PASS;
} }
@@ -824,8 +820,8 @@ public class Backend {
{ {
long l = lastHeal.get(player.getName()); long l = lastHeal.get(player.getName());
lastHeal.remove(player.getName()); lastHeal.remove(player.getName());
if((System.currentTimeMillis() - l) < magic.HEAL_TIME_MIN) { if ((System.currentTimeMillis() - l) < magic.HEAL_TIME_MIN) {
return new CheckResult(Result.FAILED, player.getName()+" healed too quickly (time="+(System.currentTimeMillis() - l)+" ms, min="+magic.HEAL_TIME_MIN+" ms)"); return new CheckResult(Result.FAILED, player.getName() + " healed too quickly (time=" + (System.currentTimeMillis() - l) + " ms, min=" + magic.HEAL_TIME_MIN + " ms)");
} }
} }
return PASS; return PASS;
@@ -836,8 +832,8 @@ public class Backend {
{ {
long l = startEat.get(player.getName()); long l = startEat.get(player.getName());
startEat.remove(player.getName()); startEat.remove(player.getName());
if((System.currentTimeMillis() - l) < magic.EAT_TIME_MIN) { if ((System.currentTimeMillis() - l) < magic.EAT_TIME_MIN) {
return new CheckResult(Result.FAILED, player.getName()+" ate too quickly (time="+(System.currentTimeMillis() - l)+" ms, min="+magic.EAT_TIME_MIN+" ms)"); return new CheckResult(Result.FAILED, player.getName() + " ate too quickly (time=" + (System.currentTimeMillis() - l) + " ms, min=" + magic.EAT_TIME_MIN + " ms)");
} }
} }
return PASS; return PASS;
@@ -861,7 +857,9 @@ public class Backend {
public boolean isHoveringOverWaterAfterViolation(Player player) { public boolean isHoveringOverWaterAfterViolation(Player player) {
if (waterSpeedViolation.containsKey(player.getName())) { if (waterSpeedViolation.containsKey(player.getName())) {
if (waterSpeedViolation.get(player.getName()) >= magic.WATER_SPEED_VIOLATION_MAX && Utilities.isHoveringOverWater(player.getLocation())) { return true; } if (waterSpeedViolation.get(player.getName()) >= magic.WATER_SPEED_VIOLATION_MAX && Utilities.isHoveringOverWater(player.getLocation())) {
return true;
}
} }
return false; return false;
} }
@@ -1026,7 +1024,7 @@ public class Backend {
} }
public void processChatSpammer(Player player) { public void processChatSpammer(Player player) {
if(chatLevel.get(player.getName()) != null && chatLevel.get(player.getName()) >= magic.CHAT_KICK_LEVEL) { if (chatLevel.get(player.getName()) != null && chatLevel.get(player.getName()) >= magic.CHAT_KICK_LEVEL) {
if (player != null && player.isOnline()) { if (player != null && player.isOnline()) {
String name = player.getName(); String name = player.getName();
int kick; int kick;
@@ -18,18 +18,18 @@
package net.h31ix.anticheat.manage; package net.h31ix.anticheat.manage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.h31ix.anticheat.AntiCheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.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;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* <p> * <p/>
* The manager that AntiCheat will check with to see if it should watch certain checks and certain players. * The manager that AntiCheat will check with to see if it should watch certain checks and certain players.
*/ */
@@ -85,7 +85,7 @@ public class CheckManager {
* Exempt a player from a check * Exempt a player from a check
* *
* @param player The player * @param player The player
* @param type The check * @param type The check
*/ */
public void exemptPlayer(Player player, CheckType type) { public void exemptPlayer(Player player, CheckType type) {
if (!isExempt(player, type)) { if (!isExempt(player, type)) {
@@ -102,7 +102,7 @@ public class CheckManager {
* Unexempt a player from a check * Unexempt a player from a check
* *
* @param player The player * @param player The player
* @param type The check * @param type The check
*/ */
public void unexemptPlayer(Player player, CheckType type) { public void unexemptPlayer(Player player, CheckType type) {
if (isExempt(player, type)) { if (isExempt(player, type)) {
@@ -115,7 +115,7 @@ public class CheckManager {
* Determine whether a player is exempt from a check * Determine whether a player is exempt from a check
* *
* @param player The player * @param player The player
* @param type The check * @param type The check
*/ */
public boolean isExempt(Player player, CheckType type) { public boolean isExempt(Player player, CheckType type) {
return exemptList.containsKey(player.getName()) ? exemptList.get(player.getName()).contains(type) : false; return exemptList.containsKey(player.getName()) ? exemptList.get(player.getName()).contains(type) : false;
@@ -144,29 +144,29 @@ public class CheckManager {
* Run a quick version of the "willCheck" method, using the other non-check-specific methods beforehand * Run a quick version of the "willCheck" method, using the other non-check-specific methods beforehand
* *
* @param player The player to check * @param player The player to check
* @param type The check being run * @param type The check being run
* @return true if the check should run * @return true if the check should run
*/ */
public boolean willCheckQuick(Player player, CheckType type) { public boolean willCheckQuick(Player player, CheckType type) {
return return
isActive(type) isActive(type)
&& !isExempt(player, type) && !isExempt(player, type)
&& !type.checkPermission(player); && !type.checkPermission(player);
} }
/** /**
* Determine whether a check should run on a player * Determine whether a check should run on a player
* *
* @param player The player to check * @param player The player to check
* @param type The check being run * @param type The check being run
* @return true if the check should run * @return true if the check should run
*/ */
public boolean willCheck(Player player, CheckType type) { public boolean willCheck(Player player, CheckType type) {
boolean check = isActive(type) boolean check = isActive(type)
&& checkInWorld(player) && 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,16 +18,16 @@
package net.h31ix.anticheat.manage; package net.h31ix.anticheat.manage;
import java.util.HashMap;
import java.util.Map;
import net.h31ix.anticheat.api.CheckFailEvent; import net.h31ix.anticheat.api.CheckFailEvent;
import net.h31ix.anticheat.util.Permission; import net.h31ix.anticheat.util.Permission;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
/** /**
* <p> * <p/>
* All the types of checks and their corresponding permission nodes. * All the types of checks and their corresponding permission nodes.
*/ */
@@ -30,7 +30,8 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.*; import java.util.ArrayList;
import java.util.List;
public class User { public class User {
private final String name; private final String name;
@@ -40,8 +41,8 @@ public class User {
private List<ItemStack> inventorySnapshot = null; private List<ItemStack> inventorySnapshot = null;
private Configuration config = AntiCheat.getManager().getConfiguration(); private Configuration config = AntiCheat.getManager().getConfiguration();
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];
private boolean isWaitingOnLevelSync; private boolean isWaitingOnLevelSync;
private Timestamp levelSyncTimestamp; private Timestamp levelSyncTimestamp;
@@ -94,10 +95,10 @@ public class User {
public Level getNamedLevel() { public Level getNamedLevel() {
List<Level> levels = config.getEvents().getLevels(); List<Level> levels = config.getEvents().getLevels();
for (int i=0;i<levels.size();i++) { for (int i = 0; i < levels.size(); i++) {
if (i == 0 && level < levels.get(i).getValue()) break; if (i == 0 && level < levels.get(i).getValue()) break;
else if (i == levels.size()-1) return levels.get(i); else if (i == levels.size() - 1) return levels.get(i);
else if (level >= levels.get(i).getValue() && level < levels.get(i+1).getValue()) return levels.get(i); else if (level >= levels.get(i).getValue() && level < levels.get(i + 1).getValue()) return levels.get(i);
} }
return null; return null;
} }
@@ -118,17 +119,17 @@ public class User {
level++; level++;
// Check levels // Check levels
for(Level l : getLevels()) { 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.getEvents().getHighestLevel()) { if (l.getValue() == config.getEvents().getHighestLevel()) {
level = l.getValue() - 10; level = l.getValue() - 10;
} }
} }
} }
// Execute rules // Execute rules
for(Rule rule : config.getRules().getRules()) { for (Rule rule : config.getRules().getRules()) {
rule.check(this, type); rule.check(this, type);
} }
return true; return true;
@@ -149,6 +150,7 @@ public class User {
/** /**
* Set the users level to a specific value. Must be 0 < level < config-defined highest level * Set the users level to a specific value. Must be 0 < level < config-defined highest level
*
* @param level level to set * @param level level to set
* @return true if the level was valid and set properly * @return true if the level was valid and set properly
*/ */
@@ -213,8 +215,8 @@ public class User {
*/ */
public void setInventorySnapshot(ItemStack[] is) { public void setInventorySnapshot(ItemStack[] is) {
inventorySnapshot = new ArrayList<ItemStack>(); inventorySnapshot = new ArrayList<ItemStack>();
for(int i=0;i<is.length;i++) { for (int i = 0; i < is.length; i++) {
if(is[i] != null) { if (is[i] != null) {
inventorySnapshot.add(is[i].clone()); inventorySnapshot.add(is[i].clone());
} }
} }
@@ -229,13 +231,14 @@ public class User {
/** /**
* Restore the player's inventory with the current inventory snapshot * Restore the player's inventory with the current inventory snapshot
*
* @param inventory Player's inventory * @param inventory Player's inventory
*/ */
public void restoreInventory(Inventory inventory) { public void restoreInventory(Inventory inventory) {
if(inventorySnapshot != null) { if (inventorySnapshot != null) {
inventory.clear(); inventory.clear();
for(ItemStack is : inventorySnapshot) { for (ItemStack is : inventorySnapshot) {
if(is != null) { if (is != null) {
inventory.addItem(is); inventory.addItem(is);
} }
} }
@@ -244,25 +247,27 @@ public class User {
/** /**
* Set the player's to location * Set the player's to location
*
* @param x X value * @param x X value
* @param y Y value * @param y Y value
* @param z Z value * @param z Z value
*/ */
public void setTo(double x, double y, double z) { public void setTo(double x, double y, double z) {
toX = (int)x; toX = (int) x;
toY = (int)y; toY = (int) y;
toZ = (int)z; toZ = (int) z;
} }
/** /**
* Check if a given to value is the same as the stored value * Check if a given to value is the same as the stored value
*
* @param x X value * @param x X value
* @param y Y value * @param y Y value
* @param z Z value * @param z Z value
* @return true if coordinates are all equal * @return true if coordinates are all equal
*/ */
public boolean checkTo(double x, double y, double z) { public boolean checkTo(double x, double y, double z) {
return (int)x == toX && (int)y == toY && (int)z == toZ; return (int) x == toX && (int) y == toY && (int) z == toZ;
} }
/** /**
@@ -18,9 +18,6 @@
package net.h31ix.anticheat.manage; package net.h31ix.anticheat.manage;
import java.util.ArrayList;
import java.util.List;
import net.h31ix.anticheat.AntiCheat; import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.Configuration; import net.h31ix.anticheat.config.Configuration;
import net.h31ix.anticheat.util.Level; import net.h31ix.anticheat.util.Level;
@@ -28,6 +25,9 @@ import net.h31ix.anticheat.util.Utilities;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.List;
public class UserManager { public class UserManager {
private List<User> users = new ArrayList<User>(); private List<User> users = new ArrayList<User>();
private static Configuration config; private static Configuration config;
@@ -49,6 +49,7 @@ public class UserManager {
/** /**
* Get a user with the given name * Get a user with the given name
*
* @param name Name * @param name Name
* @return User with name * @return User with name
*/ */
@@ -119,7 +120,7 @@ public class UserManager {
/** /**
* Set a user's level * Set a user's level
* *
* @param name Name of the player * @param name Name of the player
* @param level Level to set * @param level Level to set
*/ */
public void safeSetLevel(String name, int level) { public void safeSetLevel(String name, int level) {
@@ -131,6 +132,7 @@ public class UserManager {
/** /**
* Reset a user * Reset a user
*
* @param name Name of the user * @param name Name of the user
*/ */
public void safeReset(String name) { public void safeReset(String name) {
@@ -143,15 +145,15 @@ public class UserManager {
/** /**
* Fire an alert * Fire an alert
* *
* @param user The user to alert * @param user The user to alert
* @param level The user's level * @param level The user's level
* @param type The CheckType that triggered the alert * @param type The CheckType that triggered the alert
*/ */
public void alert(User user, Level level, CheckType type) { public void alert(User user, Level level, CheckType type) {
ArrayList<String> messageArray = new ArrayList<String>(); ArrayList<String> messageArray = new ArrayList<String>();
for (int i = 0; i < alert.size(); i++) { for (int i = 0; i < alert.size(); i++) {
String message = alert.get(i); String message = alert.get(i);
if(!message.equals("")) { if (!message.equals("")) {
message = message.replaceAll("&player", GOLD + user.getName() + GRAY); message = message.replaceAll("&player", GOLD + user.getName() + GRAY);
message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY); message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY);
message = message.replaceAll("&level", level.getColor() + level.getName() + GRAY); message = message.replaceAll("&level", level.getColor() + level.getName() + GRAY);
@@ -164,9 +166,10 @@ public class UserManager {
/** /**
* Execute configuration actions for an alert * Execute configuration actions for an alert
* @param user The user *
* @param user The user
* @param actions The list of actions to execute * @param actions The list of actions to execute
* @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().kickReason.getValue(), config.getLang().playerWarning.getValue(), config.getLang().banReason.getValue()); execute(user, actions, type, config.getLang().kickReason.getValue(), config.getLang().playerWarning.getValue(), config.getLang().banReason.getValue());
@@ -175,12 +178,12 @@ public class UserManager {
/** /**
* Execute configuration actions for an alert * Execute configuration actions for an alert
* *
* @param user The user * @param user The user
* @param actions The list of actions to execute * @param actions The list of actions to execute
* @param type The CheckType that triggered the alert * @param type The CheckType that triggered the alert
* @param kickReason The config's kick reason * @param kickReason The config's kick reason
* @param warning The config's warning format * @param warning The config's warning format
* @param banReason The config's ban reason * @param banReason The config's ban reason
*/ */
public void execute(final User user, final List<String> actions, final CheckType type, final String kickReason, final List<String> warning, final String banReason) { 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
@@ -188,11 +191,11 @@ public class UserManager {
@Override @Override
public void run() { public void run() {
final String name = user.getName(); final String name = user.getName();
for(String event : actions) { for (String event : actions) {
event = event.replaceAll("&player", name).replaceAll("&world", user.getPlayer().getWorld().getName()).replaceAll("&check", type.name()); event = event.replaceAll("&player", name).replaceAll("&world", user.getPlayer().getWorld().getName()).replaceAll("&check", type.name());
if (event.startsWith("COMMAND[")) { if (event.startsWith("COMMAND[")) {
for(String cmd : Utilities.getCommands(event)) { for (String cmd : Utilities.getCommands(event)) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd);
} }
} else if (event.equalsIgnoreCase("KICK")) { } else if (event.equalsIgnoreCase("KICK")) {
@@ -204,7 +207,7 @@ public class UserManager {
} else if (event.equalsIgnoreCase("WARN")) { } else if (event.equalsIgnoreCase("WARN")) {
List<String> message = warning; List<String> message = warning;
for (String string : message) { for (String string : message) {
if(!string.equals("")) { if (!string.equals("")) {
user.getPlayer().sendMessage(RED + string); user.getPlayer().sendMessage(RED + string);
} }
} }
@@ -6,31 +6,30 @@
package net.h31ix.anticheat.update; package net.h31ix.anticheat.update;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import java.io.*; import java.io.*;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
/** /**
* Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed. * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed.
* <p> * <p/>
* <b>VERY, VERY IMPORTANT</b>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating. * <b>VERY, VERY IMPORTANT</b>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating.
* <br> * <br>
* It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config that prevents the auto-updater from running <b>AT ALL</b>. * It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config that prevents the auto-updater from running <b>AT ALL</b>.
* <br> * <br>
* If you fail to include this option in your config, your plugin will be <b>REJECTED</b> when you attempt to submit it to dev.bukkit.org. * If you fail to include this option in your config, your plugin will be <b>REJECTED</b> when you attempt to submit it to dev.bukkit.org.
* <p> * <p/>
* An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater. * An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater.
* <br> * <br>
* If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l
@@ -38,8 +37,7 @@ import org.bukkit.plugin.Plugin;
* @author H31IX * @author H31IX
*/ */
public class Updater public class Updater {
{
private Plugin plugin; private Plugin plugin;
private UpdateType type; private UpdateType type;
private String versionTitle; private String versionTitle;
@@ -53,7 +51,7 @@ public class Updater
private File file; // The plugin's file private File file; // The plugin's file
private Thread thread; // Updater thread private Thread thread; // Updater thread
private static final String DBOUrl = "http://dev.bukkit.org/server-mods/"; // Slugs will be appended to this to get to the project's RSS feed private static final String DBOUrl = "http://dev.bukkit.org/server-mods/"; // Slugs will be appended to this to get to the project's RSS feed
private String [] noUpdateTag = {"-DEV","-PRE","-SNAPSHOT"}; // If the version number contains one of these, don't update. private String[] noUpdateTag = {"-DEV", "-PRE", "-SNAPSHOT"}; // If the version number contains one of these, don't update.
private static final int BYTE_SIZE = 1024; // Used for downloading files private static final int BYTE_SIZE = 1024; // Used for downloading files
private String updateFolder = YamlConfiguration.loadConfiguration(new File("bukkit.yml")).getString("settings.update-folder"); // The folder that downloads will be placed in private String updateFolder = YamlConfiguration.loadConfiguration(new File("bukkit.yml")).getString("settings.update-folder"); // The folder that downloads will be placed in
private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process
@@ -65,8 +63,7 @@ public class Updater
/** /**
* Gives the dev the result of the update process. Can be obtained by called getResult(). * Gives the dev the result of the update process. Can be obtained by called getResult().
*/ */
public enum UpdateResult public enum UpdateResult {
{
/** /**
* The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads.
*/ */
@@ -100,8 +97,7 @@ public class Updater
/** /**
* Allows the dev to specify the type of update that will be run. * Allows the dev to specify the type of update that will be run.
*/ */
public enum UpdateType public enum UpdateType {
{
/** /**
* Run a version check, and then if the file is out of date, download the newest version. * Run a version check, and then if the file is out of date, download the newest version.
*/ */
@@ -119,30 +115,21 @@ public class Updater
/** /**
* Initialize the updater * Initialize the updater
* *
* @param plugin * @param plugin The plugin that is checking for an update.
* The plugin that is checking for an update. * @param slug The dev.bukkit.org slug of the project (http://dev.bukkit.org/server-mods/SLUG_IS_HERE)
* @param slug * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class.
* The dev.bukkit.org slug of the project (http://dev.bukkit.org/server-mods/SLUG_IS_HERE) * @param type Specify the type of update this will be. See {@link UpdateType}
* @param file * @param announce True if the program should announce the progress of new updates in console
* The file that the plugin is running from, get this by doing this.getFile() from within your main class.
* @param type
* Specify the type of update this will be. See {@link UpdateType}
* @param announce
* True if the program should announce the progress of new updates in console
*/ */
public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) {
{
this.plugin = plugin; this.plugin = plugin;
this.type = type; this.type = type;
this.announce = announce; this.announce = announce;
this.file = file; this.file = file;
try try {
{
// Obtain the results of the project's file feed // Obtain the results of the project's file feed
url = new URL(DBOUrl + slug + "/files.rss"); url = new URL(DBOUrl + slug + "/files.rss");
} } catch (MalformedURLException ex) {
catch (MalformedURLException ex)
{
// Invalid slug // Invalid slug
plugin.getLogger().warning("The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system"); plugin.getLogger().warning("The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system");
plugin.getLogger().warning("The project slug given ('" + slug + "') is invalid. Please nag the author about this."); plugin.getLogger().warning("The project slug given ('" + slug + "') is invalid. Please nag the author about this.");
@@ -155,8 +142,7 @@ public class Updater
/** /**
* Get the result of the update process. * Get the result of the update process.
*/ */
public Updater.UpdateResult getResult() public Updater.UpdateResult getResult() {
{
waitForThread(); waitForThread();
return result; return result;
} }
@@ -164,8 +150,7 @@ public class Updater
/** /**
* Get the total bytes of the file (can only be used after running a version check or a normal run). * Get the total bytes of the file (can only be used after running a version check or a normal run).
*/ */
public long getFileSize() public long getFileSize() {
{
waitForThread(); waitForThread();
return totalSize; return totalSize;
} }
@@ -173,8 +158,7 @@ public class Updater
/** /**
* Get the version string latest file avaliable online. * Get the version string latest file avaliable online.
*/ */
public String getLatestVersionString() public String getLatestVersionString() {
{
waitForThread(); waitForThread();
return versionTitle; return versionTitle;
} }
@@ -184,7 +168,7 @@ public class Updater
* before alloowing anyone to check the result. * before alloowing anyone to check the result.
*/ */
public void waitForThread() { public void waitForThread() {
if(thread.isAlive()) { if (thread.isAlive()) {
try { try {
thread.join(); thread.join();
} catch (InterruptedException e) { } catch (InterruptedException e) {
@@ -196,16 +180,13 @@ public class Updater
/** /**
* Save an update from dev.bukkit.org into the server's update folder. * Save an update from dev.bukkit.org into the server's update folder.
*/ */
private void saveFile(File folder, String file, String u) private void saveFile(File folder, String file, String u) {
{ if (!folder.exists()) {
if(!folder.exists())
{
folder.mkdir(); folder.mkdir();
} }
BufferedInputStream in = null; BufferedInputStream in = null;
FileOutputStream fout = null; FileOutputStream fout = null;
try try {
{
// Download the file // Download the file
URL url = new URL(u); URL url = new URL(u);
int fileLength = url.openConnection().getContentLength(); int fileLength = url.openConnection().getContentLength();
@@ -214,55 +195,41 @@ public class Updater
byte[] data = new byte[BYTE_SIZE]; byte[] data = new byte[BYTE_SIZE];
int count; int count;
if(announce) plugin.getLogger().info("About to download a new update: " + versionTitle); if (announce) plugin.getLogger().info("About to download a new update: " + versionTitle);
long downloaded = 0; long downloaded = 0;
while ((count = in.read(data, 0, BYTE_SIZE)) != -1) while ((count = in.read(data, 0, BYTE_SIZE)) != -1) {
{
downloaded += count; downloaded += count;
fout.write(data, 0, count); fout.write(data, 0, count);
int percent = (int) (downloaded * 100 / fileLength); int percent = (int) (downloaded * 100 / fileLength);
if(announce & (percent % 10 == 0)) if (announce & (percent % 10 == 0)) {
{
plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes.");
} }
} }
//Just a quick check to make sure we didn't leave any files from last time... //Just a quick check to make sure we didn't leave any files from last time...
for(File xFile : new File("plugins/" + updateFolder).listFiles()) for (File xFile : new File("plugins/" + updateFolder).listFiles()) {
{ if (xFile.getName().endsWith(".zip")) {
if(xFile.getName().endsWith(".zip"))
{
xFile.delete(); xFile.delete();
} }
} }
// Check to see if it's a zip file, if it is, unzip it. // Check to see if it's a zip file, if it is, unzip it.
File dFile = new File(folder.getAbsolutePath() + "/" + file); File dFile = new File(folder.getAbsolutePath() + "/" + file);
if(dFile.getName().endsWith(".zip")) if (dFile.getName().endsWith(".zip")) {
{
// Unzip // Unzip
unzip(dFile.getCanonicalPath()); unzip(dFile.getCanonicalPath());
} }
if(announce) plugin.getLogger().info("Finished updating."); if (announce) plugin.getLogger().info("Finished updating.");
} } catch (Exception ex) {
catch (Exception ex)
{
plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DOWNLOAD; result = Updater.UpdateResult.FAIL_DOWNLOAD;
} } finally {
finally try {
{ if (in != null) {
try
{
if (in != null)
{
in.close(); in.close();
} }
if (fout != null) if (fout != null) {
{
fout.close(); fout.close();
} }
} } catch (Exception ex) {
catch (Exception ex)
{
} }
} }
} }
@@ -270,40 +237,32 @@ public class Updater
/** /**
* Part of Zip-File-Extractor, modified by H31IX for use with Bukkit * Part of Zip-File-Extractor, modified by H31IX for use with Bukkit
*/ */
private void unzip(String file) private void unzip(String file) {
{ try {
try
{
File fSourceZip = new File(file); File fSourceZip = new File(file);
String zipPath = file.substring(0, file.length()-4); String zipPath = file.substring(0, file.length() - 4);
ZipFile zipFile = new ZipFile(fSourceZip); ZipFile zipFile = new ZipFile(fSourceZip);
Enumeration<? extends ZipEntry> e = zipFile.entries(); Enumeration<? extends ZipEntry> e = zipFile.entries();
while(e.hasMoreElements()) while (e.hasMoreElements()) {
{ ZipEntry entry = (ZipEntry) e.nextElement();
ZipEntry entry = (ZipEntry)e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName());
File destinationFilePath = new File(zipPath,entry.getName());
destinationFilePath.getParentFile().mkdirs(); destinationFilePath.getParentFile().mkdirs();
if(entry.isDirectory()) if (entry.isDirectory()) {
{
continue; continue;
} } else {
else
{
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
int b; int b;
byte buffer[] = new byte[BYTE_SIZE]; byte buffer[] = new byte[BYTE_SIZE];
FileOutputStream fos = new FileOutputStream(destinationFilePath); FileOutputStream fos = new FileOutputStream(destinationFilePath);
BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE); BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE);
while((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) while ((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) {
{
bos.write(buffer, 0, b); bos.write(buffer, 0, b);
} }
bos.flush(); bos.flush();
bos.close(); bos.close();
bis.close(); bis.close();
String name = destinationFilePath.getName(); String name = destinationFilePath.getName();
if(name.endsWith(".jar") && pluginFile(name)) if (name.endsWith(".jar") && pluginFile(name)) {
{
destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name)); destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name));
} }
} }
@@ -314,32 +273,25 @@ public class Updater
zipFile.close(); zipFile.close();
zipFile = null; zipFile = null;
// Move any plugin data folders that were included to the right place, Bukkit won't do this for us. // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
for(File dFile : new File(zipPath).listFiles()) for (File dFile : new File(zipPath).listFiles()) {
{ if (dFile.isDirectory()) {
if(dFile.isDirectory()) if (pluginFile(dFile.getName())) {
{
if(pluginFile(dFile.getName()))
{
File oFile = new File("plugins/" + dFile.getName()); // Get current dir File oFile = new File("plugins/" + dFile.getName()); // Get current dir
File [] contents = oFile.listFiles(); // List of existing files in the current dir File[] contents = oFile.listFiles(); // List of existing files in the current dir
for(File cFile : dFile.listFiles()) // Loop through all the files in the new dir for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir
{ {
boolean found = false; boolean found = false;
for(File xFile : contents) // Loop through contents to see if it exists for (File xFile : contents) // Loop through contents to see if it exists
{ {
if(xFile.getName().equals(cFile.getName())) if (xFile.getName().equals(cFile.getName())) {
{
found = true; found = true;
break; break;
} }
} }
if(!found) if (!found) {
{
// Move the new file into the current dir // Move the new file into the current dir
cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName()));
} } else {
else
{
// This file already exists, so we don't need it anymore. // This file already exists, so we don't need it anymore.
cFile.delete(); cFile.delete();
} }
@@ -350,9 +302,7 @@ public class Updater
} }
new File(zipPath).delete(); new File(zipPath).delete();
fSourceZip.delete(); fSourceZip.delete();
} } catch (IOException ex) {
catch(IOException ex)
{
ex.printStackTrace(); ex.printStackTrace();
plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DOWNLOAD; result = Updater.UpdateResult.FAIL_DOWNLOAD;
@@ -363,12 +313,9 @@ public class Updater
/** /**
* Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip.
*/ */
public boolean pluginFile(String name) public boolean pluginFile(String name) {
{ for (File file : new File("plugins").listFiles()) {
for(File file : new File("plugins").listFiles()) if (file.getName().equals(name)) {
{
if(file.getName().equals(name))
{
return true; return true;
} }
} }
@@ -378,11 +325,9 @@ public class Updater
/** /**
* Obtain the direct download file url from the file's page. * Obtain the direct download file url from the file's page.
*/ */
private String getFile(String link) private String getFile(String link) {
{
String download = null; String download = null;
try try {
{
// Open a connection to the page // Open a connection to the page
URL url = new URL(link); URL url = new URL(link);
URLConnection urlConn = url.openConnection(); URLConnection urlConn = url.openConnection();
@@ -391,35 +336,28 @@ public class Updater
int counter = 0; int counter = 0;
String line; String line;
while((line = buff.readLine()) != null) while ((line = buff.readLine()) != null) {
{
counter++; counter++;
// Search for the download link // Search for the download link
if(line.contains("<li class=\"user-action user-action-download\">")) if (line.contains("<li class=\"user-action user-action-download\">")) {
{
// Get the raw link // Get the raw link
download = line.split("<a href=\"")[1].split("\">Download</a>")[0]; download = line.split("<a href=\"")[1].split("\">Download</a>")[0];
} }
// Search for size // Search for size
else if (line.contains("<dt>Size</dt>")) else if (line.contains("<dt>Size</dt>")) {
{ sizeLine = counter + 1;
sizeLine = counter+1; } else if (counter == sizeLine) {
}
else if(counter == sizeLine)
{
String size = line.replaceAll("<dd>", "").replaceAll("</dd>", ""); String size = line.replaceAll("<dd>", "").replaceAll("</dd>", "");
multiplier = size.contains("MiB") ? 1048576 : 1024; multiplier = size.contains("MiB") ? 1048576 : 1024;
size = size.replace(" KiB", "").replace(" MiB", ""); size = size.replace(" KiB", "").replace(" MiB", "");
totalSize = (long)(Double.parseDouble(size)*multiplier); totalSize = (long) (Double.parseDouble(size) * multiplier);
} }
} }
urlConn = null; urlConn = null;
inStream = null; inStream = null;
buff.close(); buff.close();
buff = null; buff = null;
} } catch (Exception ex) {
catch (Exception ex)
{
ex.printStackTrace(); ex.printStackTrace();
plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DBO; result = Updater.UpdateResult.FAIL_DBO;
@@ -431,33 +369,24 @@ public class Updater
/** /**
* Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated * Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated
*/ */
private boolean versionCheck(String title) private boolean versionCheck(String title) {
{ if (type != UpdateType.NO_VERSION_CHECK) {
if(type != UpdateType.NO_VERSION_CHECK)
{
String version = plugin.getDescription().getVersion(); String version = plugin.getDescription().getVersion();
if(title.split(" v").length == 2) if (title.split(" v").length == 2) {
{
String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number
int remVer = -1,curVer=0; int remVer = -1, curVer = 0;
try try {
{
remVer = calVer(remoteVersion); remVer = calVer(remoteVersion);
curVer = calVer(version); curVer = calVer(version);
} catch (NumberFormatException nfe) {
remVer = -1;
} }
catch(NumberFormatException nfe) if (hasTag(version) || version.equalsIgnoreCase(remoteVersion) || curVer >= remVer) {
{
remVer=-1;
}
if(hasTag(version)||version.equalsIgnoreCase(remoteVersion)||curVer>=remVer)
{
// We already have the latest version, or this build is tagged for no-update // We already have the latest version, or this build is tagged for no-update
result = Updater.UpdateResult.NO_UPDATE; result = Updater.UpdateResult.NO_UPDATE;
return false; return false;
} }
} } else {
else
{
// The file's name did not contain the string 'vVersion' // The file's name did not contain the string 'vVersion'
plugin.getLogger().warning("The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system"); plugin.getLogger().warning("The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system");
plugin.getLogger().warning("Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0"); plugin.getLogger().warning("Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0");
@@ -468,19 +397,16 @@ public class Updater
} }
return true; return true;
} }
/** /**
* Used to calculate the version string as an Integer * Used to calculate the version string as an Integer
*/ */
private Integer calVer(String s) throws NumberFormatException private Integer calVer(String s) throws NumberFormatException {
{ if (s.contains(".")) {
if(s.contains("."))
{
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i = 0; i <s.length(); i++) for (int i = 0; i < s.length(); i++) {
{
Character c = s.charAt(i); Character c = s.charAt(i);
if (Character.isLetterOrDigit(c)) if (Character.isLetterOrDigit(c)) {
{
sb.append(c); sb.append(c);
} }
} }
@@ -488,15 +414,13 @@ public class Updater
} }
return Integer.parseInt(s); return Integer.parseInt(s);
} }
/** /**
* Evaluate whether the version number is marked showing that it should not be updated by this program * Evaluate whether the version number is marked showing that it should not be updated by this program
*/ */
private boolean hasTag(String version) private boolean hasTag(String version) {
{ for (String string : noUpdateTag) {
for(String string : noUpdateTag) if (version.contains(string)) {
{
if(version.contains(string))
{
return true; return true;
} }
} }
@@ -506,10 +430,8 @@ public class Updater
/** /**
* Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit * Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit
*/ */
private boolean readFeed() private boolean readFeed() {
{ try {
try
{
// Set header values intial to the empty string // Set header values intial to the empty string
String title = ""; String title = "";
String link = ""; String link = "";
@@ -517,32 +439,24 @@ public class Updater
XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader // Setup a new eventReader
InputStream in = read(); InputStream in = read();
if(in != null) if (in != null) {
{
XMLEventReader eventReader = inputFactory.createXMLEventReader(in); XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Read the XML document // Read the XML document
while (eventReader.hasNext()) while (eventReader.hasNext()) {
{
XMLEvent event = eventReader.nextEvent(); XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) if (event.isStartElement()) {
{ if (event.asStartElement().getName().getLocalPart().equals(TITLE)) {
if (event.asStartElement().getName().getLocalPart().equals(TITLE))
{
event = eventReader.nextEvent(); event = eventReader.nextEvent();
title = event.asCharacters().getData(); title = event.asCharacters().getData();
continue; continue;
} }
if (event.asStartElement().getName().getLocalPart().equals(LINK)) if (event.asStartElement().getName().getLocalPart().equals(LINK)) {
{
event = eventReader.nextEvent(); event = eventReader.nextEvent();
link = event.asCharacters().getData(); link = event.asCharacters().getData();
continue; continue;
} }
} } else if (event.isEndElement()) {
else if (event.isEndElement()) if (event.asEndElement().getName().getLocalPart().equals(ITEM)) {
{
if (event.asEndElement().getName().getLocalPart().equals(ITEM))
{
// Store the title and link of the first entry we get - the first file on the list is all we need // Store the title and link of the first entry we get - the first file on the list is all we need
versionTitle = title; versionTitle = title;
versionLink = link; versionLink = link;
@@ -552,14 +466,10 @@ public class Updater
} }
} }
return true; return true;
} } else {
else
{
return false; return false;
} }
} } catch (XMLStreamException e) {
catch (XMLStreamException e)
{
plugin.getLogger().warning("Could not reach dev.bukkit.org for update checking. Is it offline?"); plugin.getLogger().warning("Could not reach dev.bukkit.org for update checking. Is it offline?");
return false; return false;
} }
@@ -568,14 +478,10 @@ public class Updater
/** /**
* Open the RSS feed * Open the RSS feed
*/ */
private InputStream read() private InputStream read() {
{ try {
try
{
return url.openStream(); return url.openStream();
} } catch (IOException e) {
catch (IOException e)
{
plugin.getLogger().warning("Could not reach BukkitDev file stream for update checking. Is dev.bukkit.org offline?"); plugin.getLogger().warning("Could not reach BukkitDev file stream for update checking. Is dev.bukkit.org offline?");
return null; return null;
} }
@@ -584,27 +490,20 @@ public class Updater
private class UpdateRunnable implements Runnable { private class UpdateRunnable implements Runnable {
public void run() { public void run() {
if(url != null) if (url != null) {
{
// Obtain the results of the project's file feed // Obtain the results of the project's file feed
if(readFeed()) if (readFeed()) {
{ if (versionCheck(versionTitle)) {
if(versionCheck(versionTitle))
{
String fileLink = getFile(versionLink); String fileLink = getFile(versionLink);
if(fileLink != null && type != UpdateType.NO_DOWNLOAD) if (fileLink != null && type != UpdateType.NO_DOWNLOAD) {
{
String name = file.getName(); String name = file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name // If it's a zip file, it shouldn't be downloaded as the plugin's name
if(fileLink.endsWith(".zip")) if (fileLink.endsWith(".zip")) {
{ String[] split = fileLink.split("/");
String [] split = fileLink.split("/"); name = split[split.length - 1];
name = split[split.length-1];
} }
saveFile(new File("plugins/" + updateFolder), name, fileLink); saveFile(new File("plugins/" + updateFolder), name, fileLink);
} } else {
else
{
result = UpdateResult.UPDATE_AVAILABLE; result = UpdateResult.UPDATE_AVAILABLE;
} }
} }
@@ -21,7 +21,7 @@ package net.h31ix.anticheat.util;
public class CheckResult { public class CheckResult {
public enum Result { public enum Result {
PASSED,FAILED PASSED, FAILED
} }
private Result result; private Result result;
@@ -18,13 +18,13 @@
package net.h31ix.anticheat.util; package net.h31ix.anticheat.util;
import net.h31ix.anticheat.AntiCheat;
import org.bukkit.ChatColor;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import net.h31ix.anticheat.AntiCheat;
import org.bukkit.ChatColor;
public class Level { public class Level {
private String name; private String name;
@@ -39,8 +39,8 @@ public class Level {
this.actions = actions; this.actions = actions;
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;
@@ -69,7 +69,7 @@ public class Level {
public static Level load(String string) { public static Level load(String string) {
try { try {
if(string.split(":").length == 4) { if (string.split(":").length == 4) {
string = Utilities.removeWhitespace(string); string = Utilities.removeWhitespace(string);
String name = string.split(":")[0]; String name = string.split(":")[0];
int level = Integer.parseInt(string.split(":")[1]); int level = Integer.parseInt(string.split(":")[1]);
@@ -80,15 +80,15 @@ public class Level {
throw new Exception(); throw new Exception();
} }
} 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 : action' such as 'High : 50 : RED : KICK'"); AntiCheat.getPlugin().getLogger().warning("The proper format is: 'name : threshold : color : action' such as 'High : 50 : RED : KICK'");
AntiCheat.getPlugin().getLogger().warning("This event will NOT run. ("+ex.getMessage()+")"); AntiCheat.getPlugin().getLogger().warning("This event will NOT run. (" + ex.getMessage() + ")");
return null; return null;
} }
} }
@Override @Override
public String toString() { public String toString() {
return name + " : " + value + " : "+ color.name() + " : " + Utilities.listToCommaString(actions); return name + " : " + value + " : " + color.name() + " : " + Utilities.listToCommaString(actions);
} }
} }
@@ -18,6 +18,13 @@
package net.h31ix.anticheat.util; package net.h31ix.anticheat.util;
import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.files.Magic;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.io.*; import java.io.*;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
@@ -27,13 +34,6 @@ import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import net.h31ix.anticheat.AntiCheat;
import net.h31ix.anticheat.config.files.Magic;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
public class PastebinReport { public class PastebinReport {
private StringBuilder report = new StringBuilder(); private StringBuilder report = new StringBuilder();
private String url = ""; private String url = "";
@@ -43,13 +43,14 @@ public class PastebinReport {
public PastebinReport(CommandSender cs) { public PastebinReport(CommandSender cs) {
Player player = null; Player player = null;
if(cs instanceof Player) { if (cs instanceof Player) {
player = (Player) cs; player = (Player) cs;
} }
createReport(player); createReport(player);
try { try {
writeReport(); writeReport();
} catch (IOException e) {} } catch (IOException e) {
}
postReport(); postReport();
} }
@@ -57,7 +58,8 @@ public class PastebinReport {
createReport(tp); createReport(tp);
try { try {
writeReport(); writeReport();
} catch (IOException e) {} } catch (IOException e) {
}
postReport(); postReport();
} }
@@ -73,8 +75,8 @@ public class PastebinReport {
for (Permission node : Permission.values()) { for (Permission node : Permission.values()) {
report.append(player.getName() + ": " + node.toString() + " " + node.get(player)); report.append(player.getName() + ": " + node.toString() + " " + node.get(player));
if(node.get(player) && !node.whichPermission(player).equals(node.toString())) { if (node.get(player) && !node.whichPermission(player).equals(node.toString())) {
report.append(" (Applied by " + node.whichPermission(player) +")"); report.append(" (Applied by " + node.whichPermission(player) + ")");
} }
report.append('\n'); report.append('\n');
} }
@@ -100,11 +102,11 @@ 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;
} }
for(String log : logs) { for (String log : logs) {
append(log); append(log);
} }
} }
@@ -131,25 +133,25 @@ public class PastebinReport {
FileConfiguration file = magic.getDefaultConfigFile(); 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()) {
Object defaultValue = file.get(field.getName()); Object defaultValue = file.get(field.getName());
try { try {
Field value = magic.getClass().getDeclaredField(field.getName()); Field value = magic.getClass().getDeclaredField(field.getName());
boolean x = false; boolean x = false;
String s1 = value.get(magic).toString(); String s1 = value.get(magic).toString();
String s2 = defaultValue.toString(); String s2 = defaultValue.toString();
if(!s1.equals(s2) && !s1.equals(s2 + ".0")) { if (!s1.equals(s2) && !s1.equals(s2 + ".0")) {
changed = true; changed = true;
append(field.getName() + ": " + s1 + " (Default: " + s2 + ")"); append(field.getName() + ": " + s1 + " (Default: " + s2 + ")");
} else { } else {
} }
} catch(NoSuchFieldException ex) { } catch (NoSuchFieldException ex) {
} catch(IllegalAccessException ex) { } catch (IllegalAccessException ex) {
} }
} }
if(!changed) { if (!changed) {
append("No changes from default."); append("No changes from default.");
} }
} }
@@ -19,7 +19,6 @@
package net.h31ix.anticheat.util; package net.h31ix.anticheat.util;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public enum Permission { public enum Permission {
/* Check Nodes */ /* Check Nodes */
@@ -74,8 +73,8 @@ public enum Permission {
} }
public String whichPermission(CommandSender cs) { public String whichPermission(CommandSender cs) {
for(String s : new String[]{toString(), getBase(), PERMISSION_ALL}) { for (String s : new String[]{toString(), getBase(), PERMISSION_ALL}) {
if(cs.hasPermission(s)) { if (cs.hasPermission(s)) {
return s; return s;
} }
} }
@@ -38,7 +38,9 @@ public enum ToolHardness {
public static double getToolHardness(Material tool) { public static double getToolHardness(Material tool) {
for (ToolHardness e : ToolHardness.values()) { for (ToolHardness e : ToolHardness.values()) {
if (tool.name().contains(e.name())) { return e.hardness; } if (tool.name().contains(e.name())) {
return e.hardness;
}
} }
return 1.50D; return 1.50D;
@@ -18,11 +18,6 @@
package net.h31ix.anticheat.util; package net.h31ix.anticheat.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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;
@@ -34,6 +29,11 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.util.NumberConversions; import org.bukkit.util.NumberConversions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class Utilities { public final class Utilities {
private static final List<Material> INSTANT_BREAK = new ArrayList<Material>(); private static final List<Material> INSTANT_BREAK = new ArrayList<Material>();
private static final List<Material> FOOD = new ArrayList<Material>(); private static final List<Material> FOOD = new ArrayList<Material>();
@@ -46,7 +46,6 @@ public final class Utilities {
* Send a hack level alert to players and console * Send a hack level alert to players and console
* *
* @param message List of strings to send as the alert * @param message List of strings to send as the alert
*
*/ */
public static void alert(List<String> message) { public static void alert(List<String> message) {
for (Player player : Bukkit.getOnlinePlayers()) { for (Player player : Bukkit.getOnlinePlayers()) {
@@ -138,6 +137,7 @@ public final class Utilities {
/** /**
* Fixes a player's X position to determine the block they are on, even if they're on the edge * Fixes a player's X position to determine the block they are on, even if they're on the edge
*
* @param x player's x position * @param x player's x position
* @return fixed x position * @return fixed x position
*/ */
@@ -336,19 +336,20 @@ public final class Utilities {
try { try {
Integer.parseInt(string); Integer.parseInt(string);
x = true; x = true;
} catch (Exception ex) {} } catch (Exception ex) {
}
return x; return x;
} }
/** /**
* Calculate the time in milliseconds that it should take to break the given block with the given tool * Calculate the time in milliseconds that it should take to break the given block with the given tool
* *
* @param tool tool to check * @param tool tool to check
* @param block block to check * @param block block to check
* @return time in milliseconds to break * @return time in milliseconds to break
*/ */
public static long calcSurvivalFastBreak(ItemStack tool, Material block) { public static long calcSurvivalFastBreak(ItemStack tool, Material block) {
if(isInstantBreak(block) || (tool.getType() == Material.SHEARS && block == Material.LEAVES)) { if (isInstantBreak(block) || (tool.getType() == Material.SHEARS && block == Material.LEAVES)) {
return 0; return 0;
} }
double bhardness = BlockHardness.getBlockHardness(block); double bhardness = BlockHardness.getBlockHardness(block);
@@ -369,8 +370,8 @@ public final class Utilities {
result = 0; result = 0;
} }
if(isQuickCombo(tool, block)) { if (isQuickCombo(tool, block)) {
result = result/2; result = result / 2;
} }
return result; return result;
@@ -379,13 +380,13 @@ public final class Utilities {
/** /**
* Determine whether the given tool is a combination that makes the breaking of this block faster * Determine whether the given tool is a combination that makes the breaking of this block faster
* *
* @param tool tool to check * @param tool tool to check
* @param block block to check * @param block block to check
* @return true if quick combo * @return true if quick combo
*/ */
private static boolean isQuickCombo(ItemStack tool, Material block) { private static boolean isQuickCombo(ItemStack tool, Material block) {
for(Material t : COMBO.keySet()) { for (Material t : COMBO.keySet()) {
if(tool.getType() == t && COMBO.get(t) == block) { if (tool.getType() == t && COMBO.get(t) == block) {
return true; return true;
} }
} }
@@ -395,14 +396,14 @@ public final class Utilities {
/** /**
* Determine if a block ISN'T one of the specified types * Determine if a block ISN'T one of the specified types
* *
* @param block block to check * @param block block to check
* @param materials array of possible materials * @param materials array of possible materials
* @return true if the block isn't any of the materials * @return true if the block isn't any of the materials
*/ */
public static boolean blockIsnt(Block block, Material[] materials) { public static boolean blockIsnt(Block block, Material[] materials) {
Material type = block.getType(); Material type = block.getType();
for(Material m : materials) { for (Material m : materials) {
if(m == type) { if (m == type) {
return false; return false;
} }
} }
@@ -415,7 +416,7 @@ public final class Utilities {
* @param command input string * @param command input string
* @return parsed commands * @return parsed commands
*/ */
public static String [] getCommands(String command) { public static String[] getCommands(String command) {
return command.replaceAll("COMMAND\\[", "").replaceAll("]", "").split(";"); return command.replaceAll("COMMAND\\[", "").replaceAll("]", "").split(";");
} }
@@ -433,12 +434,12 @@ public final class Utilities {
* Determine if a player has the given enchantment on their armor * Determine if a player has the given enchantment on their armor
* *
* @param player player to check * @param player player to check
* @param e enchantment to check * @param e enchantment to check
* @return true if the armor has this enchantment * @return true if the armor has this enchantment
*/ */
public static boolean hasArmorEnchantment(Player player, Enchantment e) { public static boolean hasArmorEnchantment(Player player, Enchantment e) {
for(ItemStack is : player.getInventory().getArmorContents()) { for (ItemStack is : player.getInventory().getArmorContents()) {
if(is != null && is.containsEnchantment(e)) { if (is != null && is.containsEnchantment(e)) {
return true; return true;
} }
} }
@@ -465,9 +466,9 @@ public final class Utilities {
*/ */
public static String listToCommaString(List<String> list) { public static String listToCommaString(List<String> list) {
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
for(int i=0;i<list.size();i++) { for (int i = 0; i < list.size(); i++) {
b.append(list.get(i)); b.append(list.get(i));
if(i < list.size()-1) { if (i < list.size() - 1) {
b.append(","); b.append(",");
} }
} }
@@ -24,7 +24,10 @@ import net.h31ix.anticheat.manage.User;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import java.sql.*; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Database { public class Database {
@@ -126,12 +129,12 @@ public class Database {
connection.setAutoCommit(false); connection.setAutoCommit(false);
eventTask = Bukkit.getScheduler().runTaskTimerAsynchronously(AntiCheat.getPlugin(), new Runnable(){ eventTask = Bukkit.getScheduler().runTaskTimerAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override @Override
public void run() { public void run() {
flushEvents(); flushEvents();
} }
}, eventInterval* 60 * 20, eventInterval * 60 * 20); }, eventInterval * 60 * 20, eventInterval * 60 * 20);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
@@ -179,7 +182,7 @@ public class Database {
} }
public void cleanEvents() { public void cleanEvents() {
Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable(){ Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
@@ -32,16 +32,16 @@ import java.util.SortedMap;
* Where CONDITION is a statement that will be evaluated as either <b>TRUE</b> or <b>FALSE</b> * Where CONDITION is a statement that will be evaluated as either <b>TRUE</b> or <b>FALSE</b>
* and the results are actions to be taken for either outcome. * and the results are actions to be taken for either outcome.
* <br /><br /> * <br /><br />
* * <p/>
* Should you need additional actions, the system will recursively parse the following values and handle appropriately. * Should you need additional actions, the system will recursively parse the following values and handle appropriately.
* <br /> * <br />
* For instance, (CONDITION) ? (TRUE RESULT) : (CONDITION) ? (TRUE RESULT) : (FALSE RESULT) is a valid rule * For instance, (CONDITION) ? (TRUE RESULT) : (CONDITION) ? (TRUE RESULT) : (FALSE RESULT) is a valid rule
* <br /><br /> * <br /><br />
* * <p/>
* An example of a valid Conditional Rule:<br /> * An example of a valid Conditional Rule:<br />
* Check_SPIDER > 0 ? Player.KICK : null<br /> * Check_SPIDER > 0 ? Player.KICK : null<br />
* <i>The above statement would read 'If the spider check has been failed over zero times, kick the player. Otherwise, do nothing.'</i> * <i>The above statement would read 'If the spider check has been failed over zero times, kick the player. Otherwise, do nothing.'</i>
* * <p/>
* To see syntax for variables and functions that you may use, see {@link net.h31ix.anticheat.util.rule.Rule} * To see syntax for variables and functions that you may use, see {@link net.h31ix.anticheat.util.rule.Rule}
*/ */
public class ConditionalRule extends Rule { public class ConditionalRule extends Rule {
@@ -62,11 +62,11 @@ public class ConditionalRule extends Rule {
try { try {
// Load all variables // Load all variables
SortedMap<String, Object> map = getVariables(user, type); SortedMap<String, Object> map = getVariables(user, type);
for(String key : map.keySet()) { for (String key : map.keySet()) {
engine.put(key, map.get(key)); engine.put(key, map.get(key));
} }
boolean value = (Boolean)engine.eval(getString().split(TRUE_DELIMITER)[0]); boolean value = (Boolean) engine.eval(getString().split(TRUE_DELIMITER)[0]);
// Yo dawg I heard you like conditionals... // Yo dawg I heard you like conditionals...
String next = value ? getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[0] : getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[1]; String next = value ? getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[0] : getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[1];
@@ -80,14 +80,14 @@ public class ConditionalRule extends Rule {
private void execute(String string, User user, CheckType type) { private void execute(String string, User user, CheckType type) {
// If we're told to do nothing // If we're told to do nothing
if(string.equalsIgnoreCase("null") || string.equalsIgnoreCase("none")) return; if (string.equalsIgnoreCase("null") || string.equalsIgnoreCase("none")) return;
// If this string is a new conditional statement // If this string is a new conditional statement
if(TYPE.matches(string)) { if (TYPE.matches(string)) {
new ConditionalRule(string).check(user, type); new ConditionalRule(string).check(user, type);
} else if(isVariableSet(string)) { } else if (isVariableSet(string)) {
setVariable(string.split("=")[0], string.split("=")[1], user); setVariable(string.split("=")[0], string.split("=")[1], user);
} else if(isFunction(string)) { } else if (isFunction(string)) {
doFunction(string, type, user); doFunction(string, type, user);
} }
} }
@@ -24,37 +24,39 @@ import net.h31ix.anticheat.manage.User;
import net.h31ix.anticheat.util.Utilities; import net.h31ix.anticheat.util.Utilities;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.util.*; import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
/** /**
* A rule is a scriptable function used to customize the functions of AntiCheat<br /> * A rule is a scriptable function used to customize the functions of AntiCheat<br />
* Rules are executed whenever a user's level rises.<br /><br /> * Rules are executed whenever a user's level rises.<br /><br />
* * <p/>
* There are various variables you can use to interact with AntiCheat through your rules<br /> * There are various variables you can use to interact with AntiCheat through your rules<br />
* Variables are denoted with the type followed by a _ followed by the variable name.<br /> * Variables are denoted with the type followed by a _ followed by the variable name.<br />
* For instance, a variable coming from a user who has used FLY 5 times and is checked by a rule containing 'Check_FLY' will produce a value of 5. * For instance, a variable coming from a user who has used FLY 5 times and is checked by a rule containing 'Check_FLY' will produce a value of 5.
* <br /><br /> * <br /><br />
* * <p/>
* <b>Types of variables:</b><br /> * <b>Types of variables:</b><br />
* - Check: Contains all valid checks as listed in {@link net.h31ix.anticheat.manage.CheckType}, and will return the number of times this user has failed the given check<br /> * - Check: Contains all valid checks as listed in {@link net.h31ix.anticheat.manage.CheckType}, and will return the number of times this user has failed the given check<br />
* - Player: Contains LEVEL, the player's current level and CHECK, the check that was just failed * - Player: Contains LEVEL, the player's current level and CHECK, the check that was just failed
* <br /><br /> * <br /><br />
* * <p/>
* There are also functions you can use to execute an action within AntiCheat<br /> * There are also functions you can use to execute an action within AntiCheat<br />
* Functions are denoted with the type followed by a period followed by the function name.<br /> * Functions are denoted with the type followed by a period followed by the function name.<br />
* For instance, a rule containing Player.KICK will result in the user being kicked.<br /> * For instance, a rule containing Player.KICK will result in the user being kicked.<br />
* <br /><br /> * <br /><br />
* * <p/>
* <b>Types of functions:</b><br /> * <b>Types of functions:</b><br />
* - Player: RESET, KICK, BAN, COMMAND[command] OR COMMAND[command1;command2] * - Player: RESET, KICK, BAN, COMMAND[command] OR COMMAND[command1;command2]
* <i>- when using commands <b>&player</b> will be replaced by the player name, <b>&world</b> will be replaced by the player's world, * <i>- when using commands <b>&player</b> will be replaced by the player name, <b>&world</b> will be replaced by the player's world,
* and <b>&check</b> will be replaced by the check that caused this rule to be run</i><br /> * and <b>&check</b> will be replaced by the check that caused this rule to be run</i><br />
* <br /><br /> * <br /><br />
* * <p/>
* The Rule class itself is not an functional rule setup, * The Rule class itself is not an functional rule setup,
* it is inherited and made functional by different implementations of the rule parser.<br /> * it is inherited and made functional by different implementations of the rule parser.<br />
* The only current Rule implementation is the {@link net.h31ix.anticheat.util.rule.ConditionalRule} * The only current Rule implementation is the {@link net.h31ix.anticheat.util.rule.ConditionalRule}
*
*/ */
public class Rule { public class Rule {
@@ -106,12 +108,12 @@ public class Rule {
* @return an instance of Rule if an implementation exists to handle this rule, null if none are found * @return an instance of Rule if an implementation exists to handle this rule, null if none are found
*/ */
public static Rule load(String string) { public static Rule load(String string) {
for(Type type : Type.values()) { for (Type type : Type.values()) {
if(type.matches(string)) { if (type.matches(string)) {
try { try {
Class c = Class.forName(type.getInstance()); Class c = Class.forName(type.getInstance());
Constructor con = c.getConstructor(String.class); Constructor con = c.getConstructor(String.class);
return (Rule)con.newInstance(string); return (Rule) con.newInstance(string);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
@@ -135,10 +137,10 @@ public class Rule {
protected SortedMap<String, Object> getVariables(User user, CheckType type) { protected SortedMap<String, Object> getVariables(User user, CheckType type) {
SortedMap<String, Object> map = new TreeMap<String, Object>(); SortedMap<String, Object> map = new TreeMap<String, Object>();
map.put("player_check", type.name().toLowerCase()); map.put("player_check", type.name().toLowerCase());
map.put("player_level", user.getLevel()); map.put("player_level", user.getLevel());
for(CheckType t : CheckType.values()) { for (CheckType t : CheckType.values()) {
map.put("check_"+t.name().toLowerCase(), t.getUses(user.getName())); map.put("check_" + t.name().toLowerCase(), t.getUses(user.getName()));
} }
return map; return map;
} }
@@ -146,13 +148,13 @@ public class Rule {
protected void setVariable(String variable, String value, User user) { protected void setVariable(String variable, String value, User user) {
// Only variable that can be set for now, may change in the future // Only variable that can be set for now, may change in the future
// others wouldn't make any sense to set // others wouldn't make any sense to set
if(variable.equals("player_level") && Utilities.isInt(value)) { if (variable.equals("player_level") && Utilities.isInt(value)) {
user.setLevel(Integer.parseInt(value)); user.setLevel(Integer.parseInt(value));
} }
} }
protected void doFunction(String text, CheckType type, User user) { protected void doFunction(String text, CheckType type, User user) {
if(text.toLowerCase().startsWith("player")) { if (text.toLowerCase().startsWith("player")) {
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);
@@ -170,6 +172,6 @@ public class Rule {
@Override @Override
public String toString() { public String toString() {
return type+"{"+string+"}"; return type + "{" + string + "}";
} }
} }
@@ -38,7 +38,9 @@ public class XRayListener implements Listener {
public void onBlockBreak(BlockBreakEvent event) { public void onBlockBreak(BlockBreakEvent event) {
if (config.getConfig().logXRayStats.getValue()) { if (config.getConfig().logXRayStats.getValue()) {
Player p = event.getPlayer(); Player p = event.getPlayer();
if (p.getGameMode() == GameMode.CREATIVE && !config.getConfig().trackCreativeXRay.getValue()) { 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();
@@ -18,12 +18,13 @@
package net.h31ix.anticheat.xray; package net.h31ix.anticheat.xray;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
public class XRayTracker { public class XRayTracker {
private Map<String, Integer> diamond = new HashMap<String, Integer>(); private Map<String, Integer> diamond = new HashMap<String, Integer>();
@@ -18,6 +18,7 @@
package net.h31ix.anticheat.util; package net.h31ix.anticheat.util;
import org.bukkit.Material; import org.bukkit.Material;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@@ -26,8 +27,8 @@ public class BlockHardnessTest {
@Test @Test
public void verifyExistence() { public void verifyExistence() {
for(Material m : Material.values()) { for (Material m : Material.values()) {
if(!BlockHardness.hasBlockHardness(m) && m.isBlock() && m != Material.AIR && m != Material.BEDROCK) { if (!BlockHardness.hasBlockHardness(m) && m.isBlock() && m != Material.AIR && m != Material.BEDROCK) {
Assert.fail("Material " + m + " is not accounted for by BlockHardness"); Assert.fail("Material " + m + " is not accounted for by BlockHardness");
} }
} }