Refactor package to new namespace

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

No files matched your search

@@ -0,0 +1,213 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import org.bukkit.Material;
public enum BlockHardness {
STONE(1.50D),
GRASS(0.60D),
DIRT(0.50D),
COBBLESTONE(2.00D),
WOOD(2.00D),
SAPLING(0.00D),
WATER(100.00D),
STATIONARY_WATER(100.00D),
LAVA(0.00D),
STATIONARY_LAVA(100.00D),
SAND(0.50D),
GRAVEL(0.60D),
GOLD_ORE(3.00D),
IRON_ORE(3.00D),
COAL_ORE(3.00D),
LOG(2.00D),
LEAVES(0.20D),
SPONGE(0.60D),
GLASS(0.30D),
LAPIS_ORE(3.00D),
LAPIS_BLOCK(3.00D),
DISPENSER(3.50D),
DROPPER(3.50D),
SANDSTONE(0.80D),
NOTE_BLOCK(0.80D),
BED(0.20D),
RAILS(0.70D),
DETECTOR_RAIL(0.70D),
POWERED_RAIL(0.70D),
ACTIVATOR_RAIL(0.70D),
WEB(4.00D),
LONG_GRASS(0.00D),
DEAD_BUSH(0.00D),
WOOL(0.80D),
YELLOW_FLOWER(0.00D),
RED_ROSE(0.00D),
BROWN_MUSHROOM(0.00D),
RED_MUSHROOM(0.00D),
GOLD_BLOCK(3.00D),
IRON_BLOCK(5.00D),
DOUBLE_STEP(2.00D),
STEP(2.00D),
BRICK(2.00D),
TNT(0.00D),
BOOKSHELF(1.50D),
MOSSY_COBBLESTONE(2.00D),
OBSIDIAN(50.00D),
TORCH(0.00D),
FIRE(0.00D),
MOB_SPAWNER(5.00D),
CHEST(2.50D),
TRAPPED_CHEST(2.50D),
REDSTONE_WIRE(0.00D),
DIAMOND_ORE(3.00D),
DIAMOND_BLOCK(5.00D),
WORKBENCH(2.50D),
SOIL(0.60D),
FURNACE(3.50D),
BURNING_FURNACE(3.50D),
WOODEN_DOOR(3.00D),
LADDER(0.40D),
LEVER(0.50D),
IRON_DOOR_BLOCK(5.00D),
HOPPER(2.00D),
STONE_PLATE(0.50D),
WOOD_PLATE(0.50D),
GOLD_PLATE(0.50D),
IRON_PLATE(0.50D),
QUARTZ_BLOCK(0.80D),
QUARTZ_ORE(3.00D),
QUARTZ_STAIRS(0.80D),
REDSTONE_BLOCK(5.00D),
REDSTONE_ORE(3.00D),
GLOWING_REDSTONE_ORE(3.00D),
REDSTONE_TORCH_OFF(0.00D),
REDSTONE_TORCH_ON(0.00D),
REDSTONE_COMPARATOR_OFF(0.00D),
REDSTONE_COMPARATOR_ON(0.00D),
DAYLIGHT_DETECTOR(0.20D),
STONE_BUTTON(0.50D),
SNOW(0.10D),
ICE(0.50D),
SNOW_BLOCK(0.20D),
CACTUS(0.40D),
CLAY(0.60D),
HARD_CLAY(1.25D),
STAINED_CLAY(1.25D),
SUGAR_CANE_BLOCK(0.00D),
JUKEBOX(2.00D),
FENCE(2.00D),
NETHERRACK(0.40D),
SOUL_SAND(0.50D),
GLOWSTONE(0.30D),
PORTAL(-1.00D),
CAKE_BLOCK(0.50D),
LOCKED_CHEST(0.00D),
TRAP_DOOR(3.00D),
MONSTER_EGGS(0.750D),
SMOOTH_BRICK(1.50D),
IRON_FENCE(5.00D),
THIN_GLASS(0.30D),
PUMPKIN_STEM(0.00D),
MELON_STEM(0.00D),
VINE(0.20D),
FENCE_GATE(2.00D),
MYCEL(0.60D),
WATER_LILY(0.00D),
NETHER_BRICK(2.00D),
NETHER_FENCE(2.00D),
ENCHANTMENT_TABLE(5.00D),
BREWING_STAND(0.50D),
CAULDRON(2.00D),
ENDER_PORTAL(-1.00D),
ENDER_PORTAL_FRAME(-1.00D),
DRAGON_EGG(3.00D),
REDSTONE_LAMP_OFF(0.30D),
REDSTONE_LAMP_ON(0.30D),
WOOD_DOUBLE_STEP(2.00D),
WOOD_STEP(2.00D),
COCOA(0.20D),
EMERALD_ORE(3.00D),
ENDER_CHEST(22.50D),
EMERALD_BLOCK(5.00D),
FLOWER_POT(0.00D),
WOOD_BUTTON(0.50D),
ANVIL(5.00D),
HUGE_MUSHROOM_1(0.20D),
HUGE_MUSHROOM_2(0.20D),
BED_BLOCK(0.20D),
WOOD_STAIRS(2.00D),
COBBLESTONE_STAIRS(2.00D),
BRICK_STAIRS(2.00D),
SMOOTH_STAIRS(2.00D),
NETHER_BRICK_STAIRS(2.00D),
SANDSTONE_STAIRS(2.00D),
SPRUCE_WOOD_STAIRS(2.00D),
BIRCH_WOOD_STAIRS(2.00D),
JUNGLE_WOOD_STAIRS(2.00D),
COMMAND(0.00D),
BEACON(3.00D),
COBBLE_WALL(2.00D),
CROPS(0.00D),
CARROT(0.00D),
POTATO(0.00D),
SKULL(1.00D),
NETHER_WARTS(0.00D),
SIGN_POST(1.00D),
WALL_SIGN(1.00D),
PUMPKIN(1.00D),
JACK_O_LANTERN(1.00D),
DIODE_BLOCK_ON(0.00D),
DIODE_BLOCK_OFF(0.00D),
MELON_BLOCK(1.00D),
ENDER_STONE(3.00D),
TRIPWIRE(0.00D),
TRIPWIRE_HOOK(0.00D),
HAY_BLOCK(0.50D),
CARPET(0.10D),
COAL_BLOCK(5.00D),
PISTON_BASE(0.70D),
PISTON_EXTENSION(0.70D),
PISTON_MOVING_PIECE(0.70D),
PISTON_STICKY_BASE(0.70D);
Material mat;
double hardness;
BlockHardness(double hard) {
mat = Material.getMaterial(name());
hardness = hard;
}
public static double getBlockHardness(Material m) {
BlockHardness h = getHardness(m);
return h == null ? 0D : h.hardness;
}
public static boolean hasBlockHardness(Material m) {
return getHardness(m) != null;
}
public static BlockHardness getHardness(Material m) {
for (BlockHardness e : BlockHardness.values()) {
if (e.mat.equals(m)) {
return e;
}
}
return null;
}
}
@@ -0,0 +1,239 @@
// Not production code yet. Still experimental and needs a lot of work.
package net.gravitydevelopment.anticheat.util;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
public class Calibrator implements Listener {
private final Player player;
private int step = 0;
private static final int TOTAL = 30;
private long lastLong;
private int lastInt;
private int lastDouble;
private long[] longs = new long[10];
private double[] doubles = new double[10];
private int[] ints = new int[10];
private int times = 0;
// Value-specific calculations
private long projectileTime;
private long dropItemTime;
private long punchAvg;
private double blockBreakMax;
private double blockPlaceMax;
public Calibrator(Player player) {
this.player = player;
player.sendMessage(ChatColor.GREEN + "----You have entered calibration mode.----");
// Wait for listener to be registered and calibrate method called.
}
public void calibrate() {
switch (step) {
case 0:
sendStep();
player.getInventory().setItemInHand(new ItemStack(Material.BOW));
player.getInventory().addItem(new ItemStack(Material.ARROW, 64));
player.sendMessage("Fire arrows as fast as possible (don't pull all the way back)");
break;
case 2:
player.getInventory().clear();
player.getInventory().setItemInHand(new ItemStack(Material.DIRT, 64));
player.sendMessage("Drop items as fast as possible.");
/*
* case 0: sendStep(); player.sendMessage("Spam the left mouse button as fast as possible."); break; case 2: player.setGameMode(GameMode.CREATIVE); player.sendMessage("Break blocks from as far away as you can possibly get from them."); break; case 3:
* player.sendMessage("Place blocks from as far away as you can possibly get from them."); break;
*/
}
}
private int getLongCount() {
int fill = 0;
for (long l : longs) {
if (l != 0) {
fill++;
}
}
return fill;
}
private int getDoubleCount() {
int fill = 0;
for (double d : doubles) {
if (d != 0) {
fill++;
}
}
return fill;
}
private void clear() {
for (int i = 0; i < longs.length; i++) {
longs[i] = 0;
}
for (int i = 0; i < ints.length; i++) {
ints[i] = 0;
}
for (int i = 0; i < doubles.length; i++) {
doubles[i] = 0;
}
lastInt = 0;
lastDouble = 0;
lastLong = 0;
times = 0;
}
private void sendStep() {
step++;
player.sendMessage(ChatColor.GREEN + "Step " + step + "/" + TOTAL);
}
// Find the average time it takes to do a task
private long getAvgLong() {
int count = getLongCount();
if (count < 10) {
if (lastLong == 0) {
lastLong = System.currentTimeMillis();
} else {
longs[count] = System.currentTimeMillis() - lastLong;
lastLong = System.currentTimeMillis();
}
} else {
long avg = 0;
for (long l : longs) {
avg += l;
}
clear();
avg /= 10;
player.sendMessage(ChatColor.AQUA + "Done. Average calculated at " + ChatColor.WHITE + avg);
sendStep();
calibrate();
return avg;
}
return -1;
}
// Find the maximum time it takes to do a task
private double getMaxDouble(double length) {
int count = getDoubleCount();
if (count < 10) {
doubles[count] = length;
} else {
double max = 0;
for (double d : doubles) {
if (max == 0 || d > max) {
max = d;
}
}
clear();
player.sendMessage(ChatColor.AQUA + "Done. Maximum calculated at " + ChatColor.WHITE + max);
sendStep();
calibrate();
return max;
}
return -1;
}
// Get the absolute time it takes to do something X times
private long getAbsoluteLong() {
int count = getLongCount();
if (count < 10) {
if (lastLong == 0) {
lastLong = System.currentTimeMillis();
} else {
longs[count] = System.currentTimeMillis();
lastLong = System.currentTimeMillis();
}
} else {
long val = longs[9] - longs[0];
clear();
player.sendMessage(ChatColor.AQUA + "Done. Value calculated at " + ChatColor.WHITE + val);
sendStep();
calibrate();
return val;
}
return -1;
}
// Begin event listeners
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event) {
if (event.getPlayer() == player) {
if (step == 2) {
long v = getAbsoluteLong();
if (v != -1) {
dropItemTime = v;
}
}
}
}
@EventHandler
public void onEntityShootBow(EntityShootBowEvent event) {
if (event.getEntity() instanceof Player && ((Player) event.getEntity()) == player) {
if (step == 1) {
long v = getAbsoluteLong();
if (v != -1) {
projectileTime = v;
}
}
}
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getPlayer() == player) {
if (step == -1) {
long v = getAvgLong();
if (v != -1) {
punchAvg = v;
}
} else if (step == 1) {
}
}
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
if (event.getPlayer() == player) {
if (step == -1) {
double lengthX = Math.abs(event.getBlock().getX() - event.getPlayer().getLocation().getX());
double lengthZ = Math.abs(event.getBlock().getZ() - event.getPlayer().getLocation().getZ());
double v = getMaxDouble(lengthX >= lengthZ ? lengthX : lengthZ);
if (v != -1) {
blockBreakMax = v;
}
}
}
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
if (event.getPlayer() == player) {
if (step == -1) {
double lengthX = Math.abs(event.getBlock().getX() - event.getPlayer().getLocation().getX());
double lengthZ = Math.abs(event.getBlock().getZ() - event.getPlayer().getLocation().getZ());
double v = getMaxDouble(lengthX >= lengthZ ? lengthX : lengthZ);
if (v != -1) {
blockPlaceMax = v;
}
}
}
}
}
@@ -0,0 +1,61 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
public class CheckResult {
public enum Result {
PASSED, FAILED
}
private Result result;
private String message;
private int data;
public CheckResult(Result result, String message, int data) {
this(result, message);
this.data = data;
}
public CheckResult(Result result, String message) {
this(result);
this.message = message;
}
public CheckResult(Result result) {
this.result = result;
}
public boolean failed() {
return result == Result.FAILED;
}
public String getMessage() {
return message;
}
public Result getResult() {
return result;
}
public int getData() {
return data;
}
}
@@ -0,0 +1,59 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import org.bukkit.Location;
public class Distance {
private final double l1Y;
private final double l2Y;
private final double XDiff;
private final double YDiff;
private final double ZDiff;
public Distance(Location from, Location to) {
l1Y = to.getY();
l2Y = from.getY();
XDiff = Math.abs(to.getX() - from.getX());
ZDiff = Math.abs(to.getZ() - from.getZ());
YDiff = Math.abs(l1Y - l2Y);
}
public double fromY() {
return l2Y;
}
public double toY() {
return l1Y;
}
public double getXDifference() {
return XDiff;
}
public double getZDifference() {
return ZDiff;
}
public double getYDifference() {
return YDiff;
}
}
@@ -0,0 +1,36 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public class FileFormatter extends Formatter {
private static final DateFormat FORMAT = new SimpleDateFormat("h:mm:ss");
private static final String LINE_SEP = System.getProperty("line.separator");
@Override
public String format(LogRecord record) {
StringBuilder output = new StringBuilder().append("[").append(record.getLevel()).append('|').append(FORMAT.format(new Date(record.getMillis()))).append("]: ").append(record.getMessage()).append(' ').append(LINE_SEP);
return output.toString();
}
}
@@ -0,0 +1,94 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import net.gravitydevelopment.anticheat.AntiCheat;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Level {
private String name;
private int value;
private ChatColor color = ChatColor.RED;
private List<String> actions = new ArrayList<String>();
public Level(String name, int value, String color, List<String> actions) {
this.name = name;
this.value = value;
this.actions = actions;
ChatColor c = ChatColor.valueOf(color);
if (c == null) {
AntiCheat.getPlugin().getLogger().warning("Event '" + name + "' was initialized with the color '" + color + "' which is invalid.");
AntiCheat.getPlugin().getLogger().warning("This event will not run properly. See http://jd.bukkit.org/apidocs/org/bukkit/ChatColor.html#enum_constant_summary for a list of valid colors");
} else {
this.color = c;
}
}
public void setValue(int value) {
this.value = value;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public ChatColor getColor() {
return color;
}
public List<String> getActions() {
return actions;
}
public static Level load(String string) {
try {
if (string.split(":").length == 4) {
string = Utilities.removeWhitespace(string);
String name = string.split(":")[0];
int level = Integer.parseInt(string.split(":")[1]);
String color = string.split(":")[2];
List<String> actions = Arrays.asList(string.split(":")[3].split(","));
return new Level(name, level, color, actions);
} else {
throw new Exception();
}
} catch (Exception ex) {
AntiCheat.getPlugin().getLogger().warning("An event was initialized with an invalid string: '" + string + "'");
AntiCheat.getPlugin().getLogger().warning("The proper format is: 'name : threshold : color : action' such as 'High : 50 : RED : KICK'");
AntiCheat.getPlugin().getLogger().warning("This event will NOT run. (" + ex.getMessage() + ")");
return null;
}
}
@Override
public String toString() {
return name + " : " + value + " : " + color.name() + " : " + Utilities.listToCommaString(actions);
}
}
@@ -0,0 +1,216 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import net.gravitydevelopment.anticheat.AntiCheat;
import net.gravitydevelopment.anticheat.config.files.Magic;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class PastebinReport {
private StringBuilder report = new StringBuilder();
private String url = "";
private Date date = new Date();
private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd kk:mm Z");
public PastebinReport(CommandSender cs) {
Player player = null;
if (cs instanceof Player) {
player = (Player) cs;
}
createReport(player);
try {
writeReport();
} catch (IOException e) {
}
postReport();
}
public PastebinReport(CommandSender cs, Player tp) {
createReport(tp);
try {
writeReport();
} catch (IOException e) {
}
postReport();
}
public String getURL() {
return url;
}
private void appendPermissionsTester(Player player) {
if (player == null) {
append("No player defined.");
return;
}
for (Permission node : Permission.values()) {
report.append(player.getName() + ": " + node.toString() + " " + node.get(player));
if (node.get(player) && !node.whichPermission(player).equals(node.toString())) {
report.append(" (Applied by " + node.whichPermission(player) + ")");
}
report.append('\n');
}
}
private void createReport(Player player) {
if (Bukkit.getPluginManager().getPlugin("NoCheatPlus") != null) {
append("------------ WARNING! ------------");
append("This report was run with NoCheatPlus enabled. Results may be inaccurate." + '\n');
}
append("------------ AntiCheat Report - " + format.format(date) + " ------------");
appendSystemInfo();
append("------------Last 30 logs------------");
appendLogs();
append("------------Permission Tester------------");
appendPermissionsTester(player);
append("------------Event Chains------------");
appendEventHandlers();
append("------------Magic Diff------------");
appendMagicDiff();
append("-----------End Of Report------------");
}
private void appendLogs() {
List<String> logs = AntiCheat.getManager().getLastLogs();
if (logs.size() == 0) {
append("No recent logs.");
return;
}
for (String log : logs) {
append(log);
}
}
private void appendSystemInfo() {
Runtime runtime = Runtime.getRuntime();
append("AntiCheat Version: " + AntiCheat.getVersion() + (AntiCheat.isUpdated() ? "" : " (OUTDATED)"));
append("Server Version: " + Bukkit.getVersion());
append("Server Implementation: " + Bukkit.getName());
append("Server ID: " + Bukkit.getServerId());
append("Java Version: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version"));
append("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
append("Free Memory: " + runtime.freeMemory() / 1024 / 1024 + "MB");
append("Max Memory: " + runtime.maxMemory() / 1024 / 1024 + "MB");
append("Total Memory: " + runtime.totalMemory() / 1024 / 1024 + "MB");
append("Online Mode: " + String.valueOf(Bukkit.getOnlineMode()).toUpperCase());
append("Players: " + Bukkit.getOnlinePlayers().length + "/" + Bukkit.getMaxPlayers());
append("Plugin Count: " + Bukkit.getPluginManager().getPlugins().length);
}
private void appendMagicDiff() {
// This is hacky, and I like it
Magic magic = AntiCheat.getManager().getConfiguration().getMagic();
FileConfiguration file = magic.getDefaultConfigFile();
append("Version: " + magic.getVersion());
boolean changed = false;
for (Field field : Magic.class.getFields()) {
Object defaultValue = file.get(field.getName());
try {
Field value = magic.getClass().getDeclaredField(field.getName());
boolean x = false;
String s1 = value.get(magic).toString();
String s2 = defaultValue.toString();
if (!s1.equals(s2) && !s1.equals(s2 + ".0")) {
changed = true;
append(field.getName() + ": " + s1 + " (Default: " + s2 + ")");
} else {
}
} catch (NoSuchFieldException ex) {
} catch (IllegalAccessException ex) {
}
}
if (!changed) {
append("No changes from default.");
}
}
private void appendEventHandlers() {
report.append(AntiCheat.getManager().getEventChainReport());
}
private void writeReport() throws IOException {
File f = new File(AntiCheat.getPlugin().getDataFolder() + "/report.txt");
FileWriter r = new FileWriter(f);
BufferedWriter writer = new BufferedWriter(r);
writer.write(report.toString());
writer.close();
}
private void postReport() {
try {
URL urls = new URL("http://pastebin.com/api/api_post.php");
HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("POST");
conn.addRequestProperty("Content-type", "application/x-www-form-urlencoded");
conn.setInstanceFollowRedirects(false);
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
out.write(("api_option=paste" + "&api_dev_key=" + URLEncoder.encode("c0616def494dcb5b7632304f8c52c0f1", "utf-8") + "&api_paste_code=" + URLEncoder.encode(report.toString(), "utf-8") + "&api_paste_private=" + URLEncoder.encode("1", "utf-8") + "&api_paste_name=" + URLEncoder.encode("", "utf-8") + "&api_paste_expire_date=" + URLEncoder.encode("1M", "utf-8") + "&api_paste_format=" + URLEncoder.encode("text", "utf-8") + "&api_user_key=" + URLEncoder.encode("", "utf-8")).getBytes());
out.flush();
out.close();
if (conn.getResponseCode() == 200) {
InputStream receive = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(receive));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
response.append("\r\n");
}
reader.close();
String result = response.toString().trim();
if (!result.contains("http://")) {
url = "Failed to post. Check report.txt";
} else {
url = result.trim();
}
} else {
url = "Failed to post. Check report.txt";
}
} catch (Exception e) {
url = "Failed to post. Check report.txt";
}
}
private void append(String s) {
report.append(s + '\n');
}
}
@@ -0,0 +1,90 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import org.bukkit.command.CommandSender;
public enum Permission {
/* Check Nodes */
CHECK_ZOMBE_FLY,
CHECK_ZOMBE_NOCLIP,
CHECK_ZOMBE_CHEAT,
CHECK_FLY,
CHECK_WATERWALK,
CHECK_NOSWING,
CHECK_FASTBREAK,
CHECK_FASTPLACE,
CHECK_SPAM,
CHECK_SPRINT,
CHECK_SNEAK,
CHECK_SPEED,
CHECK_VCLIP,
CHECK_SPIDER,
CHECK_NOFALL,
CHECK_FASTBOW,
CHECK_FASTEAT,
CHECK_FASTHEAL,
CHECK_FORCEFIELD,
CHECK_XRAY,
CHECK_LONGREACH,
CHECK_FASTPROJECTILE,
CHECK_ITEMSPAM,
CHECK_VISUAL,
CHECK_FASTINVENTORY,
CHECK_FASTANIMATION,
CHECK_AUTOTOOL,
/* System Nodes */
SYSTEM_LOG,
SYSTEM_XRAY,
SYSTEM_RESET,
SYSTEM_SPY,
SYSTEM_HELP,
SYSTEM_UPDATE,
SYSTEM_REPORT,
SYSTEM_ALERT,
SYSTEM_CALIBRATE,
SYSTEM_DEBUG,
SYSTEM_RELOAD;
private static final String PERMISSION_ALL = "anticheat.*";
public boolean get(CommandSender cs) {
return cs.hasPermission(toString()) || cs.hasPermission(getBase()) || cs.hasPermission(PERMISSION_ALL);
}
public String getBase() {
return "anticheat." + this.name().toLowerCase().split("_")[0] + ".*";
}
public String whichPermission(CommandSender cs) {
for (String s : new String[]{toString(), getBase(), PERMISSION_ALL}) {
if (cs.hasPermission(s)) {
return s;
}
}
return null;
}
@Override
public String toString() {
return "anticheat." + this.name().toLowerCase().replace("_", ".");
}
}
@@ -0,0 +1,45 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import org.bukkit.Location;
public class SpyState {
private boolean allowFlight;
private boolean flying;
private Location location;
public SpyState(boolean allowFlight, boolean flying, Location location) {
this.allowFlight = allowFlight;
this.flying = flying;
this.location = location;
}
public boolean getAllowFlight() {
return this.allowFlight;
}
public boolean getFlying() {
return this.flying;
}
public Location getLocation() {
return this.location;
}
}
@@ -0,0 +1,48 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import org.bukkit.Material;
public enum ToolHardness {
// NOTHING(null, 1.5)
WOOD(0.75D),
STONE(0.40D),
IRON(0.25D),
DIAMOND(0.20D),
SHEARS(0.55D),
GOLD(0.15D);
double hardness;
ToolHardness(double hard) {
hardness = hard;
}
public static double getToolHardness(Material tool) {
for (ToolHardness e : ToolHardness.values()) {
if (tool.name().contains(e.name())) {
return e.hardness;
}
}
return 1.50D;
}
}
@@ -0,0 +1,563 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util;
import net.gravitydevelopment.anticheat.AntiCheat;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.NumberConversions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class Utilities {
private static final List<Material> INSTANT_BREAK = new ArrayList<Material>();
private static final List<Material> FOOD = new ArrayList<Material>();
private static final List<Material> INTERACTABLE = new ArrayList<Material>();
private static final Map<Material, Material> COMBO = new HashMap<Material, Material>();
public static final String SPY_METADATA = "ac-spydata";
/**
* Send a hack level alert to players and console
*
* @param message List of strings to send as the alert
*/
public static void alert(List<String> message) {
for (Player player : Bukkit.getOnlinePlayers()) {
if (Permission.SYSTEM_ALERT.get(player)) {
for (String msg : message) {
player.sendMessage(msg);
}
}
}
if (AntiCheat.getManager().getConfiguration().getConfig().logToConsole.getValue()) {
for (String msg : message) {
AntiCheat.getManager().log(msg);
}
}
if (AntiCheat.getManager().getConfiguration().getConfig().fileLogLevel.getValue() != 0) {
for (String msg : message) {
AntiCheat.getManager().log(msg, 1);
}
}
}
/**
* Determine whether a player cannot stand on or around the given block
*
* @param block the block to check
* @return true if the player should be unable to stand here
*/
public static boolean cantStandAt(Block block) {
return !canStand(block) && cantStandClose(block) && cantStandFar(block);
}
/**
* Determine whether a player should be unable to stand at a given location
*
* @param location the location to check
* @return true if the player should be unable to stand here
*/
public static boolean cantStandAtExp(Location location) {
return cantStandAt(new Location(location.getWorld(), fixXAxis(location.getX()), location.getY() - 0.01D, location.getBlockZ()).getBlock());
}
/**
* Determine whether cannot stand on the block's immediately surroundings (North, East, South, West)
*
* @param block the block to check
* @return true if a player cannot stand in the immediate vicinity
*/
public static boolean cantStandClose(Block block) {
return !canStand(block.getRelative(BlockFace.NORTH)) && !canStand(block.getRelative(BlockFace.EAST)) && !canStand(block.getRelative(BlockFace.SOUTH)) && !canStand(block.getRelative(BlockFace.WEST));
}
/**
* Determine whether cannot stand on the block's outer surroundings
*
* @param block the block to check
* @return true if a player cannot stand in areas further away from the block
*/
public static boolean cantStandFar(Block block) {
return !canStand(block.getRelative(BlockFace.NORTH_WEST)) && !canStand(block.getRelative(BlockFace.NORTH_EAST)) && !canStand(block.getRelative(BlockFace.SOUTH_WEST)) && !canStand(block.getRelative(BlockFace.SOUTH_EAST));
}
/**
* Determine whether a player can stand on the given block
*
* @param block the block to check
* @return true if the player can stand here
*/
public static boolean canStand(Block block) {
return !(block.isLiquid() || block.getType() == Material.AIR);
}
/**
* Determine whether a player is fully submerged in water
*
* @param player the player's location
* @return true if the player is fully in the water
*/
public static boolean isFullyInWater(Location player) {
double touchedX = fixXAxis(player.getX());
// Yes, this doesn't make sense, but it's supposed to fix some false positives in water walk.
// Think of it as 2 negatives = a positive :)
if (!(new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() && !(new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()).getBlock()).isLiquid()) {
return true;
}
return (new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() && (new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()).getBlock()).isLiquid();
}
/**
* Fixes a player's X position to determine the block they are on, even if they're on the edge
*
* @param x player's x position
* @return fixed x position
*/
public static double fixXAxis(double x) {
/* For Z axis, just use Math.round(xaxis); */
double touchedX = x;
double rem = touchedX - Math.round(touchedX) + 0.01D;
if (rem < 0.30D) {
touchedX = NumberConversions.floor(x) - 1;
}
return touchedX;
}
/**
* Determine if the player is hovering over water with the given limit
*
* @param player the player's location
* @param blocks max blocks to check
* @return true if the player is hovering over water
*/
public static boolean isHoveringOverWater(Location player, int blocks) {
for (int i = player.getBlockY(); i > player.getBlockY() - blocks; i--) {
Block newloc = (new Location(player.getWorld(), player.getBlockX(), i, player.getBlockZ())).getBlock();
if (newloc.getType() != Material.AIR) {
return newloc.isLiquid();
}
}
return false;
}
/**
* Determine if the player is hovering over water with a hard limit of 25 blocks
*
* @param player the player's location
* @return true if the player is hovering over water
*/
public static boolean isHoveringOverWater(Location player) {
return isHoveringOverWater(player, 25);
}
/**
* Determine whether a material will break instantly when hit
*
* @param m the material to check
* @return true if the material is instant break
*/
public static boolean isInstantBreak(Material m) {
return INSTANT_BREAK.contains(m);
}
/**
* Determine whether a material is edible
*
* @param m the material to check
* @return true if the material is food
*/
public static boolean isFood(Material m) {
return FOOD.contains(m);
}
/**
* Determine whether a block is a slab
*
* @param block block to check
* @return true if slab
*/
public static boolean isSlab(Block block) {
Material type = block.getType();
switch (type) {
case STEP:
case DOUBLE_STEP:
case WOOD_STEP:
case WOOD_DOUBLE_STEP:
return true;
default:
return false;
}
}
/**
* Determine whether a block is a stair
*
* @param block block to check
* @return true if stair
*/
public static boolean isStair(Block block) {
Material type = block.getType();
switch (type) {
case WOOD_STAIRS:
case SPRUCE_WOOD_STAIRS:
case SMOOTH_STAIRS:
case SANDSTONE_STAIRS:
case QUARTZ_STAIRS:
case JUNGLE_WOOD_STAIRS:
case NETHER_BRICK_STAIRS:
case BIRCH_WOOD_STAIRS:
case COBBLESTONE_STAIRS:
return true;
default:
return false;
}
}
/**
* Determine whether a player can interact with this material
*
* @param m material to check
* @return true if interactable
*/
public static boolean isInteractable(Material m) {
return INTERACTABLE.contains(m);
}
/**
* Determine whether a player is sprinting or flying
*
* @param player player to check
* @return true if sprinting or flying
*/
public static boolean sprintFly(Player player) {
return player.isSprinting() || player.isFlying();
}
/**
* Determine whether a player is standing on a lily pad
*
* @param player player to check
* @return true if on lily pad
*/
public static boolean isOnLilyPad(Player player) {
Block block = player.getLocation().getBlock();
Material lily = Material.WATER_LILY;
// TODO: Can we fix X this?
return block.getType() == lily || block.getRelative(BlockFace.NORTH).getType() == lily || block.getRelative(BlockFace.SOUTH).getType() == lily || block.getRelative(BlockFace.EAST).getType() == lily || block.getRelative(BlockFace.WEST).getType() == lily;
}
/**
* Determine whether a player is fully submersed in liquid
*
* @param player player to check
* @return true if submersed
*/
public static boolean isSubmersed(Player player) {
return player.getLocation().getBlock().isLiquid() && player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid();
}
/**
* Determine whether a player is in water
*
* @param player player to check
* @return true if in water
*/
public static boolean isInWater(Player player) {
return player.getLocation().getBlock().isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.DOWN).isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid();
}
/**
* Determine whether a player is in a web
*
* @param player player to check
* @return true if in web
*/
public static boolean isInWeb(Player player) {
return player.getLocation().getBlock().getType() == Material.WEB || player.getLocation().getBlock().getRelative(BlockFace.DOWN).getType() == Material.WEB || player.getLocation().getBlock().getRelative(BlockFace.UP).getType() == Material.WEB;
}
/**
* Determine whether a block is climbable
*
* @param block block to check
* @return true if climbable
*/
public static boolean isClimbableBlock(Block block) {
return block.getType() == Material.VINE || block.getType() == Material.LADDER || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER;
}
/**
* Determine whether a player is on a vine (can be free hanging)
*
* @param player to check
* @return true if on vine
*/
public static boolean isOnVine(Player player) {
return player.getLocation().getBlock().getType() == Material.VINE;
}
/**
* Determine whether a String can be cast to an Integer
*
* @param string text to check
* @return true if int
*/
public static boolean isInt(String string) {
boolean x = false;
try {
Integer.parseInt(string);
x = true;
} catch (Exception ex) {
}
return x;
}
/**
* Calculate the time in milliseconds that it should take to break the given block with the given tool
*
* @param tool tool to check
* @param block block to check
* @return time in milliseconds to break
*/
public static long calcSurvivalFastBreak(ItemStack tool, Material block) {
if (isInstantBreak(block) || (tool.getType() == Material.SHEARS && block == Material.LEAVES)) {
return 0;
}
double bhardness = BlockHardness.getBlockHardness(block);
double thardness = ToolHardness.getToolHardness(tool.getType());
long enchantlvl = (long) tool.getEnchantmentLevel(Enchantment.DIG_SPEED);
long result = Math.round((bhardness * thardness) * 0.10 * 10000);
result += 150;
if (enchantlvl > 0) {
result /= enchantlvl * enchantlvl + 1L;
}
if (result > 25000) {
result = 25000;
} else if (result < 0) {
result = 0;
}
if (isQuickCombo(tool, block)) {
result = result / 2;
}
return result;
}
/**
* Determine whether the given tool is a combination that makes the breaking of this block faster
*
* @param tool tool to check
* @param block block to check
* @return true if quick combo
*/
private static boolean isQuickCombo(ItemStack tool, Material block) {
for (Material t : COMBO.keySet()) {
if (tool.getType() == t && COMBO.get(t) == block) {
return true;
}
}
return false;
}
/**
* Determine if a block ISN'T one of the specified types
*
* @param block block to check
* @param materials array of possible materials
* @return true if the block isn't any of the materials
*/
public static boolean blockIsnt(Block block, Material[] materials) {
Material type = block.getType();
for (Material m : materials) {
if (m == type) {
return false;
}
}
return false;
}
/**
* Parse a COMMAND[] input to a set of commands to execute
*
* @param command input string
* @return parsed commands
*/
public static String[] getCommands(String command) {
return command.replaceAll("COMMAND\\[", "").replaceAll("]", "").split(";");
}
/**
* Remove all whitespace from the given string to ready it for parsing
*
* @param string the string to parse
* @return string with whitespace removed
*/
public static String removeWhitespace(String string) {
return string.replaceAll(" ", "");
}
/**
* Determine if a player has the given enchantment on their armor
*
* @param player player to check
* @param e enchantment to check
* @return true if the armor has this enchantment
*/
public static boolean hasArmorEnchantment(Player player, Enchantment e) {
for (ItemStack is : player.getInventory().getArmorContents()) {
if (is != null && is.containsEnchantment(e)) {
return true;
}
}
return false;
}
/**
* Create a list with the given string for execution
*
* @param string the string to parse
* @return ArrayList with string
*/
public static ArrayList<String> stringToList(String string) {
ArrayList<String> i = new ArrayList<String>();
i.add(string);
return i;
}
/**
* Create a comma-delimited string from a list
*
* @param list the list to parse
* @return the list in a string format
*/
public static String listToCommaString(List<String> list) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
b.append(list.get(i));
if (i < list.size() - 1) {
b.append(",");
}
}
return b.toString();
}
/**
* Parse a string in the format of "XdXhXmXs" to seconds
* @param string The string to parse
* @return seconds
*/
public static long lifeToSeconds(String string) {
if (string.equals("0") || string.equals("")) return 0;
String[] lifeMatch = new String[]{ "d", "h", "m", "s" };
int[] lifeInterval = new int[]{ 86400, 3600, 60, 1 };
long seconds = 0L;
for (int i=0;i<lifeMatch.length;i++) {
Matcher matcher = Pattern.compile("([0-9]*)" + lifeMatch[i]).matcher(string);
while (matcher.find()) {
seconds += Integer.parseInt(matcher.group(1)) * lifeInterval[i];
}
}
return seconds;
}
static {
// START INSTANT BREAK MATERIALS
INSTANT_BREAK.add(Material.RED_MUSHROOM);
INSTANT_BREAK.add(Material.RED_ROSE);
INSTANT_BREAK.add(Material.BROWN_MUSHROOM);
INSTANT_BREAK.add(Material.YELLOW_FLOWER);
INSTANT_BREAK.add(Material.REDSTONE);
INSTANT_BREAK.add(Material.REDSTONE_TORCH_OFF);
INSTANT_BREAK.add(Material.REDSTONE_TORCH_ON);
INSTANT_BREAK.add(Material.REDSTONE_WIRE);
INSTANT_BREAK.add(Material.LONG_GRASS);
INSTANT_BREAK.add(Material.PAINTING);
INSTANT_BREAK.add(Material.WHEAT);
INSTANT_BREAK.add(Material.SUGAR_CANE);
INSTANT_BREAK.add(Material.SUGAR_CANE_BLOCK);
INSTANT_BREAK.add(Material.DIODE);
INSTANT_BREAK.add(Material.DIODE_BLOCK_OFF);
INSTANT_BREAK.add(Material.DIODE_BLOCK_ON);
INSTANT_BREAK.add(Material.SAPLING);
INSTANT_BREAK.add(Material.TORCH);
INSTANT_BREAK.add(Material.CROPS);
INSTANT_BREAK.add(Material.SNOW);
INSTANT_BREAK.add(Material.TNT);
INSTANT_BREAK.add(Material.POTATO);
INSTANT_BREAK.add(Material.CARROT);
// END INSTANT BREAK MATERIALS
// START INTERACTABLE MATERIALS
INTERACTABLE.add(Material.STONE_BUTTON);
INTERACTABLE.add(Material.LEVER);
INTERACTABLE.add(Material.CHEST);
// END INTERACTABLE MATERIALS
// START FOOD
FOOD.add(Material.COOKED_BEEF);
FOOD.add(Material.COOKED_CHICKEN);
FOOD.add(Material.COOKED_FISH);
FOOD.add(Material.GRILLED_PORK);
FOOD.add(Material.PORK);
FOOD.add(Material.MUSHROOM_SOUP);
FOOD.add(Material.RAW_BEEF);
FOOD.add(Material.RAW_CHICKEN);
FOOD.add(Material.RAW_FISH);
FOOD.add(Material.APPLE);
FOOD.add(Material.GOLDEN_APPLE);
FOOD.add(Material.MELON);
FOOD.add(Material.COOKIE);
FOOD.add(Material.BREAD);
FOOD.add(Material.SPIDER_EYE);
FOOD.add(Material.ROTTEN_FLESH);
FOOD.add(Material.POTATO_ITEM);
// END FOOD
// START COMBOS
COMBO.put(Material.SHEARS, Material.WOOL);
COMBO.put(Material.IRON_SWORD, Material.WEB);
COMBO.put(Material.DIAMOND_SWORD, Material.WEB);
COMBO.put(Material.STONE_SWORD, Material.WEB);
COMBO.put(Material.WOOD_SWORD, Material.WEB);
// END COMBOS
}
}
@@ -0,0 +1,207 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util.enterprise;
import net.gravitydevelopment.anticheat.AntiCheat;
import net.gravitydevelopment.anticheat.manage.CheckType;
import net.gravitydevelopment.anticheat.manage.User;
import net.gravitydevelopment.anticheat.util.Utilities;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitTask;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Database {
private static final String EVENTS_TABLE = "logs";
private String sqlLogEvent;
private String sqlCleanEvents;
private String sqlCreateEvents;
public enum DatabaseType {
MySQL,
}
private DatabaseType type;
private String hostname;
private int port;
private String username;
private String password;
private String prefix;
private String schema;
private String serverName;
private long logInterval;
private long logLife;
private Connection connection;
private PreparedStatement eventBatch;
private BukkitTask eventTask;
public Database(DatabaseType type, String hostname, int port, String username, String password, String prefix, String schema, String serverName, String logInterval, String logLife) {
this.type = type;
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
this.prefix = prefix;
this.schema = schema;
this.serverName = serverName;
this.logInterval = Utilities.lifeToSeconds(logInterval);
this.logLife = Utilities.lifeToSeconds(logLife);
sqlLogEvent = "INSERT INTO " + prefix + EVENTS_TABLE +
" (server, user, check_type) " +
"VALUES (?, ?, ?)";
sqlCleanEvents = "DELETE FROM " + prefix + EVENTS_TABLE + " " +
"WHERE time < (CURRENT_TIMESTAMP - INTERVAL ? SECOND)";
sqlCreateEvents = "CREATE TABLE IF NOT EXISTS " + prefix + EVENTS_TABLE + "(" +
" `id` INT NOT NULL AUTO_INCREMENT," +
" `server` VARCHAR(45) NOT NULL," +
" `time` TIMESTAMP NOT NULL DEFAULT NOW()," +
" `user` VARCHAR(45) NOT NULL," +
" `check_type` VARCHAR(45) NOT NULL," +
" PRIMARY KEY (`id`));";
}
public DatabaseType getType() {
return type;
}
public String getHostname() {
return hostname;
}
public int getPort() {
return port;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getPrefix() {
return prefix;
}
public String getSchema() {
return schema;
}
public void connect() {
String url = "jdbc:" + type.toString().toLowerCase() + "://" + hostname + ":" + port + "/" + schema;
try {
connection = DriverManager.getConnection(url, username, password);
eventBatch = connection.prepareStatement(sqlLogEvent);
connection.prepareStatement(sqlCreateEvents).executeUpdate();
connection.setAutoCommit(false);
if (logInterval != 0) {
eventTask = Bukkit.getScheduler().runTaskTimerAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
flushEvents();
}
}, logInterval * 20, logInterval * 20);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void shutdown() {
eventTask.cancel();
flushEvents();
try {
eventBatch.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getConnection() {
return connection;
}
public void logEvent(User user, CheckType checkType) {
try {
eventBatch.setString(1, serverName);
eventBatch.setString(2, user.getName());
eventBatch.setString(3, checkType.toString());
eventBatch.addBatch();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void flushEvents() {
try {
eventBatch.executeBatch();
connection.commit();
eventBatch = connection.prepareStatement(sqlLogEvent);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void cleanEvents() {
if (logLife != 0) {
Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
try {
PreparedStatement statement = connection.prepareStatement(sqlCleanEvents);
statement.setLong(1, logLife);
statement.executeUpdate();
connection.commit();
AntiCheat.getPlugin().verboseLog("Cleaned " + statement.getUpdateCount() + " old events from the database");
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
}
}
@@ -0,0 +1,94 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util.rule;
import net.gravitydevelopment.anticheat.manage.CheckType;
import net.gravitydevelopment.anticheat.manage.User;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.SortedMap;
/**
* The conditional rule follows the same syntax as the traditional CS conditional operator.<br />
* (CONDITION) ? (TRUE RESULT) : (FALSE RESULT)<br />
* Where CONDITION is a statement that will be evaluated as either <b>TRUE</b> or <b>FALSE</b>
* and the results are actions to be taken for either outcome.
* <br /><br />
* <p/>
* Should you need additional actions, the system will recursively parse the following values and handle appropriately.
* <br />
* For instance, (CONDITION) ? (TRUE RESULT) : (CONDITION) ? (TRUE RESULT) : (FALSE RESULT) is a valid rule
* <br /><br />
* <p/>
* An example of a valid Conditional Rule:<br />
* Check_SPIDER > 0 ? Player.KICK : null<br />
* <i>The above statement would read 'If the spider check has been failed over zero times, kick the player. Otherwise, do nothing.'</i>
* <p/>
* To see syntax for variables and functions that you may use, see {@link net.gravitydevelopment.anticheat.util.rule.Rule}
*/
public class ConditionalRule extends Rule {
private static ScriptEngineManager factory = new ScriptEngineManager();
private static ScriptEngine engine = factory.getEngineByName("js");
private static final String TRUE_DELIMITER = "\\?";
private static final String FALSE_DELIMITER = ":";
private static final Type TYPE = Type.CONDITIONAL;
public ConditionalRule(String string) {
super(string, TYPE);
}
@Override
public boolean check(User user, CheckType type) {
try {
// Load all variables
SortedMap<String, Object> map = getVariables(user, type);
for (String key : map.keySet()) {
engine.put(key, map.get(key));
}
boolean value = (Boolean) engine.eval(getString().split(TRUE_DELIMITER)[0]);
// Yo dawg I heard you like conditionals...
String next = value ? getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[0] : getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[1];
execute(next, user, type);
return value;
} catch (ScriptException e) {
e.printStackTrace();
}
return true;
}
private void execute(String string, User user, CheckType type) {
// If we're told to do nothing
if (string.equalsIgnoreCase("null") || string.equalsIgnoreCase("none")) return;
// If this string is a new conditional statement
if (TYPE.matches(string)) {
new ConditionalRule(string).check(user, type);
} else if (isVariableSet(string)) {
setVariable(string.split("=")[0], string.split("=")[1], user);
} else if (isFunction(string)) {
doFunction(string, type, user);
}
}
}
@@ -0,0 +1,177 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.util.rule;
import net.gravitydevelopment.anticheat.AntiCheat;
import net.gravitydevelopment.anticheat.manage.CheckType;
import net.gravitydevelopment.anticheat.manage.User;
import net.gravitydevelopment.anticheat.util.Utilities;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* A rule is a scriptable function used to customize the functions of AntiCheat<br />
* Rules are executed whenever a user's level rises.<br /><br />
* <p/>
* There are various variables you can use to interact with AntiCheat through your rules<br />
* Variables are denoted with the type followed by a _ followed by the variable name.<br />
* For instance, a variable coming from a user who has used FLY 5 times and is checked by a rule containing 'Check_FLY' will produce a value of 5.
* <br /><br />
* <p/>
* <b>Types of variables:</b><br />
* - Check: Contains all valid checks as listed in {@link net.gravitydevelopment.anticheat.manage.CheckType}, and will return the number of times this user has failed the given check<br />
* - Player: Contains LEVEL, the player's current level and CHECK, the check that was just failed
* <br /><br />
* <p/>
* There are also functions you can use to execute an action within AntiCheat<br />
* Functions are denoted with the type followed by a period followed by the function name.<br />
* For instance, a rule containing Player.KICK will result in the user being kicked.<br />
* <br /><br />
* <p/>
* <b>Types of functions:</b><br />
* - Player: RESET, KICK, BAN, COMMAND[command] OR COMMAND[command1;command2]
* <i>- when using commands <b>&player</b> will be replaced by the player name, <b>&world</b> will be replaced by the player's world,
* and <b>&check</b> will be replaced by the check that caused this rule to be run</i><br />
* <br /><br />
* <p/>
* The Rule class itself is not an functional rule setup,
* it is inherited and made functional by different implementations of the rule parser.<br />
* The only current Rule implementation is the {@link net.gravitydevelopment.anticheat.util.rule.ConditionalRule}
*/
public class Rule {
private static String string;
private static final String VARIABLE_SET_REGEX = ".*(_).*=.*";
private static final String FUNCTION_REGEX = ".*\\..*";
private Type type;
public enum Type {
CONDITIONAL(".*[?]*.*:.*", "net.gravitydevelopment.anticheat.util.rule.ConditionalRule");
private String regex;
private String c;
private Type(String regex, String c) {
this.regex = regex;
this.c = c;
}
public boolean matches(String s) {
return s.matches(regex);
}
public String getInstance() {
return c;
}
}
public Rule(String string, Type type) {
this.string = Utilities.removeWhitespace(string).toLowerCase();
this.type = type;
}
/**
* Check if the rule passed or failed
*
* @param user the user to check
* @return true if the rule has passed, false if failed
*/
public boolean check(User user, CheckType type) {
// Default value
return true;
}
/**
* Load a rule by its string value
*
* @param string the string value to load
* @return an instance of Rule if an implementation exists to handle this rule, null if none are found
*/
public static Rule load(String string) {
for (Type type : Type.values()) {
if (type.matches(string)) {
try {
Class c = Class.forName(type.getInstance());
Constructor con = c.getConstructor(String.class);
return (Rule) con.newInstance(string);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
/**
* Get the type of rule this is
*
* @return a {@link net.gravitydevelopment.anticheat.util.rule.Rule.Type}
*/
public Type getType() {
return type;
}
protected String getString() {
return string;
}
protected SortedMap<String, Object> getVariables(User user, CheckType type) {
SortedMap<String, Object> map = new TreeMap<String, Object>();
map.put("player_check", type.name().toLowerCase());
map.put("player_level", user.getLevel());
for (CheckType t : CheckType.values()) {
map.put("check_" + t.name().toLowerCase(), t.getUses(user.getName()));
}
return map;
}
protected void setVariable(String variable, String value, User user) {
// Only variable that can be set for now, may change in the future
// others wouldn't make any sense to set
if (variable.equals("player_level") && Utilities.isInt(value)) {
user.setLevel(Integer.parseInt(value));
}
}
protected void doFunction(String text, CheckType type, User user) {
if (text.toLowerCase().startsWith("player")) {
text = text.split("\\.")[1];
List<String> action = new ArrayList<String>();
action.add(text);
AntiCheat.getManager().getUserManager().execute(user, action, type);
}
}
protected boolean isFunction(String string) {
return string.matches(FUNCTION_REGEX);
}
protected boolean isVariableSet(String string) {
return string.matches(VARIABLE_SET_REGEX);
}
@Override
public String toString() {
return type + "{" + string + "}";
}
}