Renamed package and groupId

This commit is contained in:
Rammelkast committed 2017-02-05 13:47:13 +01:00
1 parent 21d0108c16
commit 7f13a0ad4c
78 files changed
+396 -370

No files matched your search

@@ -0,0 +1,221 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.rammelkast.anticheatreloaded.check.combat.KillAuraCheck;
import com.rammelkast.anticheatreloaded.check.movement.BlinkCheck;
import com.rammelkast.anticheatreloaded.command.CommandHandler;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.event.BlockListener;
import com.rammelkast.anticheatreloaded.event.EntityListener;
import com.rammelkast.anticheatreloaded.event.InventoryListener;
import com.rammelkast.anticheatreloaded.event.PlayerListener;
import com.rammelkast.anticheatreloaded.event.VehicleListener;
import com.rammelkast.anticheatreloaded.manage.AntiCheatManager;
import com.rammelkast.anticheatreloaded.metrics.Metrics;
import com.rammelkast.anticheatreloaded.util.User;
import com.rammelkast.anticheatreloaded.util.VersionUtil;
public class AntiCheat extends JavaPlugin {
private static AntiCheatManager manager;
private static AntiCheat plugin;
private static List<Listener> eventList = new ArrayList<Listener>();
private static Configuration config;
private static boolean verbose;
private static boolean developer;
private static ProtocolManager protocolManager;
private static boolean protocolLib = false;
private static Long loadTime;
@Override
public void onEnable() {
plugin = this;
loadTime = System.currentTimeMillis();
manager = new AntiCheatManager(this, getLogger());
eventList.add(new PlayerListener());
eventList.add(new BlockListener());
eventList.add(new EntityListener());
eventList.add(new VehicleListener());
eventList.add(new InventoryListener());
// Order is important in some cases, don't screw with these unless needed, especially config
setupConfig();
setupEvents();
setupCommands();
setupProtocol();
// Enterprise must come before levels
setupEnterprise();
restoreLevels();
// Check if NoCheatPlus is installed
Bukkit.getScheduler().runTaskLater(this, new Runnable() {
public void run() {
if (Bukkit.getPluginManager().getPlugin("NoCheatPlus") != null) {
getLogger().severe("You are also running NoCheatPlus!");
getLogger().severe("Multiple anticheats create false cheat detections.");
getLogger().severe("Please remove or disable NoCheatPlus to silence this warning.");
}else if (Bukkit.getPluginManager().getPlugin("AAC") != null) {
getLogger().severe("You are also running AAC!");
getLogger().severe("Multiple anticheats create false cheat detections.");
getLogger().severe("Please remove or disable AAC to silence this warning.");
}
}
}, 40L);
// End tests
verboseLog("Finished loading.");
getLogger().info("Running version " + VersionUtil.getVersion() + "...");
// Enable packetlisteners
KillAuraCheck.listenPackets();
BlinkCheck.startTimer();
BlinkCheck.listenPackets();
// Metrics
try {
new Metrics(this);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onDisable() {
verboseLog("Saving user levels...");
config.getLevels().saveLevelsFromUsers(getManager().getUserManager().getUsers());
AntiCheatManager.close();
getServer().getScheduler().cancelTasks(this);
cleanup();
}
private void setupProtocol() {
if (Bukkit.getPluginManager().getPlugin("ProtocolLib") != null) {
protocolLib = true;
protocolManager = ProtocolLibrary.getProtocolManager();
verboseLog("Hooked into ProtocolLib");
}
}
private void setupEvents() {
for (Listener listener : eventList) {
getServer().getPluginManager().registerEvents(listener, this);
verboseLog("Registered events for ".concat(listener.toString().split("@")[0].split(".anticheat.")[1]));
}
}
private void setupCommands() {
getCommand("anticheat").setExecutor(new CommandHandler());
verboseLog("Registered commands.");
}
private void setupConfig() {
config = manager.getConfiguration();
verboseLog("Setup the config.");
}
private void setupEnterprise() {
if (config.getConfig().enterprise.getValue()) {
if (config.getEnterprise().loggingEnabled.getValue()) {
config.getEnterprise().database.cleanEvents();
}
}
}
private void restoreLevels() {
for (Player player : getServer().getOnlinePlayers()) {
UUID uuid = player.getUniqueId();
User user = new User(uuid);
user.setIsWaitingOnLevelSync(true);
config.getLevels().loadLevelToUser(user);
manager.getUserManager().addUser(user);
verboseLog("Data for " + uuid + " loaded");
}
}
public static AntiCheat getPlugin() {
return plugin;
}
public static AntiCheatManager getManager() {
return manager;
}
public static String getVersion() {
return manager.getPlugin().getDescription().getVersion();
}
private void cleanup() {
eventList = null;
manager = null;
config = null;
}
public static boolean developerMode() {
return developer;
}
public static void setDeveloperMode(boolean b) {
developer = b;
}
public static boolean isUsingProtocolLib() {
return protocolLib;
}
public static void debugLog(final String string) {
Bukkit.getScheduler().runTask(getPlugin(), new Runnable() {
public void run() {
if (developer) {
manager.debugLog("[DEBUG] " + string);
}
}
});
}
public void verboseLog(final String string) {
if (verbose) {
getLogger().info(string);
}
}
public void setVerbose(boolean b) {
verbose = b;
}
public Long getLoadTime() {
return loadTime;
}
public static ProtocolManager getProtocolManager() {
return protocolManager;
}
}
@@ -0,0 +1,180 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.api;
import java.util.List;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.manage.AntiCheatManager;
import com.rammelkast.anticheatreloaded.manage.CheckManager;
import com.rammelkast.anticheatreloaded.manage.UserManager;
import com.rammelkast.anticheatreloaded.util.Group;
/**
* Developer's interface for all things AntiCheat.
*/
public class AntiCheatAPI {
private static CheckManager chk = AntiCheat.getManager().getCheckManager();
private static UserManager umr = AntiCheat.getManager().getUserManager();
// CheckManager API
/**
* Start running a certain check
*
* @param type Check to start watching for
*/
public static void activateCheck(CheckType type, Class caller) {
chk.activateCheck(type, caller.getName());
}
/**
* Stop running a certain check
*
* @param type Check to stop watching for
*/
public static void deactivateCheck(CheckType type, Class caller) {
chk.deactivateCheck(type, caller.getName());
}
/**
* Find out if a check is currently being watched for
*
* @param type Type to check
* @return true if plugin is watching for this check
*/
public static boolean isActive(CheckType type) {
return chk.isActive(type);
}
/**
* Allow a player to skip a certain check
*
* @param player Player to stop watching
* @param type Check to stop watching for
*/
public static void exemptPlayer(Player player, CheckType type, Class caller) {
chk.exemptPlayer(player, type, caller.getName());
}
/**
* Stop allowing a player to skip a certain check
*
* @param player Player to start watching
* @param type Check to start watching for
*/
public static void unexemptPlayer(Player player, CheckType type, Class caller) {
chk.unexemptPlayer(player, type, caller.getName());
}
/**
* Find out if a player is currently exempt from a certain check
*
* @param player Player to check
* @param type Type to check
* @return true if plugin is ignoring this check on this player
*/
public static boolean isExempt(Player player, CheckType type) {
return chk.isExempt(player, type);
}
/**
* Find out if a check will occur for a player. This checks if they are being tracked, the check is active, the player isn't exempt from the check, and the player doesn't have override permission.
*
* @param player Player to check
* @param type Type to check
* @return true if plugin will check this player, and that all things allow it to happen.
*/
public boolean willCheck(Player player, CheckType type) {
return chk.willCheck(player, type);
}
// PlayerManager API
/**
* Get a player's integer hack level
*
* @param player Player to check
* @return player's hack level
* @deprecated see {@link #getGroup(org.bukkit.entity.Player)}
*/
@Deprecated
public static int getLevel(Player player) {
return umr.safeGetLevel(player.getUniqueId());
}
/**
* Set a player's hack level
*
* @param player Player to set
* @param level Group to set to
* @deprecated see {@link #resetPlayer(org.bukkit.entity.Player)}
*/
@Deprecated
public static void setLevel(Player player, int level) {
umr.safeSetLevel(player.getUniqueId(), level);
}
/**
* Reset a player's hack level to 0
*
* @param player Player to reset
*/
public static void resetPlayer(Player player) {
umr.getUser(player.getUniqueId()).resetLevel();
}
/**
* Get a user's {@link com.rammelkast.anticheatreloaded.util.Group}
*
* @param player Player whose group to find
* @return The player's group
*/
public static Group getGroup(Player player) {
return umr.getUser(player.getUniqueId()).getGroup();
}
/**
* Get all configured Groups
*
* @return List of all groups
* @see com.rammelkast.anticheatreloaded.util.Group
*/
public static List<Group> getGroups() {
return getManager().getConfiguration().getGroups().getGroups();
}
// Advanced Users Only API.
/**
* Get access to all the other managers, advanced users ONLY
*
* @return the AntiCheat Manager
*/
public static AntiCheatManager getManager() {
return AntiCheat.getManager();
}
}
@@ -0,0 +1,65 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.api;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.util.User;
/**
* Fired when a player fails an AntiCheat check
*/
public class CheckFailEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private final User user;
private final CheckType type;
public CheckFailEvent(User user, CheckType type) {
this.user = user;
this.type = type;
}
/**
* Get the {@link com.rammelkast.anticheatreloaded.util.User} who failed the check
*
* @return a {@link com.rammelkast.anticheatreloaded.util.User}
*/
public User getUser() {
return user;
}
/**
* Get the {@link com.rammelkast.anticheatreloaded.check.CheckType} failed
*
* @return a {@link com.rammelkast.anticheatreloaded.check.CheckType}
*/
public CheckType getCheck() {
return type;
}
public HandlerList getHandlers() {
return handlers;
}
}
@@ -0,0 +1,890 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.check;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
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.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerToggleSprintEvent;
import org.bukkit.potion.PotionEffectType;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.combat.KillAuraCheck;
import com.rammelkast.anticheatreloaded.check.combat.VelocityCheck;
import com.rammelkast.anticheatreloaded.check.movement.BlinkCheck;
import com.rammelkast.anticheatreloaded.check.movement.FlightCheck;
import com.rammelkast.anticheatreloaded.check.movement.GlideCheck;
import com.rammelkast.anticheatreloaded.check.movement.SpeedCheck;
import com.rammelkast.anticheatreloaded.check.movement.WaterWalkCheck;
import com.rammelkast.anticheatreloaded.check.movement.YAxisCheck;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.providers.Lang;
import com.rammelkast.anticheatreloaded.config.providers.Magic;
import com.rammelkast.anticheatreloaded.manage.AntiCheatManager;
import com.rammelkast.anticheatreloaded.util.Distance;
import com.rammelkast.anticheatreloaded.util.User;
import com.rammelkast.anticheatreloaded.util.Utilities;
import com.rammelkast.anticheatreloaded.util.VersionUtil;
public class Backend {
private List<UUID> isAscending = new ArrayList<UUID>();
private Map<UUID, Integer> ascensionCount = new HashMap<UUID, Integer>();
private Map<UUID, Integer> chatLevel = new HashMap<UUID, Integer>();
private Map<UUID, Integer> commandLevel = new HashMap<UUID, Integer>();
private Map<UUID, Integer> nofallViolation = new HashMap<UUID, Integer>();
private Map<UUID, Integer> fastBreakViolation = new HashMap<UUID, Integer>();
private Map<UUID, Integer> fastBreaks = new HashMap<UUID, Integer>();
private Map<UUID, Boolean> blockBreakHolder = new HashMap<UUID, Boolean>();
private Map<UUID, Long> lastBlockBroken = new HashMap<UUID, Long>();
private Map<UUID, Integer> fastPlaceViolation = new HashMap<UUID, Integer>();
private Map<UUID, Long> lastBlockPlaced = new HashMap<UUID, Long>();
private Map<UUID, Long> lastBlockPlaceTime = new HashMap<UUID, Long>();
private Map<UUID, Integer> blockPunches = new HashMap<UUID, Integer>();
private Map<UUID, Integer> projectilesShot = new HashMap<UUID, Integer>();
private Map<UUID, Long> velocitized = new HashMap<UUID, Long>();
private Map<UUID, Integer> velocitytrack = new HashMap<UUID, Integer>();
private Map<UUID, Long> startEat = new HashMap<UUID, Long>();
private Map<UUID, Long> lastHeal = new HashMap<UUID, Long>();
private Map<UUID, Long> projectileTime = new HashMap<UUID, Long>();
private Map<UUID, Long> bowWindUp = new HashMap<UUID, Long>();
private Map<UUID, Long> instantBreakExempt = new HashMap<UUID, Long>();
private Map<UUID, Long> sprinted = new HashMap<UUID, Long>();
private Map<UUID, Long> brokenBlock = new HashMap<UUID, Long>();
private Map<UUID, Long> placedBlock = new HashMap<UUID, Long>();
private Map<UUID, Long> blockTime = new HashMap<UUID, Long>();
private Map<UUID, Integer> blocksDropped = new HashMap<UUID, Integer>();
private Map<UUID, Long> lastInventoryTime = new HashMap<UUID, Long>();
private Map<UUID, Long> inventoryTime = new HashMap<UUID, Long>();
private Map<UUID, Integer> inventoryClicks = new HashMap<UUID, Integer>();
private Map<UUID, Material> itemInHand = new HashMap<UUID, Material>();
private Map<UUID, Integer> steps = new HashMap<UUID, Integer>();
private Map<UUID, Long> stepTime = new HashMap<UUID, Long>();
private HashSet<Byte> transparent = new HashSet<Byte>();
private Map<UUID, Long> lastFallPacket = new HashMap<UUID, Long>();
private Magic magic;
private AntiCheatManager manager = null;
private Lang lang = null;
private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED);
public Backend(AntiCheatManager instance) {
magic = instance.getConfiguration().getMagic();
manager = instance;
lang = manager.getConfiguration().getLang();
transparent.add((byte) -1);
}
public Magic getMagic() {
return magic;
}
public void updateConfig(Configuration config) {
magic = config.getMagic();
lang = config.getLang();
}
public void resetChatLevel(User user) {
chatLevel.put(user.getUUID(), 0);
}
public void garbageClean(Player player) {
UUID pU = player.getUniqueId();
VelocityCheck.cleanPlayer(player);
KillAuraCheck.cleanPlayer(player);
BlinkCheck.MOVE_COUNT.remove(player.getUniqueId());
blocksDropped.remove(pU);
blockTime.remove(pU);
FlightCheck.movingExempt.remove(pU);
brokenBlock.remove(pU);
placedBlock.remove(pU);
bowWindUp.remove(pU);
startEat.remove(pU);
lastHeal.remove(pU);
sprinted.remove(pU);
WaterWalkCheck.isInWater.remove(pU);
WaterWalkCheck.isInWaterCache.remove(pU);
instantBreakExempt.remove(pU);
isAscending.remove(player.getUniqueId());
ascensionCount.remove(player.getUniqueId());
FlightCheck.blocksOverFlight.remove(pU);
nofallViolation.remove(pU);
fastBreakViolation.remove(pU);
YAxisCheck.yAxisViolations.remove(pU);
YAxisCheck.yAxisLastViolation.remove(pU);
YAxisCheck.lastYcoord.remove(pU);
YAxisCheck.lastYtime.remove(pU);
fastBreaks.remove(pU);
blockBreakHolder.remove(pU);
lastBlockBroken.remove(pU);
fastPlaceViolation.remove(pU);
lastBlockPlaced.remove(pU);
lastBlockPlaceTime.remove(pU);
blockPunches.remove(pU);
WaterWalkCheck.waterAscensionViolation.remove(pU);
WaterWalkCheck.waterSpeedViolation.remove(pU);
projectilesShot.remove(pU);
velocitized.remove(pU);
velocitytrack.remove(pU);
startEat.remove(pU);
lastHeal.remove(pU);
projectileTime.remove(pU);
bowWindUp.remove(pU);
instantBreakExempt.remove(pU);
sprinted.remove(pU);
brokenBlock.remove(pU);
placedBlock.remove(pU);
FlightCheck.movingExempt.remove(pU);
blockTime.remove(pU);
blocksDropped.remove(pU);
lastInventoryTime.remove(pU);
inventoryTime.remove(pU);
inventoryClicks.remove(pU);
lastFallPacket.remove(pU);
GlideCheck.lastDiff.remove(pU);
GlideCheck.lastFallDistance.remove(pU);
GlideCheck.violations.remove(pU);
SpeedCheck.speedViolation.remove(player.getUniqueId());
}
public CheckResult checkFastBow(Player player, float force) {
// Ignore magic numbers here, they are minecrafty vanilla stuff.
if (!bowWindUp.containsKey(player.getUniqueId())) {
return PASS;
}
int ticks = (int) ((((System.currentTimeMillis() - bowWindUp.get(player.getUniqueId())) * 20) / 1000) + 3);
bowWindUp.remove(player.getUniqueId());
float f = (float) ticks / 20.0F;
f = (f * f + f * 2.0F) / 3.0F;
f = f > 1.0F ? 1.0F : f;
if (Math.abs(force - f) > magic.BOW_ERROR()) {
return new CheckResult(CheckResult.Result.FAILED, player.getUniqueId() + " fired their bow too fast (actual force=" + force + ", calculated force=" + f + ")");
} else {
return PASS;
}
}
public CheckResult checkProjectile(Player player) {
incrementOld(player, projectilesShot, 10);
if (!projectileTime.containsKey(player.getUniqueId())) {
projectileTime.put(player.getUniqueId(), System.currentTimeMillis());
return new CheckResult(CheckResult.Result.PASSED);
} else if (projectilesShot.get(player.getUniqueId()) == magic.PROJECTILE_CHECK()) {
long time = System.currentTimeMillis() - projectileTime.get(player.getUniqueId());
projectileTime.remove(player.getUniqueId());
projectilesShot.remove(player.getUniqueId());
if (time < magic.PROJECTILE_TIME_MIN()) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " wound up a bow too fast (actual time=" + time + ", min time=" + magic.PROJECTILE_TIME_MIN() + ")");
}
}
return PASS;
}
public CheckResult checkFastDrop(Player player) {
incrementOld(player, blocksDropped, 10);
if (!blockTime.containsKey(player.getUniqueId())) {
blockTime.put(player.getUniqueId(), System.currentTimeMillis());
return new CheckResult(CheckResult.Result.PASSED);
} else if (blocksDropped.get(player.getUniqueId()) == magic.DROP_CHECK()) {
long time = System.currentTimeMillis() - blockTime.get(player.getUniqueId());
blockTime.remove(player.getUniqueId());
blocksDropped.remove(player.getUniqueId());
if (time < magic.DROP_TIME_MIN()) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " dropped an item too fast (actual time=" + time + ", min time=" + magic.DROP_TIME_MIN() + ")");
}
}
return PASS;
}
public CheckResult checkLongReachBlock(Player player, double x, double y, double z) {
if (isInstantBreakExempt(player)) {
return new CheckResult(CheckResult.Result.PASSED);
} else {
String string = player.getName() + " reached too far for a block";
double distance =
player.getGameMode() == GameMode.CREATIVE ? magic.BLOCK_MAX_DISTANCE_CREATIVE()
: player.getLocation().getDirection().getY() > 0.9 ? magic.BLOCK_MAX_DISTANCE_CREATIVE()
: magic.BLOCK_MAX_DISTANCE();
double i = x >= distance ? x : y > distance ? y : z > distance ? z : -1;
if (i != -1) {
return new CheckResult(CheckResult.Result.FAILED, string + " (distance=" + i + ", max=" + magic.BLOCK_MAX_DISTANCE() + ")");
} else {
return PASS;
}
}
}
public CheckResult checkLongReachDamage(Player player, double x, double y, double z) {
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;
if (i != -1) {
return new CheckResult(CheckResult.Result.FAILED, string + " (distance=" + i + ", max=" + magic.ENTITY_MAX_DISTANCE() + ")");
} else {
return PASS;
}
}
public CheckResult checkSpider(Player player, double y) {
if (y <= magic.LADDER_Y_MAX() && y >= magic.LADDER_Y_MIN() && !Utilities.isClimbableBlock(player.getLocation().getBlock())) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " tried to climb a non-ladder (" + player.getLocation().getBlock().getType() + ")");
} else {
return PASS;
}
}
public CheckResult checkYSpeed(Player player, double y) {
if (!isMovingExempt(player) && !player.isInsideVehicle() && !player.isSleeping() && (y > (VersionUtil.isNewYSpeed() ? magic.Y_SPEED_MAX() + 0.05 : magic.Y_SPEED_MAX())) && !isDoing(player, velocitized, magic.VELOCITY_TIME()) && !player.hasPotionEffect(PotionEffectType.JUMP) && !VersionUtil.isFlying(player)) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + "'s y speed was too high (speed=" + y + ", max=" + magic.Y_SPEED_MAX() + ")");
} else {
return PASS;
}
}
public CheckResult checkNoFall(Player player, double y) {
UUID uuid = player.getUniqueId();
if (player.getGameMode() != GameMode.CREATIVE && !player.isInsideVehicle() && !player.isSleeping() && !isMovingExempt(player) && !justPlaced(player) && !Utilities.isInWater(player) && !Utilities.isInWeb(player)) {
if (player.getFallDistance() == 0) {
if (nofallViolation.get(uuid) == null) {
nofallViolation.put(uuid, 1);
} else {
nofallViolation.put(uuid, nofallViolation.get(player.getUniqueId()) + 1);
}
int i = nofallViolation.get(uuid);
if (i >= magic.NOFALL_LIMIT()) {
nofallViolation.put(player.getUniqueId(), 1);
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " tried to avoid fall damage (fall distance = 0 " + i + " times in a row, max=" + magic.NOFALL_LIMIT() + ")");
} else {
return PASS;
}
} else {
nofallViolation.put(uuid, 0);
return PASS;
}
}
return PASS;
}
public CheckResult checkSneak(Player player, double x, double z) {
if (player.isSneaking() && !VersionUtil.isFlying(player) && !isMovingExempt(player) && !player.isInsideVehicle()) {
double i = x > magic.XZ_SPEED_MAX_SNEAK() ? x : z > magic.XZ_SPEED_MAX_SNEAK() ? z : -1;
if (i != -1) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " was sneaking too fast (speed=" + i + ", max=" + magic.XZ_SPEED_MAX_SNEAK() + ")");
} else {
return PASS;
}
} else {
return PASS;
}
}
public CheckResult checkSprintHungry(PlayerToggleSprintEvent event) {
Player player = event.getPlayer();
if (event.isSprinting() && player.getGameMode() != GameMode.CREATIVE && player.getFoodLevel() <= magic.SPRINT_FOOD_MIN()) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " sprinted while hungry (food=" + player.getFoodLevel() + ", min=" + magic.SPRINT_FOOD_MIN() + ")");
} else {
return PASS;
}
}
public CheckResult checkSprintStill(Player player, Location from, Location to) {
/*if(!isMovingExempt(player) && player.isSprinting() && from.getX() == to.getX() && from.getZ() == to.getZ()) {
return new CheckResult(Result.FAILED, player.getName()+" sprinted while standing still (xyz = "+(int)from.getX()+","+(int)from.getY()+","+(int)from.getZ()+")");
}*/
return PASS;
}
public CheckResult checkVClip(Player player, Distance distance) {
double from = Math.round(distance.fromY());
double to = Math.round(distance.toY());
if (player.isInsideVehicle() || (from == to || from < to) || Math.round(distance.getYDifference()) < 2) {
return PASS;
}
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();
if (block.getType() != Material.AIR && block.getType().isSolid()) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " tried to move through a solid block", (int) from + 3);
}
}
return PASS;
}
public CheckResult checkTimer(Player player) {
UUID uuid = player.getUniqueId();
int step = 1;
if (steps.containsKey(uuid)) {
step = steps.get(uuid) + 1;
}
if (step == 1) {
stepTime.put(uuid, System.currentTimeMillis());
}
incrementOld(player, steps, step);
if (step == magic.TIMER_STEP_CHECK()) {
long time = System.currentTimeMillis() - stepTime.get(uuid);
steps.put(uuid, 0);
if (time < magic.TIMER_TIMEMIN()) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " tried to alter their timer, took " + step + " steps in " + time + " ms (min = " + magic.TIMER_TIMEMIN() + " ms)");
}
}
return PASS;
}
public CheckResult checkSight(Player player, Entity entity) {
/*if (entity instanceof LivingEntity) {
LivingEntity le = (LivingEntity) entity;
// Check to make sure the entity's head is not surrounded
Block head = le.getWorld().getBlockAt((int) le.getLocation().getX(), (int) (le.getLocation().getY() + le.getEyeHeight()), (int) le.getLocation().getZ());
boolean solid = false;
// TODO: This sucks. See if it's possible to not have as many false-positives while still retaining most of the check.
for (int x = -2; x <= 2; x++) {
for (int z = -2; z <= 2; z++) {
for (int y = -1; y < 2; y++) {
if (head.getRelative(x, y, z).getTypeId() != 0) {
if (head.getRelative(x, y, z).getType().isSolid()) {
solid = true;
break;
}
}
}
}
}
if (solid) {
return PASS;
}
// TODO: Needs proper testing
Location mobLocation = le.getEyeLocation();
for (Block block : player.getLineOfSight(transparent, 5)) {
if (Math.abs(block.getLocation().getX() - mobLocation.getX()) < 2.3 || Math.abs(block.getLocation().getZ() - mobLocation.getZ()) < 2.3) {
return PASS;
}
}
return new CheckResult(Result.FAILED, player.getName()+" tried to damage an entity ("+le.getType()+") out of sight ");
}*/
return PASS;
}
public void logAscension(Player player, double y1, double y2) {
UUID name = player.getUniqueId();
if (y1 < y2 && !isAscending.contains(name)) {
isAscending.add(name);
} else {
isAscending.remove(name);
}
}
public CheckResult checkAscension(Player player, double y1, double y2) {
int max = magic.ASCENSION_COUNT_MAX();
String string = "";
if (player.hasPotionEffect(PotionEffectType.JUMP)) {
max += 12;
string = " with jump potion";
}
Block block = player.getLocation().getBlock();
if (!isMovingExempt(player) && !Utilities.isInWater(player) && !VersionUtil.isFlying(player) && !justBroke(player) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && !player.isInsideVehicle() && !YAxisCheck.isMoveUpBlock(player.getLocation().add(0, -1, 0).getBlock()) && !YAxisCheck.isMoveUpBlock(player.getLocation().add(0, -1.5, 0).getBlock())) {
if (y1 < y2) {
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);
if (ascensionCount.get(player.getUniqueId()) >= max) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " ascended " + ascensionCount.get(player.getUniqueId()) + " times in a row (max = " + max + string + ")");
}
}
} else {
ascensionCount.put(player.getUniqueId(), 0);
}
}
return PASS;
}
public CheckResult checkSwing(Player player, Block block) {
UUID uuid = player.getUniqueId();
if (!isInstantBreakExempt(player)) {
if (!player.getInventory().getItemInHand().containsEnchantment(Enchantment.DIG_SPEED) && !(player.getInventory().getItemInHand().getType() == Material.SHEARS && block.getType() == Material.LEAVES)) {
if (blockPunches.get(uuid) != null && player.getGameMode() != GameMode.CREATIVE) {
int i = blockPunches.get(uuid);
if (i < magic.BLOCK_PUNCH_MIN()) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " tried to break a block of " + block.getType() + " after only " + i + " punches (min=" + magic.BLOCK_PUNCH_MIN() + ")");
} else {
blockPunches.put(uuid, 0); // it should reset after EACH block break.
}
}
}
}
return PASS;
}
public CheckResult checkFastBreak(Player player, Block block) {
int violations = magic.FASTBREAK_MAXVIOLATIONS();
long timemax = isInstantBreakExempt(player) ? 0 : Utilities.calcSurvivalFastBreak(player.getInventory().getItemInHand(), block.getType());
if (player.getGameMode() == GameMode.CREATIVE) {
violations = magic.FASTBREAK_MAXVIOLATIONS_CREATIVE();
timemax = magic.FASTBREAK_TIMEMAX_CREATIVE();
}
UUID uuid = player.getUniqueId();
if (!fastBreakViolation.containsKey(uuid)) {
fastBreakViolation.put(uuid, 0);
} else {
Long math = System.currentTimeMillis() - lastBlockBroken.get(uuid);
int i = fastBreakViolation.get(uuid);
if (i > violations && math < magic.FASTBREAK_MAXVIOLATIONTIME()) {
lastBlockBroken.put(uuid, System.currentTimeMillis());
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " broke blocks too fast " + i + " times in a row (max=" + violations + ")");
} else if (fastBreakViolation.get(uuid) > 0 && math > magic.FASTBREAK_MAXVIOLATIONTIME()) {
fastBreakViolation.put(uuid, 0);
}
}
if (!fastBreaks.containsKey(uuid) || !lastBlockBroken.containsKey(uuid)) {
if (!lastBlockBroken.containsKey(uuid)) {
lastBlockBroken.put(uuid, System.currentTimeMillis());
}
if (!fastBreaks.containsKey(uuid)) {
fastBreaks.put(uuid, 0);
}
} else {
Long math = System.currentTimeMillis() - lastBlockBroken.get(uuid);
if ((math != 0L && timemax != 0L)) {
if (math < timemax) {
if (fastBreakViolation.containsKey(uuid) && fastBreakViolation.get(uuid) > 0) {
fastBreakViolation.put(uuid, fastBreakViolation.get(uuid) + 1);
} else {
fastBreaks.put(uuid, fastBreaks.get(uuid) + 1);
}
blockBreakHolder.put(uuid, false);
}
if (fastBreaks.get(uuid) >= magic.FASTBREAK_LIMIT() && math < timemax) {
int i = fastBreaks.get(uuid);
fastBreaks.put(uuid, 0);
fastBreakViolation.put(uuid, fastBreakViolation.get(uuid) + 1);
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " tried to break " + i + " blocks in " + math + " ms (max=" + magic.FASTBREAK_LIMIT() + " in " + timemax + " ms)");
} else if (fastBreaks.get(uuid) >= magic.FASTBREAK_LIMIT() || fastBreakViolation.get(uuid) > 0) {
if (!blockBreakHolder.containsKey(uuid) || !blockBreakHolder.get(uuid)) {
blockBreakHolder.put(uuid, true);
} else {
fastBreaks.put(uuid, fastBreaks.get(uuid) - 1);
if (fastBreakViolation.get(uuid) > 0) {
fastBreakViolation.put(uuid, fastBreakViolation.get(uuid) - 1);
}
blockBreakHolder.put(uuid, false);
}
}
}
}
lastBlockBroken.put(uuid, System.currentTimeMillis()); // always keep a log going.
return PASS;
}
public CheckResult checkFastPlace(Player player) {
int violations = player.getGameMode() == GameMode.CREATIVE ? magic.FASTPLACE_MAXVIOLATIONS_CREATIVE() : magic.FASTPLACE_MAXVIOLATIONS();
long time = System.currentTimeMillis();
UUID uuid = player.getUniqueId();
if (!lastBlockPlaceTime.containsKey(uuid) || !fastPlaceViolation.containsKey(uuid)) {
lastBlockPlaceTime.put(uuid, 0L);
if (!fastPlaceViolation.containsKey(uuid)) {
fastPlaceViolation.put(uuid, 0);
}
} else if (fastPlaceViolation.containsKey(uuid) && fastPlaceViolation.get(uuid) > violations) {
AntiCheat.debugLog("Noted that fastPlaceViolation contains key " + uuid + " with value " + fastPlaceViolation.get(uuid));
Long math = System.currentTimeMillis() - lastBlockPlaced.get(uuid);
AntiCheat.debugLog("Player lastBlockPlaced value = " + lastBlockPlaced + ", diff=" + math);
if (lastBlockPlaced.get(uuid) > 0 && math < magic.FASTPLACE_MAXVIOLATIONTIME()) {
lastBlockPlaced.put(uuid, time);
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " placed blocks too fast " + fastBreakViolation.get(uuid) + " times in a row (max=" + violations + ")");
} else if (lastBlockPlaced.get(uuid) > 0 && math > magic.FASTPLACE_MAXVIOLATIONTIME()) {
AntiCheat.debugLog("Reset facePlaceViolation for " + uuid);
fastPlaceViolation.put(uuid, 0);
}
} else if (lastBlockPlaced.containsKey(uuid)) {
long last = lastBlockPlaced.get(uuid);
long lastTime = lastBlockPlaceTime.get(uuid);
long thisTime = time - last;
if (lastTime != 0 && thisTime < magic.FASTPLACE_TIMEMIN()) {
lastBlockPlaceTime.put(uuid, (time - last));
lastBlockPlaced.put(uuid, time);
fastPlaceViolation.put(uuid, fastPlaceViolation.get(uuid) + 1);
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " tried to place a block " + thisTime + " ms after the last one (min=" + magic.FASTPLACE_TIMEMIN() + " ms)");
}
lastBlockPlaceTime.put(uuid, (time - last));
}
lastBlockPlaced.put(uuid, time);
return PASS;
}
public void logBowWindUp(Player player) {
bowWindUp.put(player.getUniqueId(), System.currentTimeMillis());
}
public void logEatingStart(Player player) {
startEat.put(player.getUniqueId(), System.currentTimeMillis());
}
public void logHeal(Player player) {
lastHeal.put(player.getUniqueId(), System.currentTimeMillis());
}
public CheckResult checkChatSpam(Player player, String msg) {
UUID uuid = player.getUniqueId();
User user = manager.getUserManager().getUser(uuid);
if (user.getLastMessageTime() != -1) {
for (int i = 0; i < 2; i++) {
String m = user.getMessage(i);
if (m == null) {
break;
}
Long l = user.getMessageTime(i);
if (System.currentTimeMillis() - l > magic.CHAT_REPEAT_MIN() * 100) {
user.clearMessages();
break;
} else {
if (manager.getConfiguration().getConfig().blockChatSpamRepetition.getValue() && m.equalsIgnoreCase(msg) && i == 1) {
manager.getLoggingManager().logFineInfo(player.getName() + " spam-repeated \"" + msg + "\"");
return new CheckResult(CheckResult.Result.FAILED, lang.SPAM_WARNING());
} else if (manager.getConfiguration().getConfig().blockChatSpamSpeed.getValue() && System.currentTimeMillis() - user.getLastCommandTime() < magic.COMMAND_MIN() * 2) {
manager.getLoggingManager().logFineInfo(player.getName() + " spammed quickly \"" + msg + "\"");
return new CheckResult(CheckResult.Result.FAILED, lang.SPAM_WARNING());
}
}
}
}
user.addMessage(msg);
return PASS;
}
public CheckResult checkCommandSpam(Player player, String cmd) {
UUID uuid = player.getUniqueId();
User user = manager.getUserManager().getUser(uuid);
if (user.getLastCommandTime() != -1) {
for (int i = 0; i < 2; i++) {
String m = user.getCommand(i);
if (m == null) {
break;
}
Long l = user.getCommandTime(i);
if (System.currentTimeMillis() - l > magic.COMMAND_REPEAT_MIN() * 100) {
user.clearCommands();
break;
} else {
if (manager.getConfiguration().getConfig().blockCommandSpamRepetition.getValue() && m.equalsIgnoreCase(cmd) && i == 1) {
return new CheckResult(CheckResult.Result.FAILED, lang.SPAM_WARNING());
} else if (manager.getConfiguration().getConfig().blockCommandSpamSpeed.getValue() && System.currentTimeMillis() - user.getLastCommandTime() < magic.COMMAND_MIN() * 2) {
return new CheckResult(CheckResult.Result.FAILED, lang.SPAM_WARNING());
}
}
}
}
user.addCommand(cmd);
return PASS;
}
public CheckResult checkInventoryClicks(Player player) {
if (player.getGameMode() == GameMode.CREATIVE) {
return PASS;
}
UUID uuid = player.getUniqueId();
int clicks = 1;
if (inventoryClicks.containsKey(uuid)) {
clicks = inventoryClicks.get(uuid) + 1;
}
inventoryClicks.put(uuid, clicks);
if (clicks == 1) {
inventoryTime.put(uuid, System.currentTimeMillis());
} else if (clicks == magic.INVENTORY_CHECK()) {
long time = System.currentTimeMillis() - inventoryTime.get(uuid);
inventoryClicks.put(uuid, 0);
if (time < magic.INVENTORY_TIMEMIN()) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " clicked inventory slots " + clicks + " times in " + time + " ms (max=" + magic.INVENTORY_CHECK() + " in " + magic.INVENTORY_TIMEMIN() + " ms)");
}
}
return PASS;
}
public CheckResult checkAutoTool(Player player) {
if (itemInHand.containsKey(player.getUniqueId()) && itemInHand.get(player.getUniqueId()) != player.getItemInHand().getType()) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " switched tools too fast (had " + itemInHand.get(player.getName()) + ", has " + player.getItemInHand().getType() + ")");
} else {
return PASS;
}
}
public CheckResult checkSprintDamage(Player player) {
if (isDoing(player, sprinted, magic.SPRINT_MIN())) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " sprinted and damaged an entity too fast (min sprint=" + magic.SPRINT_MIN() + " ms)");
} else {
return PASS;
}
}
public CheckResult checkFastHeal(Player player) {
if (lastHeal.containsKey(player.getUniqueId())) // Otherwise it was modified by a plugin, don't worry about it.
{
long healTime = VersionUtil.getHealTime();
long l = lastHeal.get(player.getUniqueId());
lastHeal.remove(player.getUniqueId());
if ((System.currentTimeMillis() - l) < healTime) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " healed too quickly (time=" + (System.currentTimeMillis() - l) + " ms, min=" + healTime + " ms)");
}
}
return PASS;
}
public CheckResult checkFastEat(Player player) {
if (startEat.containsKey(player.getUniqueId())) // Otherwise it was modified by a plugin, don't worry about it.
{
long l = startEat.get(player.getUniqueId());
startEat.remove(player.getUniqueId());
if ((System.currentTimeMillis() - l) < magic.EAT_TIME_MIN()) {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " ate too quickly (time=" + (System.currentTimeMillis() - l) + " ms, min=" + magic.EAT_TIME_MIN() + " ms)");
}
}
return PASS;
}
public void logInstantBreak(final Player player) {
instantBreakExempt.put(player.getUniqueId(), System.currentTimeMillis());
}
public boolean isInstantBreakExempt(Player player) {
return isDoing(player, instantBreakExempt, magic.INSTANT_BREAK_TIME());
}
public void logSprint(final Player player) {
sprinted.put(player.getUniqueId(), System.currentTimeMillis());
}
public boolean isHoveringOverWaterAfterViolation(Player player) {
if (WaterWalkCheck.waterSpeedViolation.containsKey(player.getUniqueId())) {
if (WaterWalkCheck.waterSpeedViolation.get(player.getUniqueId()) >= magic.WATER_SPEED_VIOLATION_MAX() && Utilities.isHoveringOverWater(player.getLocation())) {
return true;
}
}
return false;
}
public void logBlockBreak(final Player player) {
brokenBlock.put(player.getUniqueId(), System.currentTimeMillis());
}
public boolean justBroke(Player player) {
return isDoing(player, brokenBlock, magic.BLOCK_BREAK_MIN());
}
public void logVelocity(final Player player) {
velocitized.put(player.getUniqueId(), System.currentTimeMillis());
}
public boolean justVelocity(Player player) {
return (velocitized.containsKey(player.getUniqueId()) ? (System.currentTimeMillis() - velocitized.get(player.getUniqueId())) < magic.VELOCITY_CHECKTIME() : false);
}
public boolean extendVelocityTime(final Player player) {
if (velocitytrack.containsKey(player.getUniqueId())) {
velocitytrack.put(player.getUniqueId(), velocitytrack.get(player.getUniqueId()) + 1);
if (velocitytrack.get(player.getUniqueId()) > magic.VELOCITY_MAXTIMES()) {
velocitized.put(player.getUniqueId(), System.currentTimeMillis() + magic.VELOCITY_PREVENT());
manager.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(manager.getPlugin(), new Runnable() {
@Override
public void run() {
velocitytrack.put(player.getUniqueId(), 0);
}
}, magic.VELOCITY_SCHETIME() * 20L);
return true;
}
} else {
velocitytrack.put(player.getUniqueId(), 0);
}
return false;
}
public void logBlockPlace(final Player player) {
placedBlock.put(player.getUniqueId(), System.currentTimeMillis());
}
public boolean justPlaced(Player player) {
return isDoing(player, placedBlock, magic.BLOCK_PLACE_MIN());
}
public void logDamage(final Player player, int type) {
long time;
switch (type) {
case 1:
time = magic.DAMAGE_TIME();
break;
case 2:
time = magic.KNOCKBACK_DAMAGE_TIME();
break;
case 3:
time = magic.EXPLOSION_DAMAGE_TIME();
break;
default:
time = magic.DAMAGE_TIME();
break;
}
FlightCheck.movingExempt.put(player.getUniqueId(), System.currentTimeMillis() + time);
// Only map in which termination time is calculated beforehand.
}
public void logEnterExit(final Player player) {
FlightCheck.movingExempt.put(player.getUniqueId(), System.currentTimeMillis() + magic.ENTERED_EXITED_TIME());
}
public void logToggleSneak(final Player player) {
FlightCheck.movingExempt.put(player.getUniqueId(), System.currentTimeMillis() + magic.SNEAK_TIME());
}
public void logTeleport(final Player player) {
FlightCheck.movingExempt.put(player.getUniqueId(), System.currentTimeMillis() + magic.TELEPORT_TIME());
/* Data for fly/speed should be reset */
nofallViolation.remove(player.getUniqueId());
FlightCheck.blocksOverFlight.remove(player.getUniqueId());
YAxisCheck.yAxisViolations.remove(player.getUniqueId());
YAxisCheck.yAxisLastViolation.remove(player.getUniqueId());
YAxisCheck.lastYcoord.remove(player.getUniqueId());
YAxisCheck.lastYtime.remove(player.getUniqueId());
GlideCheck.lastFallDistance.remove(player.getUniqueId());
GlideCheck.lastDiff.remove(player.getUniqueId());
GlideCheck.violations.remove(player.getUniqueId());
}
public void logExitFly(final Player player) {
FlightCheck.movingExempt.put(player.getUniqueId(), System.currentTimeMillis() + magic.EXIT_FLY_TIME());
}
public void logJoin(final Player player) {
FlightCheck.movingExempt.put(player.getUniqueId(), System.currentTimeMillis() + magic.JOIN_TIME());
}
public boolean isMovingExempt(Player player) {
return isDoing(player, FlightCheck.movingExempt, -1);
}
public boolean isAscending(Player player) {
return isAscending.contains(player.getUniqueId());
}
private boolean isDoing(Player player, Map<UUID, Long> map, double max) {
if (map.containsKey(player.getUniqueId())) {
if (max != -1) {
if (((System.currentTimeMillis() - map.get(player.getUniqueId())) / 1000) > max) {
map.remove(player.getUniqueId());
return false;
} else {
return true;
}
} else {
// Termination time has already been calculated
if (map.get(player.getUniqueId()) < System.currentTimeMillis()) {
map.remove(player.getUniqueId());
return false;
} else {
return true;
}
}
} else {
return false;
}
}
public boolean hasJumpPotion(Player player) {
return player.hasPotionEffect(PotionEffectType.JUMP);
}
public boolean hasSpeedPotion(Player player) {
return player.hasPotionEffect(PotionEffectType.SPEED);
}
public void processChatSpammer(Player player) {
User user = manager.getUserManager().getUser(player.getUniqueId());
int level = chatLevel.containsKey(user.getUUID()) ? chatLevel.get(user.getUUID()) : 0;
if (player != null && player.isOnline() && level >= magic.CHAT_ACTION_ONE_LEVEL()) {
String event = level >= magic.CHAT_ACTION_TWO_LEVEL() ? manager.getConfiguration().getConfig().chatSpamActionTwo.getValue() : manager.getConfiguration().getConfig().chatSpamActionOne.getValue();
manager.getUserManager().execute(manager.getUserManager().getUser(player.getUniqueId()), Utilities.stringToList(event), CheckType.CHAT_SPAM, lang.SPAM_KICK_REASON(), Utilities.stringToList(lang.SPAM_WARNING()), lang.SPAM_BAN_REASON());
}
chatLevel.put(user.getUUID(), level + 1);
}
public void processCommandSpammer(Player player) {
User user = manager.getUserManager().getUser(player.getUniqueId());
int level = commandLevel.containsKey(user.getUUID()) ? commandLevel.get(user.getUUID()) : 0;
if (player != null && player.isOnline() && level >= magic.COMMAND_ACTION_ONE_LEVEL()) {
String event = level >= magic.COMMAND_ACTION_TWO_LEVEL() ? manager.getConfiguration().getConfig().commandSpamActionTwo.getValue() : manager.getConfiguration().getConfig().commandSpamActionOne.getValue();
manager.getUserManager().execute(manager.getUserManager().getUser(player.getUniqueId()), Utilities.stringToList(event), CheckType.COMMAND_SPAM, lang.SPAM_KICK_REASON(), Utilities.stringToList(lang.SPAM_WARNING()), lang.SPAM_BAN_REASON());
}
commandLevel.put(user.getUUID(), level + 1);
}
public int increment(Player player, Map<UUID, Integer> ascensionCount2, int num) {
UUID name = player.getUniqueId();
if (ascensionCount2.get(name) == null) {
ascensionCount2.put(name, 1);
return 1;
} else {
int amount = ascensionCount2.get(name) + 1;
if (amount < num + 1) {
ascensionCount2.put(name, amount);
return amount;
} else {
ascensionCount2.put(name, num);
return num;
}
}
}
public int incrementOld(Player player, Map<UUID, Integer> ascensionCount2, int num) {
UUID uuid = player.getUniqueId();
if (ascensionCount2.get(uuid) == null) {
ascensionCount2.put(uuid, 1);
return 1;
} else {
int amount = ascensionCount2.get(uuid) + 1;
if (amount < num + 1) {
ascensionCount2.put(uuid, amount);
return amount;
} else {
ascensionCount2.put(uuid, num);
return num;
}
}
}
public boolean silentMode() {
return manager.getConfiguration().getConfig().silentMode.getValue();
}
}
@@ -0,0 +1,61 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.check;
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,131 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.check;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.api.CheckFailEvent;
import com.rammelkast.anticheatreloaded.util.Permission;
import com.rammelkast.anticheatreloaded.util.User;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* <p/>
* All the types of checks and their corresponding permission nodes.
*/
public enum CheckType {
ZOMBE_FLY(Permission.CHECK_ZOMBE_FLY),
ZOMBE_NOCLIP(Permission.CHECK_ZOMBE_NOCLIP),
ZOMBE_CHEAT(Permission.CHECK_ZOMBE_CHEAT),
FLY(Permission.CHECK_FLY),
WATER_WALK(Permission.CHECK_WATERWALK),
NO_SWING(Permission.CHECK_NOSWING),
FAST_BREAK(Permission.CHECK_FASTBREAK),
FAST_PLACE(Permission.CHECK_FASTPLACE),
CHAT_SPAM(Permission.CHECK_CHATSPAM),
COMMAND_SPAM(Permission.CHECK_COMMANDSPAM),
SPRINT(Permission.CHECK_SPRINT),
SNEAK(Permission.CHECK_SNEAK),
SPEED(Permission.CHECK_SPEED),
VCLIP(Permission.CHECK_VCLIP),
SPIDER(Permission.CHECK_SPIDER),
NOFALL(Permission.CHECK_NOFALL),
FAST_BOW(Permission.CHECK_FASTBOW),
FAST_EAT(Permission.CHECK_FASTEAT),
FAST_HEAL(Permission.CHECK_FASTHEAL),
FORCEFIELD(Permission.CHECK_FORCEFIELD),
LONG_REACH(Permission.CHECK_LONGREACH),
FAST_PROJECTILE(Permission.CHECK_FASTPROJECTILE),
ITEM_SPAM(Permission.CHECK_ITEMSPAM),
FAST_INVENTORY(Permission.CHECK_FASTINVENTORY),
AUTOTOOL(Permission.CHECK_AUTOTOOL),
KILLAURA(Permission.CHECK_KILLAURA),
BLINK(Permission.CHECK_BLINK),
VELOCITY(Permission.VELOCITY),
CRITICALS(Permission.CRITICALS);
private final Permission permission;
private final Map<UUID, Integer> level = new HashMap<UUID, Integer>();
/**
* Initialize a CheckType
*
* @param perm Permission that applies to this check
*/
private CheckType(Permission perm) {
this.permission = perm;
}
/**
* Determine whether a player has permission to bypass this check
*
* @param player Player to check
* @return true if the player can bypass
*/
public boolean checkPermission(Player player) {
return permission.get(player);
}
/**
* Log the failure of this check
*
* @param user User who failed the check
*/
public void logUse(User user) {
int amount = level.get(user.getUUID()) == null ? 1 : level.get(user.getUUID()) + 1;
level.put(user.getUUID(), amount);
Bukkit.getServer().getPluginManager().callEvent(new CheckFailEvent(user, this));
}
/**
* Clear failure history of this check for a user
*
* @param UUID User's UUID to clear
*/
public void clearUse(UUID uuid) {
level.put(uuid, 0);
}
/**
* Get how many times a user has failed this check
*
* @param UUID User's UUID
* @return number of times failed
*/
public int getUses(UUID uuid) {
return level.get(uuid) != null ? level.get(uuid) : 0;
}
/**
* Get the reference name of a check
*
* @param type Type of check
* @return reference name
*/
public static String getName(CheckType type) {
char[] chars = type.toString().replaceAll("_", " ").toLowerCase().toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
return new String(chars);
}
}
@@ -0,0 +1,32 @@
package com.rammelkast.anticheatreloaded.check.combat;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.potion.PotionEffectType;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.event.EventListener;
import com.rammelkast.anticheatreloaded.util.Utilities;
public class CriticalsCheck {
public static void doDamageEvent(EntityDamageByEntityEvent e, Player damager) {
if (!(e.getDamager() instanceof Player) || e.getCause() != DamageCause.ENTITY_ATTACK)
return;
Player p = (Player)e.getDamager();
if (isCritical(p)) {
if ((p.getLocation().getY() % 1.0 == 0 || p.getLocation().getY() % 0.5 == 0) && p.getLocation().clone().subtract(0, 1.0, 0).getBlock().getType().isSolid()) {
e.setCancelled(true);
EventListener.log(new CheckResult(CheckResult.Result.FAILED, p.getName() + " failed Criticals, tried to do a critical without needed conditions").getMessage(), p, CheckType.CRITICALS);
}
}
}
private static boolean isCritical(Player player) {
return player.getFallDistance() > 0.0f && !player.isOnGround() && !player.isInsideVehicle() && !player.hasPotionEffect(PotionEffectType.BLINDNESS) && !Utilities.isHoveringOverWater(player.getLocation()) && player.getEyeLocation().getBlock().getType() != Material.LADDER;
}
}
@@ -0,0 +1,89 @@
package com.rammelkast.anticheatreloaded.check.combat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.event.EventListener;
import com.rammelkast.anticheatreloaded.util.NPC_1_11;
import com.rammelkast.anticheatreloaded.util.VersionUtil;
/**
* @author Rammelkast
*/
public class KillAuraCheck {
private static final Map<UUID, NPC_1_11> NPC_LIST = new HashMap<UUID, NPC_1_11>();
private static final Map<UUID, Integer> VL_COUNT = new HashMap<UUID, Integer>();
public static void cleanPlayer(Player p) {
if (!VersionUtil.getVersion().equals("v1_11_R1")) {
return;
}
NPC_LIST.remove(p.getUniqueId());
}
public static void listenPackets() {
if (!VersionUtil.getVersion().equals("v1_11_R1")) {
return;
}
AntiCheat.getProtocolManager().addPacketListener(new PacketAdapter(AntiCheat.getPlugin(), ListenerPriority.NORMAL, new PacketType[] {PacketType.Play.Client.USE_ENTITY}) {
@Override
public void onPacketReceiving(PacketEvent e) {
Player p = e.getPlayer();
if (!NPC_LIST.containsKey(p.getUniqueId()))
return;
int id = e.getPacket().getIntegers().read(0);
if (NPC_LIST.containsKey(p.getUniqueId())) {
if (NPC_LIST.get(p.getUniqueId()).getID() != id) {
return;
}
}
if (!VL_COUNT.containsKey(p.getUniqueId())) {
VL_COUNT.put(p.getUniqueId(), 1);
NPC_LIST.get(p.getUniqueId()).damage();
}else {
VL_COUNT.put(p.getUniqueId(), VL_COUNT.get(p.getUniqueId()) + 1);
if (VL_COUNT.get(p.getUniqueId()) >= 5) {
EventListener.log(new CheckResult(CheckResult.Result.FAILED, p.getName() + " failed KillAura (botcheck), hit the bot " + VL_COUNT.get(p.getUniqueId()) + " times (max=5)").getMessage(), p, CheckType.BLINK);
VL_COUNT.remove(p.getUniqueId());
}
}
}
});
}
public static void doDamageEvent(EntityDamageByEntityEvent e, Player p) {
if (!VersionUtil.getVersion().equals("v1_11_R1")) {
return;
}
if (NPC_LIST.containsKey(p.getUniqueId()))
NPC_LIST.get(p.getUniqueId()).damage(e, p);
else {
NPC_1_11 npc = new NPC_1_11(p);
NPC_LIST.put(p.getUniqueId(), npc);
npc.spawn();
}
}
public static void doMove(PlayerMoveEvent e) {
if (!VersionUtil.getVersion().equals("v1_11_R1")) {
return;
}
if (NPC_LIST.containsKey(e.getPlayer().getUniqueId())) {
NPC_LIST.get(e.getPlayer().getUniqueId()).move(e);
}
}
}
@@ -0,0 +1,51 @@
package com.rammelkast.anticheatreloaded.check.combat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.scheduler.BukkitRunnable;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.event.EventListener;
public class VelocityCheck {
private static final Map<UUID, Integer> VL_COUNT = new HashMap<UUID, Integer>();
public static void cleanPlayer(Player p) {
VL_COUNT.remove(p.getUniqueId());
}
public static void runCheck(EntityDamageByEntityEvent e, final Player p) {
if (AntiCheat.getManager().getCheckManager().isOpExempt(p) || AntiCheat.getManager().getCheckManager().isExempt(p, CheckType.VELOCITY))
return;
final Location then = p.getLocation();
new BukkitRunnable() {
@Override
public void run() {
if (!p.isOnline())
return;
if (then.distance(p.getLocation()) < 0.125) {
if (!VL_COUNT.containsKey(p.getUniqueId()))
VL_COUNT.put(p.getUniqueId(), 1);
else {
VL_COUNT.put(p.getUniqueId(), VL_COUNT.get(p.getUniqueId()) + 1);
if (VL_COUNT.get(p.getUniqueId()) > AntiCheat.getManager().getBackend().getMagic().VELOCITY_AMT()) {
EventListener.log(new CheckResult(CheckResult.Result.FAILED, p.getName() + " failed Velocity, had zero/low velocity " + VL_COUNT.get(p.getUniqueId()) + " times (max=" + AntiCheat.getManager().getBackend().getMagic().VELOCITY_AMT() + ", dist=" + then.distance(p.getLocation()) + ")").getMessage(), p, CheckType.VELOCITY);
VL_COUNT.remove(p.getUniqueId());
}
}
}else {
VL_COUNT.remove(p.getUniqueId());
}
}
}.runTaskLater(AntiCheat.getPlugin(), 4);
}
}
@@ -0,0 +1,59 @@
package com.rammelkast.anticheatreloaded.check.movement;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.event.EventListener;
/**
* @author Rammelkast
*/
public class BlinkCheck {
public static final Map<UUID, Integer> MOVE_COUNT = new HashMap<UUID, Integer>();
public static void startTimer() {
new BukkitRunnable() {
@Override
public void run() {
MOVE_COUNT.clear();
}
}.runTaskTimer(AntiCheat.getPlugin(), 0, 20);
}
public static void listenPackets() {
AntiCheat.getProtocolManager().addPacketListener(new PacketAdapter(AntiCheat.getPlugin(), ListenerPriority.NORMAL, new PacketType[] {PacketType.Play.Client.POSITION, PacketType.Play.Client.POSITION_LOOK}) {
@Override
public void onPacketReceiving(PacketEvent e) {
Player p = e.getPlayer();
Location cur = e.getPlayer().getLocation();
if (!MOVE_COUNT.containsKey(p.getUniqueId()))
MOVE_COUNT.put(p.getUniqueId(), 1);
else {
MOVE_COUNT.put(p.getUniqueId(), MOVE_COUNT.get(p.getUniqueId()) + 1);
if (AntiCheat.getManager().getCheckManager().checkInWorld(p) && !AntiCheat.getManager().getCheckManager().isOpExempt(p) && !AntiCheat.getManager().getCheckManager().isExempt(p, CheckType.BLINK)) {
if (MOVE_COUNT.get(p.getUniqueId()) > AntiCheat.getManager().getBackend().getMagic().BLINK_PACKET()) {
EventListener.log(new CheckResult(CheckResult.Result.FAILED, p.getName() + " failed Blink, sent " + MOVE_COUNT.get(p.getUniqueId()) + " packets in one second (max=" + AntiCheat.getManager().getBackend().getMagic().BLINK_PACKET() + ")").getMessage(), p, CheckType.BLINK);
MOVE_COUNT.remove(p.getUniqueId());
e.setCancelled(true);
e.getPlayer().teleport(cur);
}
}
}
}
});
}
}
@@ -0,0 +1,19 @@
package com.rammelkast.anticheatreloaded.check.movement;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.util.Distance;
/**
* TODO
*/
public class ElytraFly {
private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED);
public static CheckResult runCheck(Player player, Distance distance) {
return PASS;
}
}
@@ -0,0 +1,94 @@
package com.rammelkast.anticheatreloaded.check.movement;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.util.Distance;
import com.rammelkast.anticheatreloaded.util.Utilities;
import com.rammelkast.anticheatreloaded.util.VersionUtil;
/**
*
* @author Marco TODO rewrite this check
*/
public class FlightCheck {
private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED);
public static Map<UUID, Double> blocksOverFlight = new HashMap<UUID, Double>();
public static Map<UUID, Long> movingExempt = new HashMap<UUID, Long>();
public static CheckResult runCheck(Player player, Distance distance) {
if (distance.getYDifference() > AntiCheat.getManager().getBackend().getMagic().TELEPORT_MIN()
|| VersionUtil.isFlying(player)) {
// This was a teleport or user is flying/elyta'ing, so we don't care
// about it.
return PASS;
}
final UUID uuid = player.getUniqueId();
final double y1 = distance.fromY();
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 (!blocksOverFlight.containsKey(uuid)) {
blocksOverFlight.put(uuid, 0D);
}
blocksOverFlight.put(uuid, (blocksOverFlight.get(uuid) + distance.getXDifference()
+ distance.getYDifference() + distance.getZDifference()));
if (y1 > y2) {
blocksOverFlight.put(uuid, (blocksOverFlight.get(uuid) - distance.getYDifference()));
}
if (blocksOverFlight.get(uuid) > AntiCheat.getManager().getBackend().getMagic().FLIGHT_BLOCK_LIMIT()
&& (y1 <= y2)) {
return new CheckResult(CheckResult.Result.FAILED,
player.getName() + " flew over " + blocksOverFlight.get(uuid) + " blocks (max="
+ AntiCheat.getManager().getBackend().getMagic().FLIGHT_BLOCK_LIMIT() + ")");
}
} else {
blocksOverFlight.put(uuid, 0D);
}
return PASS;
}
public static boolean isMovingExempt(Player player) {
return isDoing(player, movingExempt, -1);
}
private static boolean isDoing(Player player, Map<UUID, Long> map, double max) {
if (map.containsKey(player.getUniqueId())) {
if (max != -1) {
if (((System.currentTimeMillis() - map.get(player.getUniqueId())) / 1000) > max) {
map.remove(player.getUniqueId());
return false;
} else {
return true;
}
} else {
// Termination time has already been calculated
if (map.get(player.getUniqueId()) < System.currentTimeMillis()) {
map.remove(player.getUniqueId());
return false;
} else {
return true;
}
}
} else {
return false;
}
}
}
@@ -0,0 +1,72 @@
package com.rammelkast.anticheatreloaded.check.movement;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.Backend;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.util.Distance;
import com.rammelkast.anticheatreloaded.util.Utilities;
import com.rammelkast.anticheatreloaded.util.VersionUtil;
public class GlideCheck {
private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED);
public static Map<UUID, Double> lastDiff = new HashMap<UUID, Double>();
public static Map<UUID, Float> lastFallDistance = new HashMap<UUID, Float>();
public static Map<UUID, Integer> violations = new HashMap<UUID, Integer>();
public static CheckResult runCheck(Player player, Distance distance) {
if (VersionUtil.isFlying(player)) {
return PASS;
}
if (!lastDiff.containsKey(player.getUniqueId())) {
lastDiff.put(player.getUniqueId(), distance.getYDifference());
return PASS;
}
if (!lastFallDistance.containsKey(player.getUniqueId())) {
lastFallDistance.put(player.getUniqueId(), player.getFallDistance());
return PASS;
}
double yDiff = distance.getYDifference();
float fallDistance = player.getFallDistance();
if (yDiff == lastDiff.get(player.getUniqueId()) && fallDistance > lastFallDistance.get(player.getUniqueId())) {
if (!violations.containsKey(player.getUniqueId())) {
violations.put(player.getUniqueId(), 1);
} else {
if (violations.get(player.getUniqueId()) + 1 >= AntiCheat.getManager().getBackend().getMagic().GLIDE_LIMIT()) {
violations.remove(player.getUniqueId());
Location to = player.getLocation();
to.setY(to.getY() - distanceToFall(to));
player.teleport(to);
return new CheckResult(CheckResult.Result.FAILED,
player.getName() + " was set back for gliding (yDiff=" + new BigDecimal(yDiff).setScale(2, BigDecimal.ROUND_UP) + ")");
} else {
violations.put(player.getUniqueId(), violations.get(player.getUniqueId()) + 1);
}
}
}
lastDiff.put(player.getUniqueId(), distance.getYDifference());
lastFallDistance.put(player.getUniqueId(), player.getFallDistance());
return PASS;
}
private static double distanceToFall(Location location) {
location = location.clone();
double firstY = location.getY();
while (location.clone().add(0, -0.1, 0).getBlock().getType() == Material.AIR)
location.add(0, -0.1, 0);
return firstY - location.getY();
}
}
@@ -0,0 +1,79 @@
package com.rammelkast.anticheatreloaded.check.movement;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.util.VersionUtil;
public class SpeedCheck {
private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED);
public static Map<UUID, Integer> speedViolation = new HashMap<UUID, Integer>();
public static boolean isSpeedExempt(Player player) {
return AntiCheat.getManager().getBackend().isMovingExempt(player)
|| AntiCheat.getManager().getBackend().justVelocity(player) || VersionUtil.isFlying(player);
}
public static CheckResult checkXZSpeed(Player player, double x, double z) {
if (!isSpeedExempt(player) && player.getVehicle() == null) {
String reason = "";
double max = AntiCheat.getManager().getBackend().getMagic().XZ_SPEED_MAX();
if (player.getLocation().getBlock().getType() == Material.SOUL_SAND) {
if (player.isSprinting()) {
reason = "on soulsand while sprinting ";
max = AntiCheat.getManager().getBackend().getMagic().XZ_SPEED_MAX_SOULSAND_SPRINT();
} else if (player.hasPotionEffect(PotionEffectType.SPEED)) {
reason = "on soulsand with speed potion ";
max = AntiCheat.getManager().getBackend().getMagic().XZ_SPEED_MAX_SOULSAND_POTION();
} else {
reason = "on soulsand ";
max = AntiCheat.getManager().getBackend().getMagic().XZ_SPEED_MAX_SOULSAND();
}
} else if (VersionUtil.isFlying(player)) {
reason = "while flying ";
max = AntiCheat.getManager().getBackend().getMagic().XZ_SPEED_MAX_FLY();
} else if (player.hasPotionEffect(PotionEffectType.SPEED)) {
if (player.isSprinting()) {
reason = "with speed potion while sprinting ";
max = AntiCheat.getManager().getBackend().getMagic().XZ_SPEED_MAX_POTION_SPRINT();
} else {
reason = "with speed potion ";
max = AntiCheat.getManager().getBackend().getMagic().XZ_SPEED_MAX_POTION();
}
} else if (player.isSprinting()) {
reason = "while sprinting ";
max = AntiCheat.getManager().getBackend().getMagic().XZ_SPEED_MAX_SPRINT();
}
float speed = player.getWalkSpeed();
max += speed > 0 ? player.getWalkSpeed() - 0.2f : 0;
if (x > max || z > max) {
int num = AntiCheat.getManager().getBackend().increment(player, speedViolation,
AntiCheat.getManager().getBackend().getMagic().SPEED_MAX());
if (num >= AntiCheat.getManager().getBackend().getMagic().SPEED_MAX()) {
return new CheckResult(CheckResult.Result.FAILED,
player.getName() + "'s speed was too high " + reason + num + " times in a row (max="
+ AntiCheat.getManager().getBackend().getMagic().SPEED_MAX() + ", speed="
+ (x > z ? x : z) + ", max speed=" + max + ")");
} else {
return PASS;
}
} else {
speedViolation.put(player.getUniqueId(), 0);
return PASS;
}
} else {
return PASS;
}
}
}
@@ -0,0 +1,106 @@
package com.rammelkast.anticheatreloaded.check.movement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.util.Utilities;
/**
* This check seems to be broken/outdated
*/
public class WaterWalkCheck {
private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED);
public static List<UUID> isInWater = new ArrayList<UUID>();
public static List<UUID> isInWaterCache = new ArrayList<UUID>();
public static Map<UUID, Integer> waterSpeedViolation = new HashMap<UUID, Integer>();
public static Map<UUID, Integer> waterAscensionViolation = new HashMap<UUID, Integer>();
/**
* TODO check & fix for 1.11? (see #25)
*/
public static CheckResult runCheck(Player player, double x, double y, double z) {
Block block = player.getLocation().getBlock();
UUID uuid = player.getUniqueId();
if (player.getVehicle() == null && !player.isFlying()) {
if (block.isLiquid()) {
if (isInWater.contains(uuid)) {
if (isInWaterCache.contains(uuid)) {
if (player.getNearbyEntities(1, 1, 1).isEmpty()) {
boolean b;
if (!Utilities.sprintFly(player)) {
b = x > AntiCheat.getManager().getBackend().getMagic().XZ_SPEED_MAX_WATER()
|| z > AntiCheat.getManager().getBackend().getMagic().XZ_SPEED_MAX_WATER();
} else {
b = x > AntiCheat.getManager().getBackend().getMagic().XZ_SPEED_MAX_WATER_SPRINT()
|| z > AntiCheat.getManager().getBackend().getMagic()
.XZ_SPEED_MAX_WATER_SPRINT();
}
if (!b && !Utilities.isFullyInWater(player.getLocation())
&& Utilities.isHoveringOverWater(player.getLocation(), 1) && y == 0D
&& !block.getType().equals(Material.WATER_LILY)) {
b = true;
}
if (b) {
if (waterSpeedViolation.containsKey(uuid)) {
int v = waterSpeedViolation.get(uuid);
if (v >= AntiCheat.getManager().getBackend().getMagic()
.WATER_SPEED_VIOLATION_MAX()) {
waterSpeedViolation.put(uuid, 0);
return new CheckResult(CheckResult.Result.FAILED,
player.getName() + " stood on water " + v + " times (can't stand on "
+ block.getType() + " or "
+ block.getRelative(BlockFace.DOWN).getType() + ")");
} else {
waterSpeedViolation.put(uuid, v + 1);
}
} else {
waterSpeedViolation.put(uuid, 1);
}
}
}
} else {
isInWaterCache.add(uuid);
return PASS;
}
} else {
isInWater.add(uuid);
return PASS;
}
} else if (block.getRelative(BlockFace.DOWN).isLiquid()
&& !AntiCheat.getManager().getBackend().isAscending(player) && Utilities.cantStandAt(block)
&& Utilities.cantStandAt(block.getRelative(BlockFace.DOWN))) {
if (waterAscensionViolation.containsKey(uuid)) {
int v = waterAscensionViolation.get(uuid);
if (v >= AntiCheat.getManager().getBackend().getMagic().WATER_ASCENSION_VIOLATION_MAX()) {
waterAscensionViolation.put(uuid, 0);
return new CheckResult(CheckResult.Result.FAILED,
player.getName() + " stood on water " + v + " times (can't stand on " + block.getType()
+ " or " + block.getRelative(BlockFace.DOWN).getType() + ")");
} else {
waterAscensionViolation.put(uuid, v + 1);
}
} else {
waterAscensionViolation.put(uuid, 1);
}
} else {
isInWater.remove(uuid);
isInWaterCache.remove(uuid);
}
}
return PASS;
}
}
@@ -0,0 +1,111 @@
package com.rammelkast.anticheatreloaded.check.movement;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.util.Distance;
import com.rammelkast.anticheatreloaded.util.Utilities;
import com.rammelkast.anticheatreloaded.util.VersionUtil;
public class YAxisCheck {
private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED);
public static Map<UUID, Double> lastYcoord = new HashMap<UUID, Double>();
public static Map<UUID, Long> lastYtime = new HashMap<UUID, Long>();
public static Map<UUID, Integer> yAxisViolations = new HashMap<UUID, Integer>();
public static Map<UUID, Long> yAxisLastViolation = new HashMap<UUID, Long>();
private static boolean hasJumpPotion(Player player) {
return player.hasPotionEffect(PotionEffectType.JUMP);
}
public static CheckResult runCheck(Player player, Distance distance) {
if (distance.getYDifference() > AntiCheat.getManager().getBackend().getMagic().TELEPORT_MIN()
|| distance.getYDifference() < 0 || VersionUtil.isFlying(player)) {
return PASS;
}
if (!FlightCheck.isMovingExempt(player) && !Utilities.isClimbableBlock(player.getLocation().getBlock())
&& !Utilities.isClimbableBlock(player.getLocation().add(0, -1, 0).getBlock())
&& !player.isInsideVehicle() && !Utilities.isInWater(player) && !hasJumpPotion(player)
&& !isMoveUpBlock(player.getLocation().add(0, -1, 0).getBlock())
&& !isMoveUpBlock(player.getLocation().add(0, -1.5, 0).getBlock())) {
double y1 = player.getLocation().getY();
UUID uuid = player.getUniqueId();
// Fix Y axis spam.
if (!lastYcoord.containsKey(uuid) || !lastYtime.containsKey(uuid)
|| !yAxisLastViolation.containsKey(uuid)) {
lastYcoord.put(uuid, y1);
yAxisViolations.put(uuid, 0);
yAxisLastViolation.put(uuid, 0L);
lastYtime.put(uuid, System.currentTimeMillis());
} else {
if (y1 > lastYcoord.get(uuid)
&& yAxisViolations.get(uuid) > AntiCheat.getManager().getBackend().getMagic().Y_MAXVIOLATIONS()
&& (System.currentTimeMillis() - yAxisLastViolation.get(uuid)) < AntiCheat.getManager()
.getBackend().getMagic().Y_MAXVIOTIME()) {
Location g = player.getLocation();
yAxisViolations.put(uuid, yAxisViolations.get(uuid) + 1);
yAxisLastViolation.put(uuid, System.currentTimeMillis());
if (!AntiCheat.getManager().getBackend().silentMode()) {
g.setY(lastYcoord.get(uuid));
if (g.getBlock().getType() == Material.AIR) {
player.teleport(g);
}
}
return new CheckResult(CheckResult.Result.FAILED,
player.getName() + " tried to fly on y-axis " + yAxisViolations.get(uuid) + " times (max ="
+ AntiCheat.getManager().getBackend().getMagic().Y_MAXVIOLATIONS() + ")");
} else {
if (yAxisViolations.get(uuid) > AntiCheat.getManager().getBackend().getMagic().Y_MAXVIOLATIONS()
&& (System.currentTimeMillis() - yAxisLastViolation.get(uuid)) > AntiCheat.getManager()
.getBackend().getMagic().Y_MAXVIOTIME()) {
yAxisViolations.put(uuid, 0);
yAxisLastViolation.put(uuid, 0L);
}
}
long i = System.currentTimeMillis() - lastYtime.get(uuid);
double diff = AntiCheat.getManager().getBackend().getMagic().Y_MAXDIFF()
+ (Utilities.isStair(player.getLocation().add(0, -1, 0).getBlock()) ? 0.5 : 0.0);
if ((y1 - lastYcoord.get(uuid)) > diff && i < AntiCheat.getManager().getBackend().getMagic().Y_TIME()) {
Location g = player.getLocation();
yAxisViolations.put(uuid, yAxisViolations.get(uuid) + 1);
yAxisLastViolation.put(uuid, System.currentTimeMillis());
if (!AntiCheat.getManager().getBackend().silentMode()) {
g.setY(lastYcoord.get(uuid));
if (g.getBlock().getType() == Material.AIR) {
player.teleport(g);
}
}
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " tried to fly on y-axis in "
+ i + " ms (min =" + AntiCheat.getManager().getBackend().getMagic().Y_TIME() + ")");
} else {
if ((y1 - lastYcoord.get(uuid)) > AntiCheat.getManager().getBackend().getMagic().Y_MAXDIFF() + 1
|| (System.currentTimeMillis() - lastYtime.get(uuid)) > AntiCheat.getManager().getBackend()
.getMagic().Y_TIME()) {
lastYtime.put(uuid, System.currentTimeMillis());
lastYcoord.put(uuid, y1);
}
}
}
}
// Fix Y axis spam
return PASS;
}
public static boolean isMoveUpBlock(Block block) {
return VersionUtil.getMoveUpBlocks().contains(block.getType());
}
}
@@ -0,0 +1,103 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.command;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.manage.CheckManager;
import com.rammelkast.anticheatreloaded.manage.UserManager;
import com.rammelkast.anticheatreloaded.util.Permission;
public class CommandBase {
public static final Configuration CONFIG = AntiCheat.getManager().getConfiguration();
public static final UserManager USER_MANAGER = AntiCheat.getManager().getUserManager();
public static final CheckManager CHECK_MANAGER = AntiCheat.getManager().getCheckManager();
public static final ChatColor RED = ChatColor.RED;
public static final ChatColor YELLOW = ChatColor.YELLOW;
public static final ChatColor GREEN = ChatColor.GREEN;
public static final ChatColor WHITE = ChatColor.WHITE;
public static final ChatColor GRAY = ChatColor.GRAY;
public static final ChatColor GOLD = ChatColor.GOLD;
public static final ChatColor AQUA = ChatColor.AQUA;
public static final Server SERVER = Bukkit.getServer();
public static final String PERMISSIONS_ERROR = RED + "You don't have the permissions to use this command.";
public static final String MENU_END = "-----------------------------------------------------";
private final String name;
private final String command;
private final String usage;
private final String[] help;
private final Permission permission;
public CommandBase(String name, String command, String usage, String help[], Permission permission) {
this.name = name;
this.command = command;
this.usage = usage;
this.help = help;
this.permission = permission;
}
public void run(CommandSender cs, String[] args) {
if (permission.get(cs)) {
execute(cs, args);
} else {
cs.sendMessage(PERMISSIONS_ERROR + " (" + WHITE + permission.toString() + RED + ")");
}
}
protected void execute(CommandSender cs, String[] args) {
return; // Stub
}
public void sendHelp(CommandSender cs) {
cs.sendMessage(RED + "== " + GRAY + getName() + RED + " ==");
cs.sendMessage(RED + "Usage: " + GRAY + (cs instanceof Player ? "/" : "") + getUsage());
cs.sendMessage(RED + "Permission: " + GRAY + getPermission().toString());
for (String string : getHelp()) {
cs.sendMessage(string);
}
}
public String getName() {
return name;
}
public String getCommand() {
return command;
}
public String getUsage() {
return usage;
}
public String[] getHelp() {
return help;
}
public Permission getPermission() {
return permission;
}
}
@@ -0,0 +1,75 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.command;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import com.rammelkast.anticheatreloaded.command.executors.CommandCheck;
import com.rammelkast.anticheatreloaded.command.executors.CommandDebug;
import com.rammelkast.anticheatreloaded.command.executors.CommandDeveloper;
import com.rammelkast.anticheatreloaded.command.executors.CommandHelp;
import com.rammelkast.anticheatreloaded.command.executors.CommandLog;
import com.rammelkast.anticheatreloaded.command.executors.CommandReload;
import com.rammelkast.anticheatreloaded.command.executors.CommandReport;
import com.rammelkast.anticheatreloaded.command.executors.CommandReset;
public class CommandHandler implements CommandExecutor {
private List<CommandBase> commands = new ArrayList<CommandBase>();
public CommandHandler() {
commands.add(new CommandHelp());
commands.add(new CommandCheck());
commands.add(new CommandDebug());
commands.add(new CommandDeveloper());
commands.add(new CommandLog());
commands.add(new CommandReload());
commands.add(new CommandReport());
commands.add(new CommandReset());
}
@Override
public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) {
if (args.length >= 1) {
String command = args[0];
// Shift args down
String[] newArgs = new String[args.length-1];
for (int i=1;i<args.length;i++) {
newArgs[i-1] = args[i];
}
for (CommandBase base : commands) {
if (base.getCommand().equalsIgnoreCase(command)) {
base.run(cs, newArgs);
return true;
}
}
// Command not found, send help
commands.get(0).run(cs, null);
} else {
// Send help
commands.get(0).run(cs, null);
}
return true;
}
}
@@ -0,0 +1,97 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.command.executors;
import org.bukkit.command.CommandSender;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.command.CommandBase;
import com.rammelkast.anticheatreloaded.util.Permission;
import java.util.List;
public class CommandCheck extends CommandBase {
private static final String NAME = "AntiCheat Check Management";
private static final String COMMAND = "check";
private static final String USAGE = "anticheat check [check] [on/off]";
private static final Permission PERMISSION = Permission.SYSTEM_CHECK;
private static final String[] HELP = new String[3];
static {
HELP[0] = GRAY + "Use: " + AQUA + "/anticheat check [check] on" + GRAY + " to enable a check";
HELP[1] = GRAY + "Use: " + AQUA + "/anticheat check [check] off" + GRAY + " to disable a check";
StringBuilder builder = new StringBuilder();
builder.append(GRAY + "Checks: ");
for (int i=0;i<CheckType.values().length;i++) {
builder.append(CheckType.values()[i]);
if (i<CheckType.values().length-1) {
builder.append(", ");
}
}
HELP[2] = builder.toString();
}
public CommandCheck() {
super(NAME, COMMAND, USAGE, HELP, PERMISSION);
}
@Override
protected void execute(CommandSender cs, String[] args) {
if (args.length == 2) {
for (CheckType type : CheckType.values()) {
if (type.toString().equalsIgnoreCase(args[0]) || type.toString().replaceAll("_", "").equalsIgnoreCase(args[0])) {
boolean value = CHECK_MANAGER.isActive(type);
boolean newValue;
if (args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("enable")) {
newValue = true;
} else if (args[1].equalsIgnoreCase("off") || args[1].equalsIgnoreCase("disable")) {
newValue = false;
} else {
sendHelp(cs);
return;
}
String strValue = (newValue ? " activated" : " deactivated");
if (value == newValue) {
cs.sendMessage(GREEN + type.toString() + " is already" + strValue + "!");
} else {
if (newValue) {
CHECK_MANAGER.activateCheck(type, cs.getName());
List<String> checks = CONFIG.getConfig().disabledChecks.getValue();
if (checks.contains(type.toString())) {
checks.remove(type.toString());
CONFIG.getConfig().disabledChecks.setValue(checks);
}
} else {
CHECK_MANAGER.deactivateCheck(type, cs.getName());
List<String> checks = CONFIG.getConfig().disabledChecks.getValue();
checks.add(type.toString());
CONFIG.getConfig().disabledChecks.setValue(checks);
}
cs.sendMessage(GREEN + type.toString() + strValue + ".");
}
return;
}
}
}
sendHelp(cs);
}
}
@@ -0,0 +1,60 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.command.executors;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.command.CommandBase;
import com.rammelkast.anticheatreloaded.util.PastebinReport;
import com.rammelkast.anticheatreloaded.util.Permission;
public class CommandDebug extends CommandBase {
private static final String NAME = "AntiCheat Debug Reporting";
private static final String COMMAND = "debug";
private static final String USAGE = "anticheat debug <user>";
private static final Permission PERMISSION = Permission.SYSTEM_DEBUG;
private static final String[] HELP = {
GRAY + "Use: " + AQUA + "/anticheat debug" + GRAY + " to create a debug report",
GRAY + "Use: " + AQUA + "/anticheat debug <user>" + GRAY + " to create a debug report for a user",
};
public CommandDebug() {
super(NAME, COMMAND, USAGE, HELP, PERMISSION);
}
@Override
protected void execute(CommandSender cs, String[] args) {
Player player = null;
if (args.length == 1) {
player = Bukkit.getPlayer(args[0]);
} else {
if (cs instanceof Player) {
player = (Player) cs;
}
}
cs.sendMessage(GRAY + "Please wait while I collect some data...");
PastebinReport report = new PastebinReport(cs, player);
cs.sendMessage(GREEN + "Debug information posted to: " + WHITE + report.getURL());
cs.sendMessage(GREEN + "Please include this link when making bug reports.");
}
}
@@ -0,0 +1,46 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.command.executors;
import org.bukkit.command.CommandSender;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.command.CommandBase;
import com.rammelkast.anticheatreloaded.util.Permission;
public class CommandDeveloper extends CommandBase {
private static final String NAME = "AntiCheat Developer Mode";
private static final String COMMAND = "developer";
private static final String USAGE = "anticheat developer";
private static final Permission PERMISSION = Permission.SYSTEM_DEBUG;
private static final String[] HELP = {
GRAY + "Use: " + AQUA + "/anticheat developer" + GRAY + " to turn on developer mode",
};
public CommandDeveloper() {
super(NAME, COMMAND, USAGE, HELP, PERMISSION);
}
@Override
protected void execute(CommandSender cs, String[] args) {
AntiCheat.setDeveloperMode(!AntiCheat.developerMode());
cs.sendMessage(GREEN + "Developer mode " + (AntiCheat.developerMode() ? "ON" : "OFF"));
}
}
@@ -0,0 +1,51 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.command.executors;
import org.bukkit.command.CommandSender;
import com.rammelkast.anticheatreloaded.command.CommandBase;
import com.rammelkast.anticheatreloaded.util.Permission;
public class CommandHelp extends CommandBase {
private static final String NAME = "AntiCheatReloaded Help";
private static final String COMMAND = "help";
private static final String USAGE = "anticheat help";
private static final Permission PERMISSION = Permission.SYSTEM_HELP;
private static final String[] HELP = {
RED + "/anti " + GRAY + "help",
RED + "/anti " + GRAY + "reload",
RED + "/anti " + GRAY + "update",
RED + "/anti " + GRAY + "debug " + WHITE + "<user>",
RED + "/anti " + GRAY + "check " + WHITE + "[check] [on/off]",
RED + "/anti " + GRAY + "log " + WHITE + "[file/console] [on/off]",
RED + "/anti " + GRAY + "report " + WHITE + "[group/user]",
RED + "/anti " + GRAY + "reset " + WHITE + "[user]",
};
public CommandHelp() {
super(NAME, COMMAND, USAGE, HELP, PERMISSION);
}
@Override
protected void execute(CommandSender cs, String[] args) {
sendHelp(cs);
}
}
@@ -0,0 +1,80 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.command.executors;
import org.bukkit.command.CommandSender;
import com.rammelkast.anticheatreloaded.command.CommandBase;
import com.rammelkast.anticheatreloaded.config.ConfigurationFile;
import com.rammelkast.anticheatreloaded.util.Permission;
public class CommandLog extends CommandBase {
private static final String NAME = "AntiCheat Logging";
private static final String COMMAND = "log";
private static final String USAGE = "anticheat log [file/console] [on/off]";
private static final Permission PERMISSION = Permission.SYSTEM_LOG;
private static final String[] HELP = {
GRAY + "Use: " + AQUA + "/anticheat log console on" + GRAY + " to enable console logging",
GRAY + "Use: " + AQUA + "/anticheat log file off" + GRAY + " to disable file logging",
};
public CommandLog() {
super(NAME, COMMAND, USAGE, HELP, PERMISSION);
}
@Override
protected void execute(CommandSender cs, String[] args) {
if (args.length == 2) {
ConfigurationFile.ConfigValue<Boolean> value;
String name;
if (args[0].equalsIgnoreCase("file")) {
value = CONFIG.getConfig().logToFile;
name = "File logging";
} else if (args[0].equalsIgnoreCase("console")) {
value = CONFIG.getConfig().logToConsole;
name = "Console logging";
} else {
sendHelp(cs);
return;
}
boolean newValue;
if (args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("enable")) {
newValue = true;
} else if (args[1].equalsIgnoreCase("off") || args[1].equalsIgnoreCase("disable")) {
newValue = false;
} else {
sendHelp(cs);
return;
}
String strValue = (newValue ? " enabled" : " disabled");
if (value.getValue() == newValue) {
cs.sendMessage(GREEN + name + " is already " + strValue + "!");
} else {
value.setValue(newValue);
cs.sendMessage(GREEN + name + strValue + ".");
CONFIG.getConfig().reload();
}
} else {
sendHelp(cs);
}
}
}
@@ -0,0 +1,45 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.command.executors;
import org.bukkit.command.CommandSender;
import com.rammelkast.anticheatreloaded.command.CommandBase;
import com.rammelkast.anticheatreloaded.util.Permission;
public class CommandReload extends CommandBase {
private static final String NAME = "AntiCheat Reload";
private static final String COMMAND = "reload";
private static final String USAGE = "anticheat reload";
private static final Permission PERMISSION = Permission.SYSTEM_RELOAD;
private static final String[] HELP = {
GRAY + "Use: " + AQUA + "/anticheat reload" + GRAY + " to reload AntiCheat settings",
};
public CommandReload() {
super(NAME, COMMAND, USAGE, HELP, PERMISSION);
}
@Override
protected void execute(CommandSender cs, String[] args) {
CONFIG.load();
cs.sendMessage(GREEN + "AntiCheat configuration reloaded.");
}
}
@@ -0,0 +1,193 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.command.executors;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.command.CommandBase;
import com.rammelkast.anticheatreloaded.manage.CheckManager;
import com.rammelkast.anticheatreloaded.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class CommandReport extends CommandBase {
private static final String NAME = "AntiCheat Reports";
private static final String COMMAND = "report";
private static final String USAGE = "anticheat report [group/user]";
private static final Permission PERMISSION = Permission.SYSTEM_REPORT;
private static final String[] HELP = {
GRAY + "Use: " + AQUA + "/anticheat report [group]" + GRAY + " to see all users in a given group",
GRAY + "Use: " + AQUA + "/anticheat report [user]" + GRAY + " to see a single user's report",
GRAY + "Use: " + AQUA + "/anticheat report [user/group] [num]" + GRAY + " to see pages of a report",
};
public CommandReport() {
super(NAME, COMMAND, USAGE, HELP, PERMISSION);
}
@Override
protected void execute(CommandSender cs, String[] args) {
if (args.length >= 1) {
int page = 1;
if (args.length == 2) {
if (Utilities.isInt(args[1])) {
page = Integer.parseInt(args[1]);
} else {
cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[1]);
}
}
if ("low".equalsIgnoreCase(args[0])) {
groupReport(cs, null, page);
}
else if ("all".equalsIgnoreCase(args[0])) {
cs.sendMessage(GREEN + "Low: " + WHITE + USER_MANAGER.getUsersInGroup(null).size() + " players");
for (Group g : CONFIG.getGroups().getGroups()) {
int numPlayers = USER_MANAGER.getUsersInGroup(g).size();
cs.sendMessage(g.getColor() + g.getName() + WHITE + ": " + numPlayers + " players");
}
cs.sendMessage(GRAY + "Use " + AQUA + "/anticheat report [group]" + GRAY + " for a list of players in each group.");
} else {
// Test groups
for (Group group : CONFIG.getGroups().getGroups()) {
if (group.getName().equalsIgnoreCase(args[0]) || "low".equalsIgnoreCase(args[0]) || "all".equalsIgnoreCase(args[0])) {
groupReport(cs, group, page);
return;
}
}
// Test users
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getUniqueId().equals(Bukkit.getPlayer(args[0]).getUniqueId())) {
User user = AntiCheat.getManager().getUserManager().getUser(player.getUniqueId());
playerReport(cs, user, page);
return;
}
}
// Neither of these
cs.sendMessage(RED + "Not a valid group or user: " + WHITE + args[0]);
}
} else {
sendHelp(cs);
}
}
private void groupReport(CommandSender cs, Group group, int page) {
List<User> users = USER_MANAGER.getUsersInGroup(group);
ChatColor color = group == null ? GREEN : group.getColor();
String groupName = group == null ? "Low" : group.getName();
int pages = (int) Math.ceil(((float) users.size()) / 7);
if (page <= pages && page > 0) {
cs.sendMessage("--------------------[" + GREEN + "REPORT[" + page + "/" + pages + "]" + WHITE + "]---------------------");
cs.sendMessage(GRAY + "Group: " + color + groupName);
for (int x = 0; x < 7; x++) {
int index = ((page - 1) * 6) + (x + ((page - 1) * 1));
if (index < users.size()) {
String player = users.get(index).getName();
cs.sendMessage(GRAY + player);
}
}
cs.sendMessage(MENU_END);
} else {
if (pages == 0) {
cs.sendMessage("--------------------[" + GREEN + "REPORT[1/1]" + WHITE + "]---------------------");
cs.sendMessage(GRAY + "Group: " + color + groupName);
cs.sendMessage(GRAY + "There are no users in this group.");
cs.sendMessage(MENU_END);
} else {
cs.sendMessage(RED + "Page not found. Requested " + WHITE + page + RED + ", Max " + WHITE + pages);
}
}
}
private void playerReport(CommandSender cs, User user, int page) {
List<CheckType> types = new ArrayList<CheckType>();
for (CheckType type : CheckType.values()) {
if (type.getUses(user.getUUID()) > 0) {
types.add(type);
}
}
UUID uuid = user.getUUID();
String name = user.getName();
int pages = (int) Math.ceil(((float) types.size()) / 6);
Group group = user.getGroup();
String groupString = GREEN + "Low";
if (group != null) {
groupString = group.getColor() + group.getName();
}
groupString += " (" + user.getLevel() + ")";
if (page <= pages && page > 0) {
cs.sendMessage("--------------------[" + GREEN + "REPORT[" + page + "/" + pages + "]" + WHITE + "]---------------------");
cs.sendMessage(GRAY + "Player: " + WHITE + name);
cs.sendMessage(GRAY + "Group: " + groupString);
for (int x = 0; x < 6; x++) {
int index = ((page - 1) * 5) + (x + ((page - 1)));
if (index < types.size()) {
CheckType type = types.get(index);
int use = type.getUses(uuid);
ChatColor color = WHITE;
if (use >= 20) {
color = YELLOW;
} else if (use > 50) {
color = RED;
}
cs.sendMessage(GRAY + CheckType.getName(type) + ": " + color + use);
}
}
cs.sendMessage(MENU_END);
} else {
if (pages == 0 && page == 1) {
cs.sendMessage("--------------------[" + GREEN + "REPORT[1/1]" + WHITE + "]---------------------");
cs.sendMessage(GRAY + "Player: " + WHITE + name);
cs.sendMessage(GRAY + "Group: " + groupString);
cs.sendMessage(GRAY + "This user has not failed any checks.");
cs.sendMessage(MENU_END);
} else {
cs.sendMessage(RED + "Page not found. Requested " + WHITE + page + RED + ", Max " + WHITE + pages + 1);
}
}
if (AntiCheat.developerMode()) {
int permission = 0;
int check = 0;
for (Permission perm : Permission.values()) {
if (perm.get(user.getPlayer())) permission++;
}
CheckManager manager = AntiCheat.getManager().getCheckManager();
for (CheckType type : CheckType.values()) {
if (manager.willCheck(user.getPlayer(), type)) check++;
}
cs.sendMessage(ChatColor.GOLD + "User has " + permission + "/" + Permission.values().length + " permissions");
cs.sendMessage(ChatColor.GOLD + "User will be checked for " + check + "/" + CheckType.values().length + " checks");
}
}
}
@@ -0,0 +1,65 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.command.executors;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.command.CommandBase;
import com.rammelkast.anticheatreloaded.util.Permission;
import com.rammelkast.anticheatreloaded.util.User;
public class CommandReset extends CommandBase {
private static final String NAME = "AntiCheat Resetting";
private static final String COMMAND = "reset";
private static final String USAGE = "anticheat reset [user]";
private static final Permission PERMISSION = Permission.SYSTEM_RESET;
private static final String[] HELP = {
GRAY + "Use: " + AQUA + "/anticheat reset [user]" + GRAY + " to reset this user's hack level",
};
public CommandReset() {
super(NAME, COMMAND, USAGE, HELP, PERMISSION);
}
@Override
protected void execute(CommandSender cs, String[] args) {
User user;
if (args.length == 1) {
if (Bukkit.getPlayer(args[0]) != null) {
user = USER_MANAGER.getUser(Bukkit.getPlayer(args[0]).getUniqueId());
} else {
user = USER_MANAGER.getUser(Bukkit.getOfflinePlayer(args[0]).getUniqueId());
}
if (user != null) {
user.resetLevel();
user.clearMessages();
AntiCheat.getManager().getBackend().resetChatLevel(user);
cs.sendMessage(args[0] + GREEN + " has been reset.");
} else {
cs.sendMessage(RED + "Player: " +args[0] + " not found.");
}
} else {
sendHelp(cs);
}
}
}
@@ -0,0 +1,194 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config;
import org.bukkit.configuration.file.YamlConfiguration;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.files.Config;
import com.rammelkast.anticheatreloaded.config.files.Enterprise;
import com.rammelkast.anticheatreloaded.config.holders.mysql.*;
import com.rammelkast.anticheatreloaded.config.holders.yaml.*;
import com.rammelkast.anticheatreloaded.config.providers.*;
import com.rammelkast.anticheatreloaded.manage.AntiCheatManager;
import java.io.File;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
public class Configuration {
private AntiCheatManager manager;
private Config config;
private Enterprise enterprise;
private Lang lang;
private Magic magic;
private Groups groups;
private Levels levels;
private Rules rules;
private ArrayList<ConfigurationFile> flatfiles;
private ArrayList<ConfigurationTable> dbfiles;
public Configuration(AntiCheat plugin, AntiCheatManager manager) {
removeOldFiles();
this.manager = manager;
config = new Config(plugin, this);
plugin.setVerbose(config.verboseStartup.getValue());
// Now load others
enterprise = new Enterprise(plugin, this);
flatfiles = new ArrayList<ConfigurationFile>() {{
add(config);
add(enterprise);
}};
dbfiles = new ArrayList<ConfigurationTable>();
// The following values can be configuration from a database, or from flatfile.
if (config.enterprise.getValue() && enterprise.configGroups.getValue()) {
groups = new MySQLGroupsHolder(this);
dbfiles.add((MySQLGroupsHolder) groups);
} else {
groups = new YamlGroupsHolder(plugin, this);
flatfiles.add((YamlGroupsHolder) groups);
}
if (config.enterprise.getValue() && enterprise.configRules.getValue()) {
rules = new MySQLRulesHolder(this);
dbfiles.add((MySQLRulesHolder) rules);
} else {
rules = new YamlRulesHolder(plugin, this);
flatfiles.add((YamlRulesHolder) rules);
}
InvocationHandler handler;
if (config.enterprise.getValue() && enterprise.configMagic.getValue()) {
handler = new MySQLMagicHolder(this);
magic = (Magic) Proxy.newProxyInstance(Magic.class.getClassLoader(),
new Class[] { Magic.class },
handler);
dbfiles.add((MySQLMagicHolder) handler);
} else {
handler = new YamlMagicHolder(plugin, this);
magic = (Magic) Proxy.newProxyInstance(Magic.class.getClassLoader(),
new Class[] { Magic.class },
handler);
flatfiles.add((YamlMagicHolder) handler);
}
if (config.enterprise.getValue() && enterprise.configLang.getValue()) {
handler = new MySQLLangHolder(this);
lang = (Lang) Proxy.newProxyInstance(Lang.class.getClassLoader(),
new Class[] { Lang.class },
handler);
dbfiles.add((MySQLLangHolder) handler);
} else {
handler = new YamlLangHolder(plugin, this);
lang = (Lang) Proxy.newProxyInstance(Lang.class.getClassLoader(),
new Class[] { Lang.class },
handler);
flatfiles.add((YamlLangHolder) handler);
}
if (config.enterprise.getValue() && enterprise.syncLevels.getValue()) {
levels = new MySQLLevelsHolder(this);
dbfiles.add((MySQLLevelsHolder) levels);
} else {
levels = new YamlLevelsHolder(plugin, this);
flatfiles.add((YamlLevelsHolder) levels);
}
// End
for (ConfigurationFile file : flatfiles) {
file.save();
checkReload(file);
}
}
public void load() {
for (ConfigurationFile file : flatfiles) {
file.load();
checkReload(file);
}
for (ConfigurationTable table : dbfiles) {
table.load();
}
if (manager.getBackend() != null) {
manager.getBackend().updateConfig(this);
}
}
private void checkReload(ConfigurationFile file) {
if (file.needsReload()) {
file.reload();
file.setNeedsReload(false);
}
}
private void removeOldFiles() {
ArrayList<String> removed = new ArrayList<String>();
File configFile = new File(AntiCheat.getPlugin().getDataFolder(), "config.yml");
if (configFile.exists() && YamlConfiguration.loadConfiguration(configFile).getString("System.Auto update") != null) {
configFile.renameTo(new File(AntiCheat.getPlugin().getDataFolder(), "config.old"));
removed.add("config.yml has been renamed to config.old and replaced with the new config.yml");
}
File eventsFile = new File(AntiCheat.getPlugin().getDataFolder(), "events.yml");
if (eventsFile.exists()) {
eventsFile.renameTo(new File(AntiCheat.getPlugin().getDataFolder(), "events.old"));
removed.add("events.yml has been renamed to events.old and replaced with groups.yml and rules.yml");
}
if (removed.size() > 0) {
AntiCheat.getPlugin().getLogger().info("You are upgrading from an old version of AntiCheat. Due to configuration changes, the following files have been modified:");
for (String s : removed) {
AntiCheat.getPlugin().getLogger().info(s);
}
}
}
public Config getConfig() {
return config;
}
public Groups getGroups() {
return groups;
}
public Rules getRules() {
return rules;
}
public Lang getLang() {
return lang;
}
public Enterprise getEnterprise() {
return enterprise;
}
public Levels getLevels() {
return levels;
}
public Magic getMagic() {
return magic;
}
}
@@ -0,0 +1,187 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.yaml.CommentedConfiguration;
import java.io.File;
import java.io.IOException;
public class ConfigurationFile {
private File rawFile;
private String fileName;
private CommentedConfiguration configFile;
private FileConfiguration defaultConfigFile;
private Configuration config;
private AntiCheat plugin;
private boolean saveDefault;
protected boolean needsReload;
public ConfigurationFile(AntiCheat plugin, Configuration config, String fileName) {
this(plugin, config, fileName, true);
}
public ConfigurationFile(AntiCheat plugin, Configuration config, String fileName, boolean saveDefault) {
this(plugin, config, fileName, saveDefault, new File(plugin.getDataFolder(), fileName));
}
public ConfigurationFile(AntiCheat plugin, Configuration config, String fileName, boolean saveDefault, File rawFile) {
// Can't change with user editing
this.plugin = plugin;
this.config = config;
this.fileName = fileName;
this.rawFile = rawFile;
this.saveDefault = saveDefault;
if (saveDefault) {
defaultConfigFile = YamlConfiguration.loadConfiguration(plugin.getResource(fileName));
}
load();
}
public void load() {
// Can change with user editing
if (!rawFile.exists()) {
if (saveDefault) {
plugin.saveResource(fileName, true);
} else {
if (!rawFile.getParentFile().exists()) {
rawFile.getParentFile().mkdir();
}
try {
rawFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
configFile = CommentedConfiguration.loadConfiguration(rawFile);
open();
}
public void open() {
// Nothing to do
}
public void close() {
// Nothing to do
}
public void save() {
close();
try {
configFile.save(rawFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public void reload() {
save();
load();
}
public File getRawFile() {
return rawFile;
}
public CommentedConfiguration getConfigFile() {
return configFile;
}
public FileConfiguration getDefaultConfigFile() {
return defaultConfigFile;
}
public Configuration getConfiguration() {
return config;
}
public void setNeedsReload(boolean reload) {
this.needsReload = reload;
}
public boolean needsReload() {
return needsReload;
}
public class ConfigValue<T> {
private String path;
private Object value = null;
private boolean didLoadDefault;
public ConfigValue(String path) {
this(path, true);
}
public ConfigValue(String path, boolean loadDefault) {
this.path = path;
if (getConfigFile().contains(path)) {
value = getConfigFile().get(path);
} else if (loadDefault) {
getConfigFile().set(path, getDefaultConfigFile().get(path));
value = getDefaultConfigFile().get(path);
getConfigFile().set(path, value);
save();
didLoadDefault = true;
}
}
public String getPath() {
return path;
}
public T getValue() {
return (T) value;
}
public T setValue(T value) {
getConfigFile().set(path, value);
save();
return value;
}
public T getDefaultValue() {
return (T) getDefaultConfigFile().get(path);
}
public boolean hasValue() {
return value != null;
}
public boolean didLoadDefault() {
return didLoadDefault;
}
}
}
@@ -0,0 +1,132 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config;
import org.bukkit.Bukkit;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.util.enterprise.Database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
public class ConfigurationTable {
private final String table;
private final Configuration config;
private Database database;
private String prefix;
private String serverName;
public ConfigurationTable(Configuration config, String table) {
this.config = config;
this.table = table;
load();
}
public void load() {
this.database = config.getEnterprise().database;
this.prefix = database.getPrefix();
this.serverName = config.getEnterprise().serverName.getValue();
open();
}
public void open() {
// Nothing to do
}
public void reload() {
// For after sql inserts have been made
Bukkit.getScheduler().runTask(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
load();
}
});
}
public Database getDatabase() {
return database;
}
public String getFullTable() {
return prefix + table;
}
public boolean tableExists() {
try {
return getConnection().getMetaData().getTables(null, null, getFullTable(), null).next();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean isUUIDFormatted(String colName) {
String sqlSelect = "SELECT " + colName + " FROM " + getFullTable() + " LIMIT 1";
String user;
try {
ResultSet res = getConnection().prepareStatement(sqlSelect).executeQuery();
if (res.next() && (user = res.getString(colName)) != null) {
try {
return UUID.fromString(user) != null;
} catch (IllegalArgumentException e) {}
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public void convertToUUID(String colName) {
String sqlSelect = "SELECT " + colName + " FROM " + getFullTable();
String sqlUpdate = "UPDATE " + getFullTable() + " SET " + colName + " = ? WHERE " + colName + " = ?";
try {
ResultSet res = getConnection().prepareStatement(sqlSelect).executeQuery();
while (res.next()) {
PreparedStatement stmt = getConnection().prepareStatement(sqlUpdate);
stmt.setString(1, (Bukkit.getOfflinePlayer(res.getString(1)).getUniqueId().toString()));
stmt.setString(2, res.getString(1));
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public String getServerName() {
return serverName;
}
public Connection getConnection() {
return database.getConnection();
}
}
@@ -0,0 +1,84 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.files;
import java.util.List;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationFile;
public class Config extends ConfigurationFile {
public static final String FILENAME = "config.yml";
public ConfigValue<Boolean> logToConsole;
public ConfigValue<Boolean> autoUpdate;
public ConfigValue<Boolean> verboseStartup;
public ConfigValue<Boolean> silentMode;
public ConfigValue<Boolean> exemptOp;
public ConfigValue<Boolean> eventChains;
public ConfigValue<Boolean> enterprise;
public ConfigValue<Boolean> blockChatSpamSpeed;
public ConfigValue<Boolean> blockCommandSpamSpeed;
public ConfigValue<Boolean> blockChatSpamRepetition;
public ConfigValue<Boolean> blockCommandSpamRepetition;
public ConfigValue<String> chatSpamActionOne;
public ConfigValue<String> chatSpamActionTwo;
public ConfigValue<String> commandSpamActionOne;
public ConfigValue<String> commandSpamActionTwo;
public ConfigValue<Boolean> logToFile;
public ConfigValue<List<String>> disabledWorlds;
public ConfigValue<List<String>> disabledChecks;
public Config(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
@Override
public void open() {
logToConsole = new ConfigValue<Boolean>("system.log-to-console");
autoUpdate = new ConfigValue<Boolean>("system.auto-update");
verboseStartup = new ConfigValue<Boolean>("system.verbose-startup");
silentMode = new ConfigValue<Boolean>("system.silent-mode");
exemptOp = new ConfigValue<Boolean>("system.exempt-op");
eventChains = new ConfigValue<Boolean>("system.event-chains");
enterprise = new ConfigValue<Boolean>("system.enterprise");
blockChatSpamSpeed = new ConfigValue<Boolean>("spam.chat.block-speed");
blockChatSpamRepetition = new ConfigValue<Boolean>("spam.chat.block-repetition");
chatSpamActionOne = new ConfigValue<String>("spam.chat.action-one");
chatSpamActionTwo = new ConfigValue<String>("spam.chat.action-two");
blockCommandSpamSpeed = new ConfigValue<Boolean>("spam.command.block-speed");
blockCommandSpamRepetition = new ConfigValue<Boolean>("spam.command.block-repetition");
commandSpamActionOne = new ConfigValue<String>("spam.command.action-one");
commandSpamActionTwo = new ConfigValue<String>("spam.command.action-two");
logToFile = new ConfigValue<Boolean>("system.log-to-file");
disabledWorlds = new ConfigValue<List<String>>("disable-in");
disabledChecks = new ConfigValue<List<String>>("disabled-checks");
}
}
@@ -0,0 +1,94 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.files;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationFile;
import com.rammelkast.anticheatreloaded.util.enterprise.Database;
public class Enterprise extends ConfigurationFile {
public static final String FILENAME = "enterprise.yml";
public ConfigValue<String> serverName;
public ConfigValue<Boolean> loggingEnabled;
public ConfigValue<String> loggingLife;
public ConfigValue<String> loggingInterval;
public ConfigValue<Boolean> syncLevels;
public ConfigValue<String> syncInterval;
public ConfigValue<Boolean> configGroups;
public ConfigValue<Boolean> configRules;
public ConfigValue<Boolean> configMagic;
public ConfigValue<Boolean> configLang;
public Database database;
public Enterprise(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
@Override
public void open() {
serverName = new ConfigValue<String>("server.name");
loggingEnabled = new ConfigValue<Boolean>("log.enable");
loggingLife = new ConfigValue<String>("log.life");
loggingInterval = new ConfigValue<String>("log.interval");
syncLevels = new ConfigValue<Boolean>("sync.levels");
syncInterval = new ConfigValue<String>("sync.interval");
configGroups = new ConfigValue<Boolean>("config.groups");
configRules = new ConfigValue<Boolean>("config.rules");
configMagic = new ConfigValue<Boolean>("config.magic");
configLang = new ConfigValue<Boolean>("config.lang");
ConfigValue<String> databaseType = new ConfigValue<String>("database.type");
ConfigValue<String> databaseHostname = new ConfigValue<String>("database.hostname");
ConfigValue<String> databaseUsername = new ConfigValue<String>("database.username");
ConfigValue<String> databasePassword = new ConfigValue<String>("database.password");
ConfigValue<String> databasePrefix = new ConfigValue<String>("database.prefix");
ConfigValue<String> databaseSchema = new ConfigValue<String>("database.database");
ConfigValue<Integer> databasePort = new ConfigValue<Integer>("database.port");
if (getConfiguration().getConfig().enterprise.getValue()) {
// Convert database values to Database
database = new Database(
Database.DatabaseType.valueOf(databaseType.getValue()),
databaseHostname.getValue(),
databasePort.getValue(),
databaseUsername.getValue(),
databasePassword.getValue(),
databasePrefix.getValue(),
databaseSchema.getValue(),
serverName.getValue(),
loggingInterval.getValue(),
loggingLife.getValue(),
syncLevels.getValue(),
syncInterval.getValue()
);
database.connect();
}
}
}
@@ -0,0 +1,97 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.holders.mysql;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationTable;
import com.rammelkast.anticheatreloaded.config.providers.Groups;
import com.rammelkast.anticheatreloaded.util.Group;
public class MySQLGroupsHolder extends ConfigurationTable implements Groups {
private static final String TABLE = "groups";
private List<Group> groups;
private int highestLevel;
public MySQLGroupsHolder(Configuration config) {
super(config, TABLE);
}
@Override
public void open() {
highestLevel = 0;
groups = new ArrayList<Group>();
String sqlCreate = "CREATE TABLE " + getFullTable() + "(" +
" `id` INT NOT NULL AUTO_INCREMENT," +
" `name` VARCHAR(45) NOT NULL," +
" `level` INT NOT NULL," +
" `color` VARCHAR(45) NOT NULL," +
" `actions` VARCHAR(45) NOT NULL," +
" PRIMARY KEY (`id`));";
String sqlPopulate = "INSERT INTO " + getFullTable() +
" SELECT t.*" +
" FROM (" +
" (SELECT 1 as id, 'Medium' as name, 20 as level, 'YELLOW' as color, 'WARN' as actions)" +
" UNION ALL " +
" (SELECT 2 as id, 'High' as name, 50 as level, 'RED' as color, 'KICK' as actions)" +
" ) t;";
String sqlLoad = "SELECT * FROM " + getFullTable();
try {
if (!tableExists()) {
getConnection().prepareStatement(sqlCreate).executeUpdate();
getConnection().prepareStatement(sqlPopulate).executeUpdate();
getConnection().commit();
}
ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery();
while (set.next()) {
String name = set.getString("name");
int level = set.getInt("level");
String color = set.getString("color");
List<String> actions = Arrays.asList(set.getString("actions").split(","));
groups.add(new Group(name, level, color, actions));
if (level > highestLevel) {
highestLevel = level;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public List<Group> getGroups() {
return groups;
}
@Override
public int getHighestLevel() {
return highestLevel;
}
}
@@ -0,0 +1,157 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.holders.mysql;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationTable;
import com.rammelkast.anticheatreloaded.config.providers.Lang;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MySQLLangHolder extends ConfigurationTable implements InvocationHandler {
private static final String TABLE = "lang";
private HashMap<String, String> stringValues;
private HashMap<String, List<String>> listValues;
private FileConfiguration defaults;
public MySQLLangHolder(Configuration config) {
super(config, TABLE);
}
@Override
public void open() {
defaults = YamlConfiguration.loadConfiguration(AntiCheat.getPlugin().getResource("lang.yml"));
stringValues = new HashMap<String, String>();
listValues = new HashMap<String, List<String>>();
String sqlCreate = "CREATE TABLE " + getFullTable() + "(" +
" `id` INT NOT NULL AUTO_INCREMENT," +
" `key` VARCHAR(45) NOT NULL," +
" `value` TEXT," +
" PRIMARY KEY (`id`));";
String sqlPopulate = "INSERT INTO " + getFullTable() +
" (`key`, `value`) " +
"SELECT t.*" +
"FROM (";
Method[] methods = Lang.class.getMethods();
for (int i=1;i<=methods.length;i++) {
sqlPopulate += "(SELECT ? as `key`, ? as `value`)";
if (i < methods.length) sqlPopulate += " UNION ALL ";
}
sqlPopulate += ") t;";
String sqlLoad = "SELECT * FROM " + getFullTable();
try {
PreparedStatement insert = getConnection().prepareStatement(sqlPopulate);
int strings = 1;
for (int i=1;i<=methods.length;i++) {
String key = methods[i-1].getName();
String value = defaults.getString(key);
insert.setString(strings, key);
strings++;
insert.setString(strings, value);
strings++;
}
if (!tableExists()) {
getConnection().prepareStatement(sqlCreate).executeUpdate();
insert.executeUpdate();
getConnection().commit();
}
ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery();
while (set.next()) {
String key = set.getString("key");
String value = set.getString("value");
if (value.matches("^\\[.*\\]$")) {
listValues.put(key, getList(value));
} else {
stringValues.put(key, value);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public Object invoke(Object proxy, Method method, Object[] args) {
String key = method.getName();
if (method.getReturnType() == List.class) {
if (listValues.containsKey(key)) {
return listValues.get(key);
} else if (defaults.getString(key) != null) {
String value = defaults.getString(key);
try {
PreparedStatement s = getConnection().prepareStatement("INSERT INTO " + getFullTable() + " (key, value) VALUES (?, ?)");
s.setString(1, key);
s.setString(2, value);
} catch (SQLException e) {
e.printStackTrace();
}
reload();
return getList(value);
}
} else {
if (stringValues.containsKey(key)) {
return stringValues.get(key);
} else if (defaults.getString(key) != null) {
String value = defaults.getString(key);
try {
PreparedStatement s = getConnection().prepareStatement("INSERT INTO " + getFullTable() + " (key, value) VALUES (?, ?)");
s.setString(1, key);
s.setString(2, value);
} catch (SQLException e) {
e.printStackTrace();
}
reload();
return value;
}
}
AntiCheat.getPlugin().getLogger().severe("The lang value " + key + " couldn't be found.");
return "Language error. See console for details.";
}
private List<String> getList(String value) {
value = value.substring(1, value.length() - 1);
ArrayList<String> list = new ArrayList<String>();
for (String s : value.split(", ")) {
list.add(s);
}
return list;
}
}
@@ -0,0 +1,187 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.holders.mysql;
import org.bukkit.Bukkit;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationTable;
import com.rammelkast.anticheatreloaded.config.providers.Levels;
import com.rammelkast.anticheatreloaded.util.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class MySQLLevelsHolder extends ConfigurationTable implements Levels {
private static final String TABLE = "levels";
private static final String MANUAL_EDIT_TAG = "MANUAL";
private String sqlSave;
private String sqlLoad;
private String sqlUpdate;
public MySQLLevelsHolder(Configuration config) {
super(config, TABLE);
}
@Override
public void open() {
sqlSave = "INSERT INTO " + getFullTable() +
" (user, level, last_update_server) " +
"VALUES (?, ?, ?) " +
"ON DUPLICATE KEY UPDATE " +
"level = IF(last_update = ?, ?, level+?), " +
"last_update=CURRENT_TIMESTAMP, " +
"last_update_server=?";
sqlLoad = "SELECT level, last_update FROM " + getFullTable() + " " +
"WHERE user = ?";
sqlUpdate = "SELECT level, last_update FROM " + getFullTable() + " " +
"WHERE user = ? AND last_update <> ? AND last_update_server = ?";
String sqlCreate = "CREATE TABLE " + getFullTable() + "(" +
" `user` VARCHAR(45) NOT NULL," +
" `level` INT NOT NULL," +
" `last_update` TIMESTAMP NOT NULL DEFAULT NOW()," +
" `last_update_server` VARCHAR(45) NOT NULL," +
" PRIMARY KEY (`user`));";
try {
if (!tableExists()) {
getConnection().prepareStatement(sqlCreate).executeUpdate();
getConnection().commit();
} else if (!isUUIDFormatted("user")) {
convertToUUID("user");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void saveLevelFromUser(final User user) {
Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
if (!user.isWaitingOnLevelSync()) {
AntiCheat.debugLog("Saving level from " + user.getUUID() + ". Value: " + user.getLevel());
try {
PreparedStatement statement = getConnection().prepareStatement(sqlSave);
statement.setString(1, user.getUUID().toString());
statement.setInt(2, user.getLevel());
statement.setString(3, getServerName());
statement.setTimestamp(4, user.getLevelSyncTimestamp());
statement.setInt(5, user.getLevel());
statement.setInt(6, user.getLevel());
statement.setString(7, getServerName());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
AntiCheat.getManager().getUserManager().remove(user);
}
});
}
@Override
public void loadLevelToUser(final User user) {
Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
try {
PreparedStatement statement = getConnection().prepareStatement(sqlLoad);
statement.setString(1, user.getUUID().toString());
ResultSet set = statement.executeQuery();
boolean has = false;
while (set.next()) {
has = true;
AntiCheat.debugLog("Syncing level to " + user.getUUID() + ". Value: " + set.getInt("level"));
user.setLevel(set.getInt("level"));
user.setLevelSyncTimestamp(set.getTimestamp("last_update"));
}
if (!has) user.setLevel(0);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
@Override
public void saveLevelsFromUsers(List<User> users) {
try {
PreparedStatement statement = getConnection().prepareStatement(sqlSave);
for (User user : users) {
if (!user.isWaitingOnLevelSync()) {
try {
statement.setString(1, user.getUUID().toString());
statement.setInt(2, user.getLevel());
statement.setString(3, getServerName());
statement.setTimestamp(4, user.getLevelSyncTimestamp());
statement.setInt(5, user.getLevel());
statement.setInt(6, user.getLevel());
statement.setString(7, getServerName());
statement.addBatch();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
statement.executeBatch();
getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void updateLevelToUser(final User user) {
Bukkit.getScheduler().runTaskAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
try {
PreparedStatement statement = getConnection().prepareStatement(sqlUpdate);
statement.setString(1, user.getUUID().toString());
statement.setTimestamp(2, user.getLevelSyncTimestamp());
statement.setString(3, MANUAL_EDIT_TAG);
ResultSet set = statement.executeQuery();
while (set.next()) {
AntiCheat.debugLog("Syncing level to " + user.getUUID() + ". Value: " + set.getInt("level"));
user.setLevel(set.getInt("level"));
user.setLevelSyncTimestamp(set.getTimestamp("last_update"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
}
@@ -0,0 +1,147 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.holders.mysql;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationTable;
import com.rammelkast.anticheatreloaded.config.providers.Magic;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
public class MySQLMagicHolder extends ConfigurationTable implements InvocationHandler {
private static final String TABLE = "magic";
private HashMap<String, Integer> ints;
private HashMap<String, Double> doubles;
private FileConfiguration defaults;
public MySQLMagicHolder(Configuration config) {
super(config, TABLE);
}
@Override
public void open() {
defaults = YamlConfiguration.loadConfiguration(AntiCheat.getPlugin().getResource("magic.yml"));
ints = new HashMap<String, Integer>();
doubles = new HashMap<String, Double>();
String sqlCreate = "CREATE TABLE " + getFullTable() + "(" +
" `id` INT NOT NULL AUTO_INCREMENT," +
" `key` VARCHAR(45) NOT NULL," +
" `value_int` INT," +
" `value_double` DOUBLE," +
" PRIMARY KEY (`id`));";
String sqlPopulate = "INSERT INTO " + getFullTable() +
" (`key`, `value_int`, `value_double`) " +
"SELECT t.*" +
"FROM (";
Method[] methods = Magic.class.getMethods();
for (int i=1;i<=methods.length;i++) {
String key = methods[i-1].getName();
Object value = defaults.get(key);
String type1 = methods[i-1].getReturnType().getSimpleName();
String type2 = type1.equals("int") ? "double" : "int";
sqlPopulate += "(SELECT '" + key + "' as `key`, " + (type1.equals("int") ? value : "null") + " as value_" + type1 + ", " + (type1.equals("double") ? value : "null") + " as value_" + type2 + ")";
if (i < methods.length) sqlPopulate += " UNION ALL ";
}
sqlPopulate += ") t;";
String sqlLoad = "SELECT * FROM " + getFullTable();
try {
if (!tableExists()) {
getConnection().prepareStatement(sqlCreate).executeUpdate();
getConnection().prepareStatement(sqlPopulate).executeUpdate();
getConnection().commit();
}
ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery();
while (set.next()) {
String key = set.getString("key");
if (set.getObject("value_int") != null) {
ints.put(key, set.getInt("value_int"));
} else if (set.getObject("value_double") != null) {
doubles.put(key, set.getDouble("value_double"));
} else {
AntiCheat.getPlugin().getLogger().severe("The magic value " + key + " loaded from the database did not have a value configured. Using the default value.");
for (int i=1;i<=methods.length;i++) {
String name = methods[i-1].getName();
if (name.equalsIgnoreCase(key)) {
String type = methods[i-1].getReturnType().getSimpleName();
if (type.equals("int")) {
ints.put(key, defaults.getInt(key));
} else if (type.equals("double")) {
doubles.put(key, defaults.getDouble(key));
}
}
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public Object invoke(Object proxy, Method method, Object[] args) {
String key = method.getName();
if (ints.containsKey(key)) {
return ints.get(key).intValue();
} else if (doubles.containsKey(key)) {
return doubles.get(key).doubleValue();
} else if (defaults.getString(key) != null ) {
if (method.getReturnType().getSimpleName().equals("int")) {
int value = defaults.getInt(key);
try {
getConnection().prepareStatement("INSERT INTO " + getFullTable() + " (key, value_int) VALUES ('" + key + "' , '" + value + "')").executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
reload();
return value;
} else if (method.getReturnType().getSimpleName().equals("double")) {
double value = defaults.getDouble(key);
try {
getConnection().prepareStatement("INSERT INTO " + getFullTable() + " (key, value_double) VALUES ('" + key + "' , '" + value + "')").executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
reload();
return value;
}
}
AntiCheat.getPlugin().getLogger().severe("The magic value " + key + " couldn't be found.");
return 0;
}
}
@@ -0,0 +1,79 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.holders.mysql;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationTable;
import com.rammelkast.anticheatreloaded.config.providers.Rules;
import com.rammelkast.anticheatreloaded.util.rule.Rule;
public class MySQLRulesHolder extends ConfigurationTable implements Rules {
private static final String TABLE = "rules";
private List<Rule> rules;
public MySQLRulesHolder(Configuration config) {
super(config, TABLE);
}
@Override
public void open() {
String sqlCreate = "CREATE TABLE " + getFullTable() + "(" +
" `id` INT NOT NULL AUTO_INCREMENT," +
" `rule` VARCHAR(256) NOT NULL," +
" PRIMARY KEY (`id`));";
String sqlPopulate = "INSERT INTO " + getFullTable() +
" VALUES (1, 'Check_SPIDER < 0 ? Player.KICK : null')";
String sqlLoad = "SELECT * FROM " + getFullTable();
try {
if (!tableExists()) {
getConnection().prepareStatement(sqlCreate).executeUpdate();
getConnection().prepareStatement(sqlPopulate).executeUpdate();
getConnection().commit();
}
this.rules = new ArrayList<Rule>();
ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery();
while (set.next()) {
String string = set.getString("rule");
Rule rule = Rule.load(string);
if (rule != null) {
this.rules.add(rule);
} else {
AntiCheat.getPlugin().getLogger().warning("Couldn't load rule '" + string + "' from the database. Improper format used.");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Rule> getRules() {
return rules;
}
}
@@ -0,0 +1,79 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.holders.yaml;
import java.util.*;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationFile;
import com.rammelkast.anticheatreloaded.config.providers.Groups;
import com.rammelkast.anticheatreloaded.util.Group;
public class YamlGroupsHolder extends ConfigurationFile implements Groups {
public static final String FILENAME = "groups.yml";
private List<Group> groups;
private int highestLevel;
public YamlGroupsHolder(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
@Override
public List<Group> getGroups() {
return groups;
}
@Override
public int getHighestLevel() {
return highestLevel;
}
@Override
public void open() {
ConfigValue<List<String>> groups = new ConfigValue<List<String>>("groups");
// Convert groups list to Levels
this.groups = new ArrayList<Group>();
for (String string : groups.getValue()) {
Group group = Group.load(string);
if (group == null || group.getLevel() < 0) {
continue;
}
this.groups.add(group);
highestLevel = group.getLevel() > highestLevel ? group.getLevel() : highestLevel;
}
// Sort groups
Collections.sort(this.groups, new Comparator<Group>() {
public int compare(Group l1, Group l2) {
if (l1.getLevel() == l2.getLevel()) {
return 0;
} else if (l1.getLevel() < l2.getLevel()) {
return -1;
}
return 1;
}
});
}
}
@@ -0,0 +1,82 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.holders.yaml;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationFile;
public class YamlLangHolder extends ConfigurationFile implements InvocationHandler {
public static final String FILENAME = "lang.yml";
public YamlLangHolder(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
@Override
public void open() {
if (new ConfigValue<String>("chat.ban_broadcast").getValue() != null) {
update();
}
}
private void update() {
new ConfigValue<List<String>>("ALERT").setValue(new ConfigValue<List<String>>("alert").getValue());
new ConfigValue<List<String>>("WARNING").setValue(new ConfigValue<List<String>>("warning.player_warning").getValue());
new ConfigValue<List<String>>("alert").setValue(null);
new ConfigValue<List<String>>("warning.player_warning").setValue(null);
updateValue("ban.ban_reason", "BAN_REASON");
updateValue("ban.ban_broadcast", "BAN_BROADCAST");
updateValue("kick.kick_reason", "KICK_REASON");
updateValue("kick.kick_broadcast", "KICK_BROADCAST");
updateValue("chat.warning", "SPAM_WARNING");
updateValue("chat.kick_reason", "SPAM_KICK_REASON");
updateValue("chat.kick_broadcast", "SPAM_KICK_BROADCAST");
updateValue("chat.ban_reason", "SPAM_BAN_REASON");
updateValue("chat.ban_broadcast", "SPAM_BAN_BROADCAST");
}
private void updateValue(String oldValue, String newValue) {
new ConfigValue<String>(newValue).setValue(new ConfigValue<String>(oldValue).getValue());
new ConfigValue<String>(oldValue).setValue(null);
}
public Object invoke(Object proxy, Method method, Object[] args) {
String key = method.getName();
if (method.getReturnType() == List.class) {
ConfigValue<List<String>> value = new ConfigValue<List<String>>(key);
if (value.getValue() != null) {
return value.getValue();
}
} else {
ConfigValue<String> value = new ConfigValue<String>(key);
if (value.getValue() != null) {
return value.getValue();
}
}
AntiCheat.getPlugin().getLogger().severe("The lang value " + key + " couldn't be found.");
return "Language error. See console for details.";
}
}
@@ -0,0 +1,78 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.holders.yaml;
import java.util.List;
import java.util.UUID;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationFile;
import com.rammelkast.anticheatreloaded.config.providers.Levels;
import com.rammelkast.anticheatreloaded.util.User;
public class YamlLevelsHolder extends ConfigurationFile implements Levels {
public static final String FILENAME = "data/levels.yml";
public YamlLevelsHolder(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME, false);
}
@Override
public void loadLevelToUser(User user) {
user.setLevel(getLevel(user.getUUID()));
}
@Override
public void saveLevelFromUser(User user) {
saveLevelFromUser(user, true);
}
private void saveLevelFromUser(User user, boolean remove) {
saveLevel(user.getUUID(), user.getLevel());
if (remove) AntiCheat.getManager().getUserManager().remove(user);
}
@Override
public void saveLevelsFromUsers(List<User> users) {
for (User user : users) {
saveLevelFromUser(user, false);
}
}
@Override
public void updateLevelToUser(User user) {
// This method intentionally left blank.
return;
}
private int getLevel(UUID uuid) {
ConfigValue<Integer> level = new ConfigValue<Integer>(uuid.toString(), false);
if (level.hasValue()) {
return level.getValue();
} else {
return 0;
}
}
private void saveLevel(UUID uuid, int level) {
new ConfigValue<Integer>(uuid.toString(), false).setValue(new Integer(level));
}
}
@@ -0,0 +1,48 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.holders.yaml;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationFile;
public class YamlMagicHolder extends ConfigurationFile implements InvocationHandler {
public static final String FILENAME = "magic.yml";
public YamlMagicHolder(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
public Object invoke(Object proxy, Method method, Object[] args) {
String key = method.getName();
if (method.getReturnType().getSimpleName().equals("int")) {
return new ConfigValue<Integer>(key).getValue();
} else if (method.getReturnType().getSimpleName().equals("double")) {
return new ConfigValue<Double>(key).getValue();
} else {
AntiCheat.getPlugin().getLogger().severe("The magic value " + key + " couldn't be found.");
return -1;
}
}
}
@@ -0,0 +1,68 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.holders.yaml;
import java.util.ArrayList;
import java.util.List;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.ConfigurationFile;
import com.rammelkast.anticheatreloaded.config.providers.Rules;
import com.rammelkast.anticheatreloaded.util.rule.Rule;
public class YamlRulesHolder extends ConfigurationFile implements Rules {
public static final String FILENAME = "rules.yml";
private List<Rule> rules;
public YamlRulesHolder(AntiCheat plugin, Configuration config) {
super(plugin, config, FILENAME);
}
@Override
public List<Rule> getRules() {
return rules;
}
@Override
public void open() {
ConfigValue<List<String>> rules = new ConfigValue<List<String>>("rules");
// Convert rules list to Rules
this.rules = new ArrayList<Rule>();
List<String> tempRules = rules.getValue();
for (int i = 0; i < tempRules.size(); i++) {
String string = tempRules.get(i);
if (string.equals("Check_SPIDER < 0 ? Player.KICK : null")) {
// Default rule, won't ever run so we shouldn't load it; only used as example
continue;
}
Rule rule = Rule.load(string);
if (rule != null) {
this.rules.add(rule);
} else {
AntiCheat.getPlugin().getLogger().warning("Couldn't load rule '" + string + "' from config. Improper format used.");
}
}
}
}
@@ -0,0 +1,41 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.providers;
import java.util.List;
import com.rammelkast.anticheatreloaded.util.Group;
public interface Groups {
/**
* Get all groups.
*
* @return List of groups.
*/
public List<Group> getGroups();
/**
* Get the highest level value assigned to a group.
* Used as a maximum cap to rising hack levels.
*
* @return Highest group level.
*/
public int getHighestLevel();
}
@@ -0,0 +1,83 @@
package com.rammelkast.anticheatreloaded.config.providers;
import java.util.List;
public interface Lang {
/**
* Get the alert to send when a player's hack group changes.
*
* @return Alert
*/
public List<String> ALERT();
/**
* Get the warning to send players when they enter a group.
*
* @return Warning.
*/
public List<String> WARNING();
/**
* Get the warning to send players for spamming.
*
* @return Spam warning.
*/
public String SPAM_WARNING();
/**
* Get the reason for kicking a player for spam.
*
* @return Spam kicking reason.
*/
public String SPAM_KICK_REASON();
/**
* Get the reason for banning a player for spam.
*
* @return Spam banning reason.
*/
public String SPAM_BAN_REASON();
/**
* Get the broadcast for kicking a player for spam.
*
* @return Spam kicking broadcast.
*/
public String SPAM_KICK_BROADCAST();
/**
* Get the broadcast for banning a player for spam.
*
* @return Spam banning broadcast.
*/
public String SPAM_BAN_BROADCAST();
/**
* Get the reason for banning a player.
*
* @return Banning reason.
*/
public String BAN_REASON();
/**
* Get the broadcast for banning a player.
*
* @return Banning broadcast.
*/
public String BAN_BROADCAST();
/**
* Get the reason for kicking a player.
*
* @return Kicking reason.
*/
public String KICK_REASON();
/**
* Get the broadcast for kicking a player.
*
* @return Kicking broadcast.
*/
public String KICK_BROADCAST();
}
@@ -0,0 +1,55 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.providers;
import java.util.List;
import com.rammelkast.anticheatreloaded.util.User;
public interface Levels {
/**
* Checks for a stored level for this user, and loads it to their object if found.
*
* @param user User to load.
*/
public void loadLevelToUser(User user);
/**
* Saves the user's level to storage.
*
* @param user User to save.
*/
public void saveLevelFromUser(User user);
/**
* Saves a list of user's levels to storage.
* Used on server shutdown / reload.
*
* @param users List of users to save.
*/
public void saveLevelsFromUsers(List<User> users);
/**
* Check to see if the user's level has been manually changed since it was loaded, and update it if needed
*
* @param user User to update.
*/
public void updateLevelToUser(User user);
}
@@ -0,0 +1,380 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.providers;
/**
* Magic number class. Modifications to values in magic.yml will be accepted here.
* <p/>
* Note that although each value is documented, changing it may have unintended side-effects. For instance, setting something to 0 that the plugin then uses as a dividend will result in an error. <br>
* Also realize that the smaller (more precise) 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 make larger modifications to it.
* <p/>
* <b>How to read the value documentation:</b>
* <p/>
* First, you will see a description of the value. Then, you will see a type: <br>
* <b>Type SYSTEM:</b> This is a millisecond value used to compare past and future events with the current SYSTEM time. Remember, 1000 ms = 1 second. <br>
* <b>Type INTEGER:</b> This is a regular number. It's typically used as something trivial, such as how many times X event can occur. <br>
* <b>Type DOUBLE:</b> This is a number that has a decimal in it. It's typically used to evaluate speed or distance.
* <p/>
* After the type, you may see a recommendation labeled as 'Leniency'. This means 'In order to add leniency to this value, do X'<br>
* The suggestion for adding leniency will either be to INCREASE or DECREASE the variable. Doing what it suggests will cause the SYSTEM to not judge the people being checked so vigorously.<br>
* Some values may not have a leniency recommendation because they are internal numbers used for running checks. Values without these recommendations would be best left alone.
*/
public interface Magic {
/**
* Time to exempt a player from moving because of entering/exiting a vehicle; Type=SYSTEM, Leniency=INCREASE.
*/
public int ENTERED_EXITED_TIME();
/**
* Time to exempt a player from moving because of entering/exiting sneak mode; Type=SYSTEM, Leniency=INCREASE.
*/
public int SNEAK_TIME();
/**
* Time to exempt a player from moving because of teleporting; Type=SYSTEM, Leniency=INCREASE.
*/
public int TELEPORT_TIME();
/**
* Time to exempt a player from moving because of exiting fly mode; Type=SYSTEM, Leniency=INCREASE.
*/
public int EXIT_FLY_TIME();
/**
* Time to exempt a player from moving because of joining the server; Type=SYSTEM, Leniency=INCREASE.
*/
public int JOIN_TIME();
/**
* Time to exempt a player from fastbreak check because of using instant break; Type=INTEGER, Leniency=INCREASE.
*/
public int INSTANT_BREAK_TIME();
/**
* Time to exempt a player from moving because of taking damage; Type=SYSTEM, Leniency=INCREASE.
*/
public int DAMAGE_TIME();
/**
* Time to exempt a player from moving because of taking damage with knockback effects; Type=SYSTEM, Leniency=INCREASE.
*/
public int KNOCKBACK_DAMAGE_TIME();
/**
* Time to exempt a player from moving because of taking damage from an explosion; Type=SYSTEM, Leniency=INCREASE.
*/
public int EXPLOSION_DAMAGE_TIME();
/**
* Minimum time it takes to fire X projectiles; Type=SYSTEM, Leniency=DECREASE.
*/
public int PROJECTILE_TIME_MIN();
/**
* Number of projectiles to wait for before checking how long they took to fire off; Type=INTEGER.
*/
public int PROJECTILE_CHECK();
/**
* Minimum time it takes to drop X items; Type=SYSTEM, Leniency=DECREASE.
*/
public int DROP_TIME_MIN();
/**
* Number of item drops to wait for before checking how long they took to drop; Type=INTEGER.
*/
public int DROP_CHECK();
/**
* Max number of blocks that can be broken in a given time; Type=INTEGER, Leniency=INCREASE.
*/
public int FASTBREAK_LIMIT();
/**
* Time to wait before checking block breaks; Type=SYSTEM, Leniency=INCREASE.
*/
public int FASTBREAK_TIMEMAX();
/**
* Time to wait before checking block breaks in creative mode; Type=SYSTEM, Leniency=INCREASE.
*/
public int FASTBREAK_TIMEMAX_CREATIVE();
/**
* Number of times fastbreak can be observed before taking action; Type=INTEGER, Leniency=INCREASE.
*/
public int FASTBREAK_MAXVIOLATIONS();
/**
* Number of times fastbreak can be observed before taking action in creative mode; Type=INTEGER, Leniency=INCREASE.
*/
public int FASTBREAK_MAXVIOLATIONS_CREATIVE();
/**
* Time a player is forced to wait after fastbreak has been detected; Type=SYSTEM, Leniency=DECREASE.
*/
public int FASTBREAK_MAXVIOLATIONTIME();
/**
* Number of blocks that can be broken without being hit before taking action; Type=INTEGER, Leniency=INCREASE.
*/
public int FASTPLACE_ZEROLIMIT();
/**
* Minimum time in between block places; Type=SYSTEM, Leniency=DECREASE.
*/
public int FASTPLACE_TIMEMIN();
/**
* Number of times fastplace can be observed before taking action; Type=INTEGER, Leniency=INCREASE.
*/
public int FASTPLACE_MAXVIOLATIONS();
/**
* Number of times fastplace can be observed before taking action in creative mode; Type=INTEGER, Leniency=INCREASE.
*/
public int FASTPLACE_MAXVIOLATIONS_CREATIVE();
/**
* Time a player is forced to wait after fastplace has been detected; Type=SYSTEM, Leniency=DECREASE.
*/
public int FASTPLACE_MAXVIOLATIONTIME();
/**
* Number of times required to punch a block before it breaks; Type=INTEGER, Leniency=DECREASE.
*/
public int BLOCK_PUNCH_MIN();
/**
* Number of command spam violations before action one is executed; Type=INTEGER, Leniency=INCREASE.
*/
public int COMMAND_ACTION_ONE_LEVEL();
/**
* Number of command spam violations before action two is executed; Type=INTEGER, Leniency=INCREASE.
*/
public int COMMAND_ACTION_TWO_LEVEL();
/**
* Number of chat spam violations before action one is executed; Type=INTEGER, Leniency=INCREASE.
*/
public int CHAT_ACTION_ONE_LEVEL();
/**
* Number of chat spam violations before action two is executed; Type=INTEGER, Leniency=INCREASE.
*/
public int CHAT_ACTION_TWO_LEVEL();
/**
* Number of times a player can be caught in-flight before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public int FLIGHT_LIMIT();
/**
* Number of times a player can be caught in-glide before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public int GLIDE_LIMIT();
/**
* How many blocks you can travel before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public double FLIGHT_BLOCK_LIMIT();
/**
* Maximum speed that a player can climb a waterfall; Type=DOUBLE, Leniency=INCREASE.
*/
public double WATER_CLIMB_MAX();
/**
* Number of times a player can fly on the y-axis before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public int Y_MAXVIOLATIONS();
/**
* Time a player is forced to wait after flying on the y-axis; Type=SYSTEM, Leniency=DECREASE.
*/
public int Y_MAXVIOTIME();
/**
* Number of times a player can fail a velocity check before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public int VELOCITY_TIME();
/**
* Time used to schedule increasing a players velocity count - probably not touching this would be good; Type=INTEGER.
*/
public int VELOCITY_SCHETIME();
/**
* Maximum time a player is considered to have a change in velocity; Type=SYSTEM, Leniency=INCREASE.
*/
public int VELOCITY_CHECKTIME();
/**
* Time to extend a player's velocity count by; Type=SYSTEM, Leniency=INCREASE.
*/
public int VELOCITY_PREVENT();
/**
* Number of times a player can fail the velocity check before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public int VELOCITY_MAXTIMES();
/**
* Number of times a player can fail the nofall check before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public int NOFALL_LIMIT();
/**
* Number of times a player can fail the ascension check before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public int ASCENSION_COUNT_MAX();
/**
* Number of times a player can fail the ascension check while in water before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public int WATER_ASCENSION_VIOLATION_MAX();
/**
* Number of times a player can be caught speeding in water before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public int WATER_SPEED_VIOLATION_MAX();
/**
* Number of times a player can sprint without proper food level before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public int SPRINT_FOOD_MIN();
/**
* Maximum times a player can interact between animations; Type=INTEGER, Leniency=INCREASE.
*/
public int ANIMATION_INTERACT_MAX();
/**
* Minimum time between animations; Type=SYSTEM, Leniency=INCREASE.
*/
public int ANIMATION_MIN();
/**
* Minimum time between commands; Type=SYSTEM, Leniency=DECREASE.
*/
public int COMMAND_MIN();
/**
* Minimum time before repeating a command is ignored; Type=SYSTEM, Leniency=DECREASE.
*/
public int COMMAND_REPEAT_MIN();
/**
* Minimum time between chats; Type=SYSTEM, Leniency=INCREASE.
*/
public int CHAT_MIN();
/**
* Time before repeating yourself in chat is ignored; Type=SYSTEM, Leniency=INCREASE.
*/
public int CHAT_REPEAT_MIN();
/**
* Maximum speed you can travel while sprinting; Type=DOUBLE, Leniency=INCREASE.
*/
public double SPRINT_MIN();
/**
* Minimum time in between block breaks; Type=INTEGER, Leniency=DECREASE.
*/
public double BLOCK_BREAK_MIN();
/**
* Minimum time in between block placing; Type=INTEGER, Leniency=DECREASE.
*/
public double BLOCK_PLACE_MIN();
/**
* Minimum time in between eating; Type=SYSTEM, Leniency=DECREASE.
*/
public int EAT_TIME_MIN();
/**
* Maximum percent error between predicted bow force and actual bow force; Type=DOUBLE, Leniency=INCREASE.
*/
public double BOW_ERROR();
/**
* Minimum distance a player can break a block from; Type=DOUBLE, Leniency=INCREASE.
*/
public double BLOCK_MAX_DISTANCE();
/**
* Minimum distance a player can break a block from in creative mode; Type=DOUBLE, Leniency=INCREASE.
*/
public double BLOCK_MAX_DISTANCE_CREATIVE();
/**
* Minimum distance a player can damage an entity from; Type=DOUBLE, Leniency=INCREASE.
*/
public double ENTITY_MAX_DISTANCE();
/**
* Minimum distance a player can damage an entity from in creative mode; Type=DOUBLE, Leniency=INCREASE.
*/
public double ENTITY_MAX_DISTANCE_CREATIVE();
/**
* Maximum speed a player on a ladder can travel; Type=DOUBLE, Leniency=INCREASE.
*/
public double LADDER_Y_MAX();
/**
* Minimum speed a player on a ladder can travel; Type=DOUBLE, Leniency=DECREASE.
*/
public double LADDER_Y_MIN();
/**
* Maximum speed a player can travel up; Type=DOUBLE, Leniency=INCREASE.
*/
public double Y_SPEED_MAX();
/**
* Maximum difference between the player's last 2 Y values when traveling up; Type=DOUBLE, Leniency=INCREASE.
*/
public double Y_MAXDIFF();
/**
* Time in between Y difference measures; Type=SYSTEM, Leniency=DECREASE.
*/
public int Y_TIME();
/**
* Maximum speed a player can travel forwards or backwards; Type=DOUBLE, Leniency=INCREASE.
*/
public double XZ_SPEED_MAX();
/**
* Maximum speed a player can travel forwards or backwards while sprinting; Type=DOUBLE, Leniency=INCREASE.
*/
public double XZ_SPEED_MAX_SPRINT();
/**
* Maximum speed a player can travel forwards or backwards while flying; Type=DOUBLE, Leniency=INCREASE.
*/
public double XZ_SPEED_MAX_FLY();
/**
* Maximum speed a player can travel forwards or backwards while under the influence; Type=DOUBLE, Leniency=INCREASE.
*/
public double XZ_SPEED_MAX_POTION();
/**
* Maximum speed a player can travel forwards or backwards while sprinting while under the influence; Type=DOUBLE, Leniency=INCREASE.
*/
public double XZ_SPEED_MAX_POTION_SPRINT();
/**
* Maximum speed a player can travel forwards or backwards while sneaking; Type=DOUBLE, Leniency=INCREASE.
*/
public double XZ_SPEED_MAX_SNEAK();
/**
* Maximum speed a player can travel forwards or backwards in water; Type=DOUBLE, Leniency=INCREASE.
*/
public double XZ_SPEED_MAX_WATER();
/**
* Maximum speed a player can travel forwards or backwards in water while sprinting; Type=DOUBLE, Leniency=INCREASE.
*/
public double XZ_SPEED_MAX_WATER_SPRINT();
/**
* Maximum speed a player can travel forwards or backwards on soul sand; Type=DOUBLE, Leniency=INCREASE.
*/
public double XZ_SPEED_MAX_SOULSAND();
/**
* Maximum speed a player can travel forwards or backwards on soul sand while sprinting; Type=DOUBLE, Leniency=INCREASE.
*/
public double XZ_SPEED_MAX_SOULSAND_SPRINT();
/**
* Maximum speed a player can travel forwards or backwards on soul sand while under the influence; Type=DOUBLE, Leniency=INCREASE.
*/
public double XZ_SPEED_MAX_SOULSAND_POTION();
/**
* Maximum times a player can fail the speed check before action is taken; Type=INTEGER, Leniency=INCREASE.
*/
public int SPEED_MAX();
/**
* The number of clicks we should wait before checking if the player has used fast inventory; Type=INTEGER; Leniency=INCREASE.
*/
public int INVENTORY_CHECK();
/**
* The minimum time it should have taken for the player to click X times; Type=INTEGER; Leniency=INCREASE.
*/
public int INVENTORY_TIMEMIN();
/**
* The number of steps we should wait before checking if the player has used timer cheating; Type=INTEGER; Leniency=INCREASE.
*/
public int TIMER_STEP_CHECK();
/**
* The minimum time it should have taken for the player to travel X steps; Type=SYSTEM; Leniency=DECREASE.
*/
public int TIMER_TIMEMIN();
/**
* Minimum travel distance for move to be considered a teleport and subsequently be ignored; Type=INTEGER, Leniency=INCREASE.
*/
public int TELEPORT_MIN();
/**
* Maximum amount of times a player can hit a killaura bot; Type=INTEGER, Leniency=INCREASE.
*/
public int KILLAURA_BOTHITS();
/**
* Maximum amount of packets a player can send in a second; Type=INTEGER, Leniency=INCREASE.
*/
public int BLINK_PACKET();
/**
* Maximum amount of low/zero velocity before flagging; Type=INTEGER, Leniency=INCREASE.
*/
public int VELOCITY_AMT();
}
@@ -0,0 +1,34 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.providers;
import java.util.List;
import com.rammelkast.anticheatreloaded.util.rule.Rule;
public interface Rules {
/**
* Get all rules.
*
* @return List of rules.
*/
public List<Rule> getRules();
}
@@ -0,0 +1,200 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.config.yaml;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.file.YamlConstructor;
import org.bukkit.configuration.file.YamlRepresenter;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.representer.Representer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
/**
* An extension of {@link org.bukkit.configuration.file.YamlConfiguration} which preserves comments.
* Note that this implementation is not synchronized.
* <br>
* Some overridden code has been moved to this file from its parent & modified.
*/
public class CommentedConfiguration extends YamlConfiguration {
private Map<Integer, String> comments = new HashMap<Integer, String>();
private final DumperOptions yamlOptions = new DumperOptions();
private final Representer yamlRepresenter = new YamlRepresenter();
private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
@Override
public void loadFromString(String contents) throws InvalidConfigurationException {
Validate.notNull(contents, "Contents cannot be null");
Map<?, ?> input;
try {
input = (Map<?, ?>) yaml.load(contents);
} catch (YAMLException e) {
throw new InvalidConfigurationException(e);
} catch (ClassCastException e) {
throw new InvalidConfigurationException("Top level is not a Map.");
}
/** - CommentedConfiguration
String header = parseHeader(contents);
if (header.length() > 0) {
options().header(header);
}
**/
if (input != null) {
convertMapsToSections(input, this);
}
// Begin CommentedConfiguration
int i = 0;
int blank = 0;
String[] lines = contents.split("\n");
while (i < lines.length) {
if (lines[i].trim().equalsIgnoreCase("")) {
i++;
blank++;
continue;
}
if (lines[i].contains(COMMENT_PREFIX)) {
comments.put(i - blank, lines[i]);
}
i++;
}
// End CommentedConfiguration
}
@Override
public String saveToString() {
yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
// String header = buildHeader(); - CommentedConfiguration
String dump = yaml.dump(getValues(false));
if (dump.equals(BLANK_CONFIG)) {
dump = "";
}
// Begin CommentedConfiguration
StringBuilder builder = new StringBuilder();
String[] lines = dump.split("\n");
ArrayDeque<String> queue = new ArrayDeque<String>();
for (String string : lines) {
queue.add(string);
}
int i = 0;
while (queue.size() > 0) {
if (comments.containsKey(i)) {
builder.append(comments.get(i));
// Handle subsequent comments
int b = i;
while (true) {
b++;
if (comments.containsKey(b)) {
builder.append('\n');
builder.append(comments.get(b));
} else {
break;
}
}
builder.append('\n');
i = b;
}
builder.append(queue.getFirst());
builder.append('\n');
queue.pop();
i++;
}
// End CommentedConfiguration
return builder.toString();
}
/**
* Creates a new {@link CommentedConfiguration}, loading from the given file.
* <p/>
* Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be returned.
*
* @param file Input file
* @return Resulting configuration
* @throws IllegalArgumentException Thrown if file is null
*/
public static CommentedConfiguration loadConfiguration(File file) {
Validate.notNull(file, "File cannot be null");
CommentedConfiguration config = new CommentedConfiguration();
try {
config.load(file);
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex);
} catch (InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex);
}
return config;
}
/**
* Creates a new {@link CommentedConfiguration}, loading from the given stream.
* <p/>
* Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be returned.
*
* @param stream Input stream
* @return Resulting configuration
* @throws IllegalArgumentException Thrown if stream is null
*/
public static CommentedConfiguration loadConfiguration(InputStream stream) {
Validate.notNull(stream, "Stream cannot be null");
CommentedConfiguration config = new CommentedConfiguration();
try {
config.load(stream);
} catch (IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex);
} catch (InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex);
}
return config;
}
}
@@ -0,0 +1,109 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.event;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.util.Distance;
import com.rammelkast.anticheatreloaded.util.Utilities;
public class BlockListener extends EventListener {
@EventHandler(priority = EventPriority.MONITOR)
public void onBlockDamage(BlockDamageEvent event) {
Player player = event.getPlayer();
if (event.getInstaBreak() || Utilities.isInstantBreak(event.getBlock().getType())) {
getBackend().logInstantBreak(player);
}
if (getCheckManager().willCheck(player, CheckType.AUTOTOOL)) {
CheckResult result = getBackend().checkAutoTool(player);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.AUTOTOOL);
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
final Player player = event.getPlayer();
if (player != null && getCheckManager().willCheck(player, CheckType.FAST_PLACE)) {
CheckResult result = getBackend().checkFastPlace(player);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FAST_PLACE);
} else {
decrease(player);
getBackend().logBlockPlace(player);
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler(ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
final Player player = event.getPlayer();
final Block block = event.getBlock();
boolean noHack = true;
if (player != null) {
CheckResult result;
if (getCheckManager().willCheck(player, CheckType.FAST_BREAK)) {
result = getBackend().checkFastBreak(player, block);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FAST_BREAK);
noHack = false;
}
}
if (getCheckManager().willCheck(player, CheckType.NO_SWING)) {
result = getBackend().checkSwing(player, block);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.NO_SWING);
noHack = false;
}
}
if (getCheckManager().willCheck(player, CheckType.LONG_REACH)) {
Distance distance = new Distance(player.getLocation(), block.getLocation());
result = getBackend().checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference());
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.LONG_REACH);
noHack = false;
}
}
}
if (noHack) {
decrease(player);
}
getBackend().logBlockBreak(player);
}
}
@@ -0,0 +1,174 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.event;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.check.combat.CriticalsCheck;
import com.rammelkast.anticheatreloaded.check.combat.KillAuraCheck;
import com.rammelkast.anticheatreloaded.check.combat.VelocityCheck;
import com.rammelkast.anticheatreloaded.util.Distance;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
public class EntityListener extends EventListener {
@EventHandler
public void onEntityShootBow(EntityShootBowEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
if (getCheckManager().willCheck(player, CheckType.FAST_BOW)) {
CheckResult result = getBackend().checkFastBow(player, event.getForce());
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FAST_BOW);
} else {
decrease(player);
}
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
if (event.getEntity() instanceof Player && event.getRegainReason() == RegainReason.SATIATED) {
Player player = (Player) event.getEntity();
if (getCheckManager().willCheck(player, CheckType.FAST_HEAL)) {
CheckResult result = getBackend().checkFastHeal(player);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FAST_HEAL);
} else {
decrease(player);
getBackend().logHeal(player);
}
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
if (player.getFoodLevel() < event.getFoodLevel() && getCheckManager().willCheck(player, CheckType.FAST_EAT)) // Make sure it's them actually gaining a food level
{
CheckResult result = getBackend().checkFastEat(player);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FAST_EAT);
} else {
decrease(player);
}
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
boolean noHack = true;
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event;
if (e.getDamager() instanceof Player) {
if (getCheckManager().willCheck((Player)e.getDamager(), CheckType.KILLAURA)) {
KillAuraCheck.doDamageEvent(e, (Player)e.getDamager());
}
if (getCheckManager().willCheck((Player)e.getDamager(), CheckType.CRITICALS)) {
CriticalsCheck.doDamageEvent(e, (Player)e.getDamager());
}
}
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
VelocityCheck.runCheck(e, player);
if (e.getDamager() instanceof Player) {
Player p = (Player) e.getDamager();
getBackend().logDamage(p, 1);
int value = p.getInventory().getItemInHand().containsEnchantment(Enchantment.KNOCKBACK) ? 2 : 1;
getBackend().logDamage(player, value);
if (getCheckManager().willCheck(p, CheckType.LONG_REACH)) {
Distance distance = new Distance(player.getLocation(), p.getLocation());
CheckResult result = getBackend().checkLongReachDamage(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference());
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), p, CheckType.LONG_REACH);
noHack = false;
}
}
} else {
if (e.getDamager() instanceof TNTPrimed || e.getDamager() instanceof Creeper) {
getBackend().logDamage(player, 3);
} else {
getBackend().logDamage(player, 1);
}
}
}
if (e.getDamager() instanceof Player) {
Player player = (Player) e.getDamager();
getBackend().logDamage(player, 1);
if (getCheckManager().willCheck(player, CheckType.AUTOTOOL)) {
CheckResult result = getBackend().checkAutoTool(player);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.AUTOTOOL);
noHack = false;
}
}
if (getCheckManager().willCheck(player, CheckType.FORCEFIELD)) {
CheckResult result = getBackend().checkSprintDamage(player);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FORCEFIELD);
noHack = false;
}
}
if (getCheckManager().willCheck(player, CheckType.FORCEFIELD)) {
CheckResult result = getBackend().checkSight(player, e.getEntity());
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FORCEFIELD);
noHack = false;
}
}
if (noHack) {
decrease(player);
}
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
}
@@ -0,0 +1,141 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.event;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.Backend;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.manage.*;
import com.rammelkast.anticheatreloaded.util.User;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class EventListener implements Listener {
private static final Map<CheckType, Integer> USAGE_LIST = new EnumMap<CheckType, Integer>(CheckType.class);
private static final Map<UUID, Integer> DECREASE_LIST = new HashMap<UUID, Integer>();
private static final CheckManager CHECK_MANAGER = AntiCheat.getManager().getCheckManager();
private static final Backend BACKEND = AntiCheat.getManager().getBackend();
private static final AntiCheat PLUGIN = AntiCheat.getManager().getPlugin();
private static final UserManager USER_MANAGER = AntiCheat.getManager().getUserManager();
private static final Configuration CONFIG = AntiCheat.getManager().getConfiguration();
public static void log(String message, Player player, CheckType type) {
User user = getUserManager().getUser(player.getUniqueId());
if (user != null) { // npc
logCheat(type, user);
if (user.increaseLevel(type) && message != null) {
AntiCheat.getManager().log(message);
}
removeDecrease(user);
}
}
private static void logCheat(CheckType type, User user) {
USAGE_LIST.put(type, getCheats(type) + 1);
// Ignore plugins that are creating NPCs with no names (why the hell)
if (user != null && user.getUUID() != null) {
type.logUse(user);
if (CONFIG.getConfig().enterprise.getValue() && CONFIG.getEnterprise().loggingEnabled.getValue()) {
CONFIG.getEnterprise().database.logEvent(user, type);
}
}
}
public void resetCheck(CheckType type) {
USAGE_LIST.put(type, 0);
}
public static int getCheats(CheckType type) {
int x = 0;
if (USAGE_LIST.get(type) != null) {
x = USAGE_LIST.get(type);
}
return x;
}
private static void removeDecrease(User user) {
int x = 0;
// Ignore plugins that are creating NPCs with no names
if (user.getUUID() != null) {
if (DECREASE_LIST.get(user.getUUID()) != null) {
x = DECREASE_LIST.get(user.getUUID());
x -= 2;
if (x < 0) {
x = 0;
}
}
DECREASE_LIST.put(user.getUUID(), x);
}
}
public static void decrease(Player player) {
User user = getUserManager().getUser(player.getUniqueId());
// Ignore plugins that are creating NPCs with no names
if (user.getUUID() != null) {
int x = 0;
if (DECREASE_LIST.get(user.getUUID()) != null) {
x = DECREASE_LIST.get(user.getUUID());
}
x += 1;
DECREASE_LIST.put(user.getUUID(), x);
if (x >= 10) {
user.decreaseLevel();
DECREASE_LIST.put(user.getUUID(), 0);
}
}
}
public static CheckManager getCheckManager() {
return CHECK_MANAGER;
}
public static AntiCheatManager getManager() {
return AntiCheat.getManager();
}
public static Backend getBackend() {
return BACKEND;
}
public static UserManager getUserManager() {
return USER_MANAGER;
}
public static AntiCheat getPlugin() {
return PLUGIN;
}
public static Configuration getConfig() {
return CONFIG;
}
public static boolean silentMode() {
return CONFIG.getConfig().silentMode.getValue();
}
}
@@ -0,0 +1,71 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.event;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.util.User;
public class InventoryListener extends EventListener {
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (!event.isRightClick() && !event.isShiftClick() && event.getWhoClicked() instanceof Player) {
Player player = (Player) event.getWhoClicked();
if (getCheckManager().willCheck(player, CheckType.FAST_INVENTORY)) {
CheckResult result = getBackend().checkInventoryClicks(player);
if (result.failed()) {
if (!silentMode()) {
//getUserManager().getUser(player.getName()).restoreInventory(event.getInventory());
player.getInventory().clear();
event.setCancelled(true);
}
log(result.getMessage(), player, CheckType.FAST_INVENTORY);
} else {
decrease(player);
}
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onInventoryOpen(InventoryOpenEvent event) {
if (event.getInventory().getType() != InventoryType.BEACON) {
getUserManager().getUser(event.getPlayer().getUniqueId()).setInventorySnapshot(event.getInventory().getContents());
}
}
@EventHandler
public void onInventoryClose(InventoryCloseEvent event) {
User user = getUserManager().getUser(event.getPlayer().getUniqueId());
if (user != null) {
user.removeInventorySnapshot();
}
}
}
@@ -0,0 +1,476 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.event;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerAnimationEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerBedLeaveEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.event.player.PlayerToggleFlightEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import org.bukkit.event.player.PlayerToggleSprintEvent;
import org.bukkit.event.player.PlayerVelocityEvent;
import org.bukkit.inventory.PlayerInventory;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.check.combat.KillAuraCheck;
import com.rammelkast.anticheatreloaded.check.movement.ElytraFly;
import com.rammelkast.anticheatreloaded.check.movement.FlightCheck;
import com.rammelkast.anticheatreloaded.check.movement.GlideCheck;
import com.rammelkast.anticheatreloaded.check.movement.SpeedCheck;
import com.rammelkast.anticheatreloaded.check.movement.WaterWalkCheck;
import com.rammelkast.anticheatreloaded.check.movement.YAxisCheck;
import com.rammelkast.anticheatreloaded.util.Distance;
import com.rammelkast.anticheatreloaded.util.Permission;
import com.rammelkast.anticheatreloaded.util.User;
import com.rammelkast.anticheatreloaded.util.Utilities;
import com.rammelkast.anticheatreloaded.util.VersionUtil;
public class PlayerListener extends EventListener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
if (getCheckManager().willCheck(player, CheckType.COMMAND_SPAM) && !Permission.getCommandExempt(player, event.getMessage().split(" ")[0])) {
CheckResult result = getBackend().checkCommandSpam(player, event.getMessage());
if (result.failed()) {
event.setCancelled(!silentMode());
if (!silentMode()) player.sendMessage(ChatColor.RED + result.getMessage());
getBackend().processCommandSpammer(player);
log(null, player, CheckType.COMMAND_SPAM);
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerToggleFlight(PlayerToggleFlightEvent event) {
if (!event.isFlying()) {
getBackend().logEnterExit(event.getPlayer());
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) {
if (event.getNewGameMode() != GameMode.CREATIVE) {
getBackend().logEnterExit(event.getPlayer());
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onProjectileLaunch(ProjectileLaunchEvent event) {
if (event.getEntity().getShooter() instanceof Player) {
Player player = (Player) event.getEntity().getShooter();
if (event.getEntity() instanceof Arrow) {
return;
}
if (getCheckManager().willCheck(player, CheckType.FAST_PROJECTILE)) {
CheckResult result = getBackend().checkProjectile(player);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.FAST_PROJECTILE);
}
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerTeleport(PlayerTeleportEvent event) {
if (event.getCause() == TeleportCause.ENDER_PEARL || event.getCause() == TeleportCause.PLUGIN) {
getBackend().logTeleport(event.getPlayer());
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerChangeWorlds(PlayerChangedWorldEvent event) {
getBackend().logTeleport(event.getPlayer());
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerToggleSneak(PlayerToggleSneakEvent event) {
if (event.isSneaking()) {
getBackend().logToggleSneak(event.getPlayer());
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerVelocity(PlayerVelocityEvent event) {
Player player = event.getPlayer();
if (getCheckManager().willCheck(player, CheckType.FLY)) {
if (getBackend().justVelocity(player) && getBackend().extendVelocityTime(player)) {
event.setCancelled(!silentMode());
return;
}
getBackend().logVelocity(player);
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
if (getCheckManager().willCheck(player, CheckType.CHAT_SPAM)) {
CheckResult result = getBackend().checkChatSpam(player, event.getMessage());
if (result.failed()) {
event.setCancelled(!silentMode());
if (!result.getMessage().equals("") && !silentMode()) {
player.sendMessage(ChatColor.RED + result.getMessage());
}
getBackend().processChatSpammer(player);
log(null, player, CheckType.CHAT_SPAM);
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerKick(PlayerKickEvent event) {
getBackend().garbageClean(event.getPlayer());
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
getBackend().garbageClean(event.getPlayer());
User user = getUserManager().getUser(event.getPlayer().getUniqueId());
getConfig().getLevels().saveLevelFromUser(user);
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerToggleSprint(PlayerToggleSprintEvent event) {
Player player = event.getPlayer();
if (!event.isSprinting()) {
getBackend().logEnterExit(player);
}
if (getCheckManager().willCheck(player, CheckType.SPRINT)) {
CheckResult result = getBackend().checkSprintHungry(event);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.SPRINT);
} else {
decrease(player);
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
PlayerInventory inv = player.getInventory();
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Material m = inv.getItemInHand().getType();
if (m == Material.BOW) {
getBackend().logBowWindUp(player);
} else if (Utilities.isFood(m)) {
getBackend().logEatingStart(player);
}
}
Block block = event.getClickedBlock();
if (block != null) {
Distance distance = new Distance(player.getLocation(), block.getLocation());
getBackend().checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference());
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler(ignoreCancelled = true)
public void onPlayerDropItem(PlayerDropItemEvent event) {
Player player = event.getPlayer();
if (getCheckManager().willCheck(player, CheckType.ITEM_SPAM)) {
CheckResult result = getBackend().checkFastDrop(player);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.ITEM_SPAM);
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler(ignoreCancelled = true)
public void onPlayerEnterBed(PlayerBedEnterEvent event) {
if (event.getBed().getType() != Material.BED) return;
getBackend().logEnterExit(event.getPlayer());
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler(ignoreCancelled = true)
public void onPlayerExitBed(PlayerBedLeaveEvent event) {
if (event.getBed().getType() != Material.BED) return;
getBackend().logEnterExit(event.getPlayer());
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerAnimation(PlayerAnimationEvent event) {
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
String section = "\u00a7";
if (getCheckManager().willCheck(player, CheckType.ZOMBE_FLY)) {
player.sendMessage(section + "f " + section + "f " + section + "1 " + section + "0 " + section + "2 " + section + "4");
}
if (getCheckManager().willCheck(player, CheckType.ZOMBE_CHEAT)) {
player.sendMessage(section + "f " + section + "f " + section + "2 " + section + "0 " + section + "4 " + section + "8");
}
if (getCheckManager().willCheck(player, CheckType.ZOMBE_NOCLIP)) {
player.sendMessage(section + "f " + section + "f " + section + "4 " + section + "0 " + section + "9 " + section + "6");
}
getBackend().logJoin(player);
User user = new User(player.getUniqueId());
user.setIsWaitingOnLevelSync(true);
getConfig().getLevels().loadLevelToUser(user);
getUserManager().addUser(user);
if (player.hasMetadata(Utilities.SPY_METADATA)) {
for (Player p : player.getServer().getOnlinePlayers()) {
if (!Permission.SYSTEM_SPY.get(p)) {
p.hidePlayer(player);
}
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerMove(PlayerMoveEvent event) {
final Player player = event.getPlayer();
if (getCheckManager().checkInWorld(player) && !getCheckManager().isOpExempt(player)) {
final Location from = event.getFrom();
final Location to = event.getTo();
final Distance distance = new Distance(from, to);
final double y = distance.getYDifference();
getBackend().logAscension(player, from.getY(), to.getY());
final User user = getUserManager().getUser(player.getUniqueId());
user.setTo(to.getX(), to.getY(), to.getZ());
KillAuraCheck.doMove(event);
if (getCheckManager().willCheckQuick(player, CheckType.SPRINT)) {
CheckResult result = getBackend().checkSprintStill(player, from, to);
if (result.failed()) {
event.setCancelled(!silentMode());
log(result.getMessage(), player, CheckType.SPRINT);
}
}
if (getCheckManager().willCheckQuick(player, CheckType.FLY) && !VersionUtil.isFlying(player)) {
CheckResult result = FlightCheck.runCheck(player, distance);
if (result.failed()) {
if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone()));
}
log(result.getMessage(), player, CheckType.FLY);
}
}
if (getCheckManager().willCheckQuick(player, CheckType.FLY) && !VersionUtil.isFlying(player)) {
CheckResult result = GlideCheck.runCheck(player, distance);
if (result.failed()) {
// NO TELEPORT NEEDED HERE, HANDLED BY CHECK ITSELF
log(result.getMessage(), player, CheckType.FLY);
}
}
if (getCheckManager().willCheckQuick(player, CheckType.FLY)) {
CheckResult result = ElytraFly.runCheck(player, distance);
if (result.failed()) {
log(result.getMessage(), player, CheckType.FLY);
}
}
if (getCheckManager().willCheckQuick(player, CheckType.VCLIP) && event.getFrom().getY() > event.getTo().getY()) {
CheckResult result = getBackend().checkVClip(player, new Distance(event.getFrom(), event.getTo()));
if (result.failed()) {
if (!silentMode()) {
int data = result.getData() > 3 ? 3 : result.getData();
Location newloc = new Location(player.getWorld(), event.getFrom().getX(), event.getFrom().getY() + data, event.getFrom().getZ());
if (newloc.getBlock().getType() == Material.AIR) {
event.setTo(newloc);
} else {
event.setTo(user.getGoodLocation(from.clone()));
}
player.damage(3);
}
log(result.getMessage(), player, CheckType.VCLIP);
}
}
if (getCheckManager().willCheckQuick(player, CheckType.NOFALL) && getCheckManager().willCheck(player, CheckType.FLY) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && event.getFrom().getY() > event.getTo().getY()) {
CheckResult result = getBackend().checkNoFall(player, y);
if (result.failed()) {
if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone()));
/*TODO: player.damage(1); better system for this, too exploitable*/
}
log(result.getMessage(), player, CheckType.NOFALL);
}
}
boolean changed = false;
if (event.getTo() != event.getFrom()) {
double x = distance.getXDifference();
double z = distance.getZDifference();
if (getCheckManager().willCheckQuick(player, CheckType.SPEED) && getCheckManager().willCheck(player, CheckType.FLY)) {
if (event.getFrom().getY() < event.getTo().getY()) {
CheckResult result = getBackend().checkYSpeed(player, y);
if (result.failed()) {
if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone()));
}
log(result.getMessage(), player, CheckType.SPEED);
changed = true;
}
}
CheckResult result = SpeedCheck.checkXZSpeed(player, x, z);
if (result.failed()) {
if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone()));
}
log(result.getMessage(), player, CheckType.SPEED);
changed = true;
}
}
if (getCheckManager().willCheckQuick(player, CheckType.WATER_WALK)) {
CheckResult result = WaterWalkCheck.runCheck(player, x, y, z);
if (result.failed()) {
if (!silentMode()) {
player.teleport(user.getGoodLocation(player.getLocation().add(0, -1.5, 0)));
}
log(result.getMessage(), player, CheckType.WATER_WALK);
changed = true;
}
}
if (getCheckManager().willCheckQuick(player, CheckType.SNEAK)) {
CheckResult result = getBackend().checkSneak(player, x, z);
if (result.failed()) {
if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone()));
player.setSneaking(false);
}
log(result.getMessage(), player, CheckType.SNEAK);
changed = true;
}
}
if (getCheckManager().willCheckQuick(player, CheckType.SPIDER)) {
CheckResult result = getBackend().checkSpider(player, y);
if (result.failed()) {
if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone()));
}
log(result.getMessage(), player, CheckType.SPIDER);
changed = true;
}
}
if (!changed) {
user.setGoodLocation(event.getFrom());
}
}
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onDeath(PlayerDeathEvent e) {
KillAuraCheck.cleanPlayer(e.getEntity()); // Remove bots on death to reduce lag
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void checkFly(PlayerMoveEvent event) {
// Check flight on highest to make sure other plugins have a chance to change the values first.
final Player player = event.getPlayer();
final User user = getUserManager().getUser(player.getUniqueId());
final Location from = event.getFrom();
final Location to = event.getTo();
if (!user.checkTo(to.getX(), to.getY(), to.getZ())) {
// The to value has been modified by another plugin
return;
}
if (getCheckManager().willCheck(player, CheckType.FLY) && !player.isFlying()) {
CheckResult result1 = YAxisCheck.runCheck(player, new Distance(from, to));
CheckResult result2 = getBackend().checkAscension(player, from.getY(), to.getY());
String log = result1.failed() ? result1.getMessage() : result2.failed() ? result2.getMessage() : "";
if (!log.equals("")) {
if (!silentMode()) {
event.setTo(user.getGoodLocation(from.clone()));
}
log(log, player, CheckType.FLY);
}
}
}
}
@@ -0,0 +1,58 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.event;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import com.rammelkast.anticheatreloaded.AntiCheat;
public class VehicleListener extends EventListener {
@EventHandler(ignoreCancelled = true)
public void onVehicleEnter(VehicleEnterEvent event) {
if (event.getEntered() instanceof Player) {
getBackend().logEnterExit((Player) event.getEntered());
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler(ignoreCancelled = true)
public void onVehicleExit(VehicleExitEvent event) {
if (event.getExited() instanceof Player) {
getBackend().logEnterExit((Player) event.getExited());
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
@EventHandler(ignoreCancelled = true)
public void onVehicleDestroy(VehicleDestroyEvent event) {
if (event.getVehicle().getPassenger() != null && event.getVehicle().getPassenger() instanceof Player) {
getBackend().logEnterExit((Player) event.getVehicle().getPassenger());
}
AntiCheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners());
}
}
@@ -0,0 +1,138 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.manage;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
import org.bukkit.plugin.RegisteredListener;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.Backend;
import com.rammelkast.anticheatreloaded.config.Configuration;
/**
* The internal hub for all managers.
*/
public class AntiCheatManager {
private static AntiCheat plugin = null;
private static Configuration configuration;
private static UserManager userManager = null;
private static CheckManager checkManager = null;
private static LoggingManager loggingManager = null;
private static Backend backend = null;
private static Map<String, RegisteredListener[]> eventchains = new ConcurrentHashMap<String, RegisteredListener[]>();
private static Map<String, Long> eventcache = new ConcurrentHashMap<String, Long>();
public AntiCheatManager(AntiCheat instance, Logger logger) {
plugin = instance;
configuration = new Configuration(plugin, this);
loggingManager = new LoggingManager(plugin, logger, configuration);
userManager = new UserManager(this);
checkManager = new CheckManager(this);
backend = new Backend(this);
}
public void log(String message) {
loggingManager.log(message);
}
public void debugLog(String message) {
loggingManager.debugLog(message);
}
public void playerLog(String message) {
loggingManager.logToPlayers(message);
}
public void addEvent(String e, RegisteredListener[] arr) {
if (!configuration.getConfig().eventChains.getValue())
return;
if (!eventcache.containsKey(e) || eventcache.get(e) > 30000L) {
eventchains.put(e, arr);
eventcache.put(e, System.currentTimeMillis());
}
}
public String getEventChainReport() {
String gen = "";
if (!configuration.getConfig().eventChains.getValue()) {
return "Event Chains is disabled by the configuration." + '\n';
}
if (eventchains.entrySet().size() == 0) {
return "No event chains found." + '\n';
}
for (Entry<String, RegisteredListener[]> e : eventchains.entrySet()) {
String toadd = "";
String ename = e.getKey();
toadd += ename + ":" + '\n';
RegisteredListener[] reg = e.getValue();
for (RegisteredListener plug : reg) {
String pluginname = plug.getPlugin().getName();
if (pluginname.equals("AntiCheat"))
pluginname = "self";
toadd += "- " + pluginname + '\n';
}
gen += toadd + '\n';
}
return gen;
}
public AntiCheat getPlugin() {
return plugin;
}
public Configuration getConfiguration() {
return configuration;
}
public UserManager getUserManager() {
return userManager;
}
public CheckManager getCheckManager() {
return checkManager;
}
public Backend getBackend() {
return backend;
}
public LoggingManager getLoggingManager() {
return loggingManager;
}
public static void close() {
loggingManager.closeHandler();
if (configuration.getConfig().enterprise.getValue()) {
configuration.getEnterprise().database.shutdown();
}
}
}
@@ -0,0 +1,200 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.manage;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.config.Configuration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* <p/>
* The manager that AntiCheat will check with to see if it should watch certain checks and certain players.
*/
public class CheckManager {
private AntiCheatManager manager = null;
private Configuration config;
private static List<CheckType> checkIgnoreList = new ArrayList<CheckType>();
private static Map<UUID, List<CheckType>> exemptList = new HashMap<UUID, List<CheckType>>();
public CheckManager(AntiCheatManager manager) {
this.manager = manager;
this.config = manager.getConfiguration();
for (String string : config.getConfig().disabledChecks.getValue()) {
for (CheckType type : CheckType.values()) {
if (type.toString().equalsIgnoreCase(string)) {
checkIgnoreList.add(type);
break;
}
}
}
}
/**
* Turn a check on
*
* @param type The CheckType to enable
*/
public void activateCheck(CheckType type, String className) {
if (!isActive(type)) {
manager.getLoggingManager().logFineInfo("The " + type.toString() + " check was activated by " + className + ".");
checkIgnoreList.remove(type);
}
}
/**
* Turn a check off
*
* @param type The CheckType to disable
*/
public void deactivateCheck(CheckType type, String className) {
if (isActive(type)) {
manager.getLoggingManager().logFineInfo("The " + type.toString() + " check was deactivated by " + className + ".");
checkIgnoreList.add(type);
}
}
/**
* Determine whether a check is enabled
*
* @param type The CheckType to check
* @return true if the check is active
*/
public boolean isActive(CheckType type) {
return !checkIgnoreList.contains(type);
}
/**
* Exempt a player from a check
*
* @param player The player
* @param type The check
*/
public void exemptPlayer(Player player, CheckType type, String className) {
if (!isExempt(player, type)) {
if (!exemptList.containsKey(player.getUniqueId())) {
exemptList.put(player.getUniqueId(), new ArrayList<CheckType>());
}
manager.getLoggingManager().logFineInfo(player.getName() + " was exempted from the " + type.toString() + " check by " + className + ".");
exemptList.get(player.getUniqueId()).add(type);
}
}
/**
* Unexempt a player from a check
*
* @param player The player
* @param type The check
*/
public void unexemptPlayer(Player player, CheckType type, String className) {
if (isExempt(player, type)) {
manager.getLoggingManager().logFineInfo(player.getName() + " was unexempted from the " + type.toString() + " check by " + className + ".");
exemptList.get(player.getUniqueId()).remove(type);
}
}
/**
* Determine whether a player is exempt from a check
*
* @param player The player
* @param type The check
*/
public boolean isExempt(Player player, CheckType type) {
return exemptList.containsKey(player.getUniqueId()) ? exemptList.get(player.getUniqueId()).contains(type) : false;
}
/**
* Determine whether a player is exempt from all checks from op status
*
* @param player The player
*/
public boolean isOpExempt(Player player) {
return (this.manager.getConfiguration().getConfig().exemptOp.getValue() && player.isOp());
}
/**
* Determine whether a player should be checked in their world
*
* @param player The player
* @return true if the player's world is enabled
*/
public boolean checkInWorld(Player player) {
return !config.getConfig().disabledWorlds.getValue().contains(player.getWorld().getName());
}
/**
* Run a quick version of the "willCheck" method, using the other non-check-specific methods beforehand
*
* @param player The player to check
* @param type The check being run
* @return true if the check should run
*/
public boolean willCheckQuick(Player player, CheckType type) {
return
isActive(type)
&& !isExempt(player, type)
&& !type.checkPermission(player);
}
/**
* Determine whether a check should run on a player
*
* @param player The player to check
* @param type The check being run
* @return true if the check should run
*/
public boolean willCheck(Player player, CheckType type) {
boolean check = isActive(type)
&& checkInWorld(player)
&& !isExempt(player, type)
&& !type.checkPermission(player)
&& !isOpExempt(player);
AntiCheat.debugLog("Check " + type + (check ? " run " : " not run ") + "on " + player.getName());
// TODO temp fix
if ((type == CheckType.FLY || type == CheckType.SPEED) && player.isFlying())
return false;
return check;
}
/**
* Determine whether a player is actually online; not an NPC
*
* @param player Player to check
* @return true if the player is a real person
*/
public boolean isOnline(Player player) {
// Check if the player is on the user list, e.g. is not an NPC
for (Player p : Bukkit.getOnlinePlayers()) {
if (p.getUniqueId().equals(player.getUniqueId())) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,117 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.manage;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.util.FileFormatter;
import com.rammelkast.anticheatreloaded.util.Permission;
import java.io.File;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LoggingManager {
private final Logger fileLogger;
private static Handler fileHandler;
private static List<String> logs = new CopyOnWriteArrayList<String>();
private final Configuration config;
public LoggingManager(AntiCheat plugin, Logger logger, Configuration config) {
this.fileLogger = Logger.getLogger("net.gravitydevelopment.anticheat.AntiCheat");
this.config = config;
try {
File file = new File(plugin.getDataFolder(), "log");
if (!file.exists()) {
file.mkdir();
}
fileHandler = new FileHandler(plugin.getDataFolder() + "/log/anticheat.log", true);
fileHandler.setFormatter(new FileFormatter());
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
}
fileLogger.setUseParentHandlers(false);
fileLogger.addHandler(fileHandler);
}
public void log(String message) {
if (config.getConfig().logToConsole.getValue()) {
logToConsole(message);
}
if (config.getConfig().logToFile.getValue()) {
logToFile(message);
}
logToLogs(message);
}
public void debugLog(String message) {
Bukkit.getConsoleSender().sendMessage("[AntiCheat] " + ChatColor.GRAY + message);
logToLogs(message);
}
public void logToConsole(String message) {
Bukkit.getConsoleSender().sendMessage("[AntiCheat] " + ChatColor.RED + message);
}
public void logToFile(String message) {
fileLogger.info(ChatColor.stripColor(message));
}
public void logFineInfo(String message) {
logToFile(message);
logToLogs(message);
}
public void logToPlayers(String message) {
for(Player player : Bukkit.getOnlinePlayers()) {
if (Permission.SYSTEM_NOTICE.get(player)) {
player.sendMessage(message);
}
}
}
private void logToLogs(String message) { // Yo dawg
logs.add(ChatColor.stripColor(message));
}
public List<String> getLastLogs() {
List<String> log = new CopyOnWriteArrayList<String>();
if (logs.size() < 30) {
return logs;
}
for (int i = logs.size() - 1; i >= 0; i--) {
log.add(logs.get(i));
}
logs.clear();
return log;
}
public void closeHandler() {
fileHandler.close();
}
}
@@ -0,0 +1,37 @@
package com.rammelkast.anticheatreloaded.manage;
import com.comphenix.protocol.Packets;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.*;
import com.rammelkast.anticheatreloaded.AntiCheat;
public class PacketManager {
private ProtocolManager protocolManager;
private AntiCheat plugin;
private AntiCheatManager manager;
public PacketManager(ProtocolManager protocolManager, AntiCheat plugin, AntiCheatManager manager) {
this.protocolManager = protocolManager;
this.plugin = plugin;
this.manager = manager;
addListeners();
}
private void addListeners() {
// Arm Animation
protocolManager.addPacketListener(new PacketAdapter(plugin,
ConnectionSide.CLIENT_SIDE,
ListenerPriority.NORMAL,
Packets.Client.ARM_ANIMATION) {
@Override
public void onPacketReceiving(PacketEvent event) {
if (event.getPacketID() == Packets.Client.ARM_ANIMATION) {
PacketContainer packet = event.getPacket();
//System.out.println("Arm animation from "+packet.getIntegers().read(0));
}
}
});
}
}
@@ -0,0 +1,260 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.manage;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.util.Group;
import com.rammelkast.anticheatreloaded.util.User;
import com.rammelkast.anticheatreloaded.util.Utilities;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class UserManager {
private List<User> users = new ArrayList<User>();
private static AntiCheatManager manager;
private static Configuration config;
private static final ChatColor GRAY = ChatColor.GRAY;
private static final ChatColor GOLD = ChatColor.GOLD;
private static final ChatColor RED = ChatColor.RED;
/**
* Initialize the user manager
*
* @param manager The AntiCheat Manager
*/
public UserManager(AntiCheatManager manager) {
this.manager = manager;
this.config = manager.getConfiguration();
}
/**
* Get a user with the given UUID
*
* @param uuid UUID
* @return User with UUID
*/
public User getUser(UUID uuid) {
for (User user : users) {
if (user.getUUID().equals(uuid)) {
return user;
}
}
// Otherwise try to load them
User user = new User(uuid);
user.setIsWaitingOnLevelSync(true);
config.getLevels().loadLevelToUser(user);
return user;
}
/**
* Get all users
*
* @return List of users
*/
public List<User> getUsers() {
return users;
}
/**
* Add a user to the list
*
* @param user User to add
*/
public void addUser(User user) {
users.add(user);
}
/**
* Remove a user from the list
*
* @param user User to remove
*/
public void remove(User user) {
users.remove(user);
}
/**
* Save a user's level
*
* @param user User to save
*/
public void saveLevel(User user) {
config.getLevels().saveLevelFromUser(user);
}
/**
* Get users in group
*
* @param group Group to find users of
*/
public List<User> getUsersInGroup(Group group) {
List<User> list = new ArrayList<User>();
for (User u : users) {
if (u.getGroup() == group) {
list.add(u);
}
}
return list;
}
/**
* Get a user's level, or 0 if the player isn't found
*
* @param uuid UUID of the player
* @return player level
*/
public int safeGetLevel(UUID uuid) {
User user = getUser(uuid);
if (user == null) {
return 0;
} else {
return user.getLevel();
}
}
/**
* Set a user's level
*
* @param uuid UUID of the player
* @param level Group to set
*/
public void safeSetLevel(UUID uuid, int level) {
User user = getUser(uuid);
if (user != null) {
user.setLevel(level);
}
}
/**
* Reset a user
*
* @param uuid UUID of the user
*/
public void safeReset(UUID uuid) {
User user = getUser(uuid);
if (user != null) {
user.resetLevel();
}
}
/**
* Get the alert to use for a check being failed
*
* @return check fail alert message
*/
public List<String> getAlert() {
return config.getLang().ALERT();
}
/**
* Fire an alert
*
* @param user The user to alert
* @param group The user's group
* @param type The CheckType that triggered the alert
*/
public void alert(User user, Group group, CheckType type) {
ArrayList<String> messageArray = new ArrayList<String>();
List<String> alert = getAlert();
for (int i = 0; i < alert.size(); i++) {
String message = alert.get(i);
if (!message.equals("")) {
message = message.replaceAll("&player", GOLD + user.getName() + GRAY);
message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY);
message = message.replaceAll("&group", group.getColor() + group.getName() + GRAY);
message = message.replaceAll("&level", "" + user.getLevel() + GRAY);
messageArray.add(message);
}
}
Utilities.alert(messageArray);
execute(user, group.getActions(), type);
}
/**
* Execute configuration actions for an alert
*
* @param user The user
* @param actions The list of actions to execute
* @param type The CheckType that triggered the alert
*/
public void execute(User user, List<String> actions, CheckType type) {
execute(user, actions, type, config.getLang().KICK_REASON(), config.getLang().WARNING(), config.getLang().BAN_REASON());
}
/**
* Execute configuration actions for an alert
*
* @param user The user
* @param actions The list of actions to execute
* @param type The CheckType that triggered the alert
* @param kickReason The config's kick reason
* @param warning The config's warning format
* @param banReason The config's ban reason
*/
public void execute(final User user, final List<String> actions, final CheckType type, final String kickReason, final List<String> warning, final String banReason) {
// Execute synchronously for thread safety when called from AsyncPlayerChatEvent
Bukkit.getScheduler().scheduleSyncDelayedTask(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
final String name = user.getName();
for (String event : actions) {
event = event.replaceAll("&player", name).replaceAll("&world", user.getPlayer().getWorld().getName()).replaceAll("&check", type.name());
if (event.startsWith("COMMAND[")) {
for (String cmd : Utilities.getCommands(event)) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd);
}
} else if (event.equalsIgnoreCase("KICK")) {
user.getPlayer().kickPlayer(RED + kickReason);
String msg = RED + config.getLang().KICK_BROADCAST().replaceAll("&player", name) + " (" + CheckType.getName(type) + ")";
if (!msg.equals("")) {
manager.log(msg);
manager.playerLog(msg);
}
} else if (event.equalsIgnoreCase("WARN")) {
List<String> message = warning;
for (String string : message) {
if (!string.equals("")) {
user.getPlayer().sendMessage(RED + string);
}
}
} else if (event.equalsIgnoreCase("BAN")) {
user.getPlayer().setBanned(true);
user.getPlayer().kickPlayer(RED + banReason);
String msg = RED + config.getLang().BAN_BROADCAST().replaceAll("&player", name) + " (" + CheckType.getName(type) + ")";
if (!msg.equals("")) {
manager.log(msg);
manager.playerLog(msg);
}
} else if (event.equalsIgnoreCase("RESET")) {
user.resetLevel();
}
}
}
});
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,225 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.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),
LOG_2(2.00D),
LEAVES(0.20D),
LEAVES_2(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),
DOUBLE_PLANT(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),
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),
PACKED_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),
STAINED_GLASS(0.30D),
STAINED_GLASS_PANE(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(1.50D),
NETHER_BRICK_STAIRS(2.00D),
SPRUCE_WOOD_STAIRS(2.00D),
BIRCH_WOOD_STAIRS(2.00D),
JUNGLE_WOOD_STAIRS(2.00D),
DARK_OAK_STAIRS(2.00D),
ACACIA_STAIRS(2.00D),
QUARTZ_STAIRS(0.80D),
SANDSTONE_STAIRS(0.80D),
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) {
try {
BlockHardness h = getHardness(m);
return h == null ? 0D : h.hardness;
}catch(Exception e) {
return 0D;
}
}
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,59 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.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-2014 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 com.rammelkast.anticheatreloaded.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,89 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.util;
import org.bukkit.ChatColor;
import com.rammelkast.anticheatreloaded.AntiCheat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Group {
private String name;
private int level;
private ChatColor color = ChatColor.RED;
private List<String> actions = new ArrayList<String>();
public Group(String name, int level, String color, List<String> actions) {
this.name = name;
this.level = level;
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 String getName() {
return name;
}
public int getLevel() {
return level;
}
public ChatColor getColor() {
return color;
}
public List<String> getActions() {
return actions;
}
public static Group load(String string) {
try {
if (string.split(" : ").length == 4) {
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 Group(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 + " : " + level + " : " + color.name() + " : " + Utilities.listToCommaString(actions);
}
}
@@ -0,0 +1,18 @@
package com.rammelkast.anticheatreloaded.util;
import java.util.EnumSet;
import org.bukkit.Material;
import org.bukkit.potion.PotionEffectType;
public class NMS_1_9_PLUS {
static final EnumSet<Material> MOVE_UP_BLOCKS_1_9 = EnumSet.of(Material.ACACIA_STAIRS,
Material.BIRCH_WOOD_STAIRS, Material.BRICK_STAIRS, Material.COBBLESTONE_STAIRS, Material.DARK_OAK_STAIRS,
Material.JUNGLE_WOOD_STAIRS, Material.NETHER_BRICK_STAIRS, Material.QUARTZ_STAIRS,
Material.RED_SANDSTONE_STAIRS, Material.SANDSTONE_STAIRS, Material.SMOOTH_STAIRS,
Material.SPRUCE_WOOD_STAIRS, Material.WOOD_STAIRS, Material.PURPUR_STAIRS);
static final PotionEffectType LEVITATION = PotionEffectType.LEVITATION;
}
@@ -0,0 +1,186 @@
package com.rammelkast.anticheatreloaded.util;
import java.util.Random;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_11_R1.CraftServer;
import org.bukkit.craftbukkit.v1_11_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import com.mojang.authlib.GameProfile;
import com.rammelkast.anticheatreloaded.AntiCheat;
import net.minecraft.server.v1_11_R1.EntityHuman;
import net.minecraft.server.v1_11_R1.EntityPlayer;
import net.minecraft.server.v1_11_R1.MinecraftServer;
import net.minecraft.server.v1_11_R1.PacketPlayOutEntityMetadata;
import net.minecraft.server.v1_11_R1.PacketPlayOutEntityTeleport;
import net.minecraft.server.v1_11_R1.PacketPlayOutNamedEntitySpawn;
import net.minecraft.server.v1_11_R1.PacketPlayOutPlayerInfo;
import net.minecraft.server.v1_11_R1.PlayerConnection;
import net.minecraft.server.v1_11_R1.PlayerInteractManager;
import net.minecraft.server.v1_11_R1.World;
import net.minecraft.server.v1_11_R1.WorldServer;
public class NPC_1_11 {
private final UUID owner;
private final String name;
private UUID uuid;
private EntityPlayer npc;
private int entityId;
private Location location;
public int getID() {
return this.entityId;
}
public NPC_1_11(Player owner) {
this.owner = owner.getUniqueId();
this.name = NameGenerator.generateName();
Location eyelocation = owner.getEyeLocation();
Vector vec = owner.getLocation().getDirection();
vec.setX(-3 * vec.getX());
vec.setZ(-3 * vec.getZ());
Location back = eyelocation.add(vec);
this.location = back; // TODO
}
public void spawn() {
final MinecraftServer nmsServer = ((CraftServer) Bukkit.getServer()).getServer();
final WorldServer nmsWorld = ((CraftWorld) this.getOwner().getWorld()).getHandle();
this.uuid = UUID.randomUUID();
(this.npc = new EntityPlayer(nmsServer, nmsWorld, new GameProfile(this.uuid, this.name),
new PlayerInteractManager((World) nmsWorld))).setLocation(this.location.getX(), this.location.getY(),
this.location.getZ(), 0.0f, 0.0f);
this.npc.collides = false;
this.npc.setInvisible(true);
this.entityId = this.npc.getId();
final PlayerConnection connection = ((CraftPlayer) this.getOwner()).getHandle().playerConnection;
connection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER,
new EntityPlayer[] { this.npc }));
connection.sendPacket(new PacketPlayOutNamedEntitySpawn((EntityHuman) this.npc));
}
public boolean up = true;
public void move(PlayerMoveEvent e) {
if (e.getTo().getPitch() <= -32.5) {
if (e.getTo().getPitch() <= -82.5) {
Location eyelocation = e.getPlayer().getEyeLocation();
Vector vec = e.getPlayer().getLocation().getDirection();
vec.setX(-3 * vec.getX());
vec.setY(e.getPlayer().getLocation().getY() - 8.25);
vec.setZ(-3 * vec.getZ());
Location back = eyelocation.add(vec);
this.location = back; // TODO
this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), (float)new Random().nextFloat() * 20, (float)new Random().nextFloat() * 20);
((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityTeleport(npc));
if (new Random().nextInt(50) == 25 && this.npc.isInvisible()) {
this.npc.setInvisible(false);
((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false));
new BukkitRunnable() {
@Override
public void run() {
npc.setInvisible(true);
((CraftPlayer) getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false));
}
}.runTaskLater(AntiCheat.getPlugin(), 4);
}
}else {
Location eyelocation = e.getPlayer().getEyeLocation();
Vector vec = e.getPlayer().getLocation().getDirection();
vec.setX(-3 * vec.getX());
vec.setY(e.getPlayer().getLocation().getY());
vec.setZ(-3 * vec.getZ());
Location back = eyelocation.add(vec);
this.location = back; // TODO
this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), (float)new Random().nextFloat() * 20, (float)new Random().nextFloat() * 20);
((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityTeleport(npc));
}
} else if (e.getTo().getPitch() >= 22) {
Location eyelocation = e.getPlayer().getEyeLocation();
Vector vec = e.getPlayer().getLocation().getDirection();
vec.setX(-3 * vec.getX());
vec.setY(e.getPlayer().getLocation().getY() - 0.4);
vec.setZ(-3 * vec.getZ());
Location back = eyelocation.add(vec);
this.location = back; // TODO
this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), (float)new Random().nextFloat() * 20, (float)new Random().nextFloat() * 20);
((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityTeleport(npc));
} else {
Location eyelocation = e.getPlayer().getEyeLocation();
Vector vec = e.getPlayer().getLocation().getDirection();
vec.setX(-1.95 * vec.getX());
if (up)
vec.setY(vec.getY() + 0.5);
else
vec.setY(vec.getY() - 0.25);
if (new Random().nextInt(10) == 5)
up = !up;
vec.setZ(-1.95 * vec.getZ());
Location back = eyelocation.add(vec);
this.location = back; // TODO
this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), (float)new Random().nextFloat() * 20, (float)new Random().nextFloat() * 20);
((CraftPlayer) this.getOwner()).getHandle().playerConnection
.sendPacket(new PacketPlayOutEntityTeleport(npc));
if (new Random().nextInt(1000) == 500 && this.npc.isInvisible()) {
this.npc.setInvisible(false);
((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false));
new BukkitRunnable() {
@Override
public void run() {
npc.setInvisible(true);
((CraftPlayer) getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false));
}
}.runTaskLater(AntiCheat.getPlugin(), 6);
}
}
}
public Player getOwner() {
return Bukkit.getPlayer(owner);
}
public void damage(EntityDamageByEntityEvent e, Player p) {
if (p != getOwner() || this.npc == null) {
return;
}
if (new Random().nextBoolean() && this.npc.isInvisible()) {
this.npc.setInvisible(false);
((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false));
new BukkitRunnable() {
@Override
public void run() {
npc.setInvisible(true);
((CraftPlayer) getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false));
}
}.runTaskLater(AntiCheat.getPlugin(), 6 + new Random().nextInt(7));
}
}
public void damage() {
if (this.npc == null) {
return;
}
if (new Random().nextBoolean() && this.npc.isInvisible()) {
this.npc.setInvisible(false);
((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false));
new BukkitRunnable() {
@Override
public void run() {
npc.setInvisible(true);
((CraftPlayer) getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false));
}
}.runTaskLater(AntiCheat.getPlugin(), 6 + new Random().nextInt(8));
}
}
}
@@ -0,0 +1,45 @@
package com.rammelkast.anticheatreloaded.util;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class NameGenerator {
private static final List<String> BEGIN = Arrays.asList(new String[]{
"Pixel",
"Pro",
"NoHax",
"Just",
"That",
"New",
"Ultra",
"Killer",
"Swift"
});
private static final List<String> END = Arrays.asList(new String[]{
"Gamer",
"PvP",
"JustYolo",
"Gaming",
"Minecraft",
"Games",
"Bawz",
"1",
"51",
"99",
"" + new Random().nextInt(100)
});
public static String generateName() {
Random r = new Random();
String begin = BEGIN.get(r.nextInt(BEGIN.size() - 1));
String end = END.get(r.nextInt(END.size() - 1));
if (r.nextBoolean())
return begin + end + r.nextInt(9);
else
return begin + end;
}
}
@@ -0,0 +1,37 @@
package com.rammelkast.anticheatreloaded.util;
import java.util.Random;
public class NameUtil {
private static String[] firstParts = new String[] {
"Gamer",
"Pixel",
"Derp",
"Random",
"That",
"NoHaxJust",
"Derp",
"Fun",
"Luigi"
};
private static String[] secondParts = new String[] {
"01",
"Boy",
"Guy",
"Mario",
"Plain",
"Simple",
"NotHacking",
"Random",
"11",
"06"
};
private static Random theRandom = new Random();
public static String getRandomName() {
return firstParts[theRandom.nextInt(firstParts.length - 1)] + secondParts[theRandom.nextInt(secondParts.length - 1)];
}
}
@@ -0,0 +1,228 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.util;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.config.providers.Magic;
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 static final String DATE = new SimpleDateFormat("yyyy-MM-dd kk:mm Z").format(new Date());
private static final String API_KEY = "d5ac92da966edb97a97860e6a052784f";
private StringBuilder report = new StringBuilder();
private String url = "";
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 - " + 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().getLoggingManager().getLastLogs();
if (logs.size() == 0) {
append("No recent logs.");
return;
}
for (String log : logs) {
append(log);
}
}
private void appendSystemInfo() {
Runtime runtime = Runtime.getRuntime();
Configuration config = AntiCheat.getManager().getConfiguration();
append("AntiCheat Version: " + AntiCheat.getVersion());
append("Server Version: " + Bukkit.getVersion());
append("Server Implementation: " + Bukkit.getName());
append("Server ID: " + Bukkit.getServerId());
append("NMS Version: " + VersionUtil.getVersion());
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: " + Bukkit.getOnlineMode());
append("Players: " + Bukkit.getOnlinePlayers().size() + "/" + Bukkit.getMaxPlayers());
append("Plugin Count: " + Bukkit.getPluginManager().getPlugins().length);
append("Plugin Uptime: " + ((System.currentTimeMillis() - AntiCheat.getPlugin().getLoadTime()) / 1000) / 60 + " minutes");
append("Enterprise: " + config.getConfig().enterprise.getValue());
if (config.getConfig().enterprise.getValue()) {
append("- Server name: " + config.getEnterprise().serverName.getValue());
append("- Database type: " + config.getEnterprise().database.getType());
append("- Groups source: " + (config.getEnterprise().configGroups.getValue() ? "Database" : "Flatfile"));
append("- Rules source: " + (config.getEnterprise().configRules.getValue() ? "Database" : "Flatfile"));
append("- Levels source: " + (config.getEnterprise().syncLevels.getValue() ? "Database" : "Flatfile"));
}
}
private void appendMagicDiff() {
// This is hacky, and I like it
Magic magic = AntiCheat.getManager().getConfiguration().getMagic();
FileConfiguration file = YamlConfiguration.loadConfiguration(new File(AntiCheat.getPlugin().getDataFolder(), "magic.yml"));
boolean changed = false;
for (Field field : Magic.class.getFields()) {
Object defaultValue = file.get(field.getName());
try {
Field value = magic.getClass().getDeclaredField(field.getName());
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(API_KEY, "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,97 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.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_CHATSPAM,
CHECK_COMMANDSPAM,
CHECK_SPRINT,
CHECK_SNEAK,
CHECK_SPEED,
CHECK_VCLIP,
CHECK_SPIDER,
CHECK_NOFALL,
CHECK_FASTBOW,
CHECK_FASTEAT,
CHECK_FASTHEAL,
CHECK_FORCEFIELD,
CHECK_LONGREACH,
CHECK_FASTPROJECTILE,
CHECK_ITEMSPAM,
CHECK_VISUAL,
CHECK_FASTINVENTORY,
CHECK_AUTOTOOL,
/* System Nodes */
SYSTEM_LOG,
SYSTEM_RESET,
SYSTEM_SPY,
SYSTEM_HELP,
SYSTEM_UPDATE,
SYSTEM_REPORT,
SYSTEM_ALERT,
SYSTEM_NOTICE,
SYSTEM_CALIBRATE,
SYSTEM_CHECK,
SYSTEM_DEBUG,
SYSTEM_RELOAD, CHECK_KILLAURA, CHECK_BLINK, VELOCITY, CRITICALS;
private static final String PERMISSION_ALL = "anticheat.*";
private static final String PERMISSION_SPAM = "anticheat.check.spam";
public static boolean getCommandExempt(CommandSender cs, String commandLabel) {
// Check permission, base, and all will have already been checked
return cs.hasPermission(CHECK_COMMANDSPAM.toString() + commandLabel);
}
public boolean get(CommandSender cs) {
if ((this == CHECK_CHATSPAM || this == CHECK_COMMANDSPAM) && cs.hasPermission(PERMISSION_SPAM)) return true;
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[]{PERMISSION_ALL, getBase(), toString()}) {
if (cs.hasPermission(s)) {
return s;
}
}
return null;
}
@Override
public String toString() {
return "anticheat." + this.name().toLowerCase().replace("_", ".");
}
}
@@ -0,0 +1,48 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.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,431 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.util;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.config.Configuration;
import com.rammelkast.anticheatreloaded.util.rule.Rule;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class User {
private final UUID uuid;
private final String name;
private final int id;
private int level = 0;
private Location goodLocation;
private List<ItemStack> inventorySnapshot = null;
private Configuration config = AntiCheat.getManager().getConfiguration();
private int toX, toY, toZ;
private String[] messages = new String[2];
private Long[] messageTimes = new Long[2];
private String[] commands = new String[2];
private Long[] commandTimes = new Long[2];
private boolean isWaitingOnLevelSync;
private Timestamp levelSyncTimestamp;
/**
* Initialize an AntiCheat user
*
* @param uuid Player's UUID
*/
public User(UUID uuid) {
this.uuid = uuid;
this.name = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getName() : "";
this.id = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getEntityId() : -1;
}
/**
* Initialize an AntiCheat user
*
* @param name Player's name
*/
/* public User(String name) {
this.uuid = Bukkit.getPlayer(name).getUniqueId();
this.name = name;
this.id = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getEntityId() : -1;
}
*/
/**
* Get the player's UUID
*
* @return Player UUID
*/
public UUID getUUID() {
return uuid;
}
/**
* Get the player's name
*
* @return Player name
*/
public String getName() {
return name;
}
/**
* Get the player's entity ID
*
* @return Entity id
*/
public int getId() {
return id;
}
/**
* Get the Bukkit player
*
* @return Player
*/
public Player getPlayer() {
return Bukkit.getPlayer(uuid);
}
/**
* Get the user's level value
*
* @return level
*/
public int getLevel() {
return level;
}
/**
* Get the user's group
*
* @return group
*/
public Group getGroup() {
List<Group> groups = config.getGroups().getGroups();
for (int i = 0; i < groups.size(); i++) {
if (i == 0 && level < groups.get(i).getLevel()) break;
else if (i == groups.size() - 1) return groups.get(i);
else if (level >= groups.get(i).getLevel() && level < groups.get(i + 1).getLevel()) return groups.get(i);
}
return null;
}
/**
* Increase the player's level (from failing a check)
*
* @param type The check failed
* @return true if the level was increased
*/
public boolean increaseLevel(CheckType type) {
if (getPlayer() != null && getPlayer().isOnline()) {
if (silentMode() && type.getUses(uuid) % 4 != 0) {
// Prevent silent mode from increasing the level way too fast
return false;
} else {
if (level < config.getGroups().getHighestLevel()) {
level++;
// Check levels
for (Group l : getLevels()) {
if (l.getLevel() == level) {
AntiCheat.getManager().getUserManager().alert(this, l, type);
if (l.getLevel() == config.getGroups().getHighestLevel()) {
level = l.getLevel() - 10;
}
}
}
// Execute rules
for (Rule rule : config.getRules().getRules()) {
rule.check(this, type);
}
return true;
}
return false;
}
} else {
return false;
}
}
/**
* Decrease the player's level by one value
*/
public void decreaseLevel() {
level = level != 0 ? level - 1 : 0;
}
/**
* Set the users level to a specific value. Must be 0 < level < config-defined highest level
*
* @param level level to set
* @return true if the level was valid and set properly
*/
public boolean setLevel(int level) {
isWaitingOnLevelSync = false;
if (level >= 0) {
if (level <= config.getGroups().getHighestLevel()) {
this.level = level;
return true;
} else {
this.level = config.getGroups().getHighestLevel();
return false;
}
} else {
return false;
}
}
/**
* Reset the user's level to zero and clear all check failures
*/
public void resetLevel() {
level = 0;
for (CheckType type : CheckType.values()) {
type.clearUse(uuid);
}
}
/**
* Get the last known valid location of the player for use in resetting
*
* @param location default value to be returned if no known good location exists
* @return last known valid location
*/
public Location getGoodLocation(Location location) {
if (goodLocation == null) {
return location;
}
return goodLocation;
}
/**
* Set the last known valid location of the player
*
* @param location location to be set
* @return true if the location was valid and set properly
*/
public boolean setGoodLocation(Location location) {
if (Utilities.cantStandAtExp(location) || (location.getBlock().isLiquid() && !Utilities.isFullyInWater(location))) {
return false;
}
goodLocation = location;
return true;
}
/**
* Store a copy of the player's inventory, for use in resetting
*
* @param is ItemStack list to store
*/
public void setInventorySnapshot(ItemStack[] is) {
inventorySnapshot = new ArrayList<ItemStack>();
for (int i = 0; i < is.length; i++) {
if (is[i] != null) {
inventorySnapshot.add(is[i].clone());
}
}
}
/**
* Remove the current inventory snapshot
*/
public void removeInventorySnapshot() {
inventorySnapshot = null;
}
/**
* Restore the player's inventory with the current inventory snapshot
*
* @param inventory Player's inventory
*/
public void restoreInventory(Inventory inventory) {
if (inventorySnapshot != null) {
inventory.clear();
for (ItemStack is : inventorySnapshot) {
if (is != null) {
inventory.addItem(is);
}
}
}
}
/**
* Set the player's to location
*
* @param x X value
* @param y Y value
* @param z Z value
*/
public void setTo(double x, double y, double z) {
toX = (int) x;
toY = (int) y;
toZ = (int) z;
}
/**
* Check if a given to value is the same as the stored value
*
* @param x X value
* @param y Y value
* @param z Z value
* @return true if coordinates are all equal
*/
public boolean checkTo(double x, double y, double z) {
return (int) x == toX && (int) y == toY && (int) z == toZ;
}
/**
* Log a player's chat message
*
* @param message Message to log
*/
public void addMessage(String message) {
addToSpamLog(message, messages, messageTimes);
}
/**
* Log a player's command
*
* @param command Command to log
*/
public void addCommand(String command) {
addToSpamLog(command, commands, commandTimes);
}
private void addToSpamLog(String string, String[] messages, Long[] times) {
messages[1] = messages[0];
messages[0] = string;
times[1] = times[0];
times[0] = System.currentTimeMillis();
}
/**
* Get a stored chat message
*
* @param index Index of the chat in storage
* @return the message
*/
public String getMessage(int index) {
return messages[index];
}
/**
* Get a stored command
*
* @param index Index of the command in storage
* @return the command
*/
public String getCommand(int index) {
return commands[index];
}
/**
* Get the time a message in storage was sent
*
* @param index Index of the chat in storage
* @return time the message was sent
*/
public Long getMessageTime(int index) {
return messageTimes[index];
}
/**
* Get the time a command in storage was sent
*
* @param index Index of the command in storage
* @return time the command was sent
*/
public Long getCommandTime(int index) {
return commandTimes[index];
}
/**
* Clear all stored messages
*/
public void clearMessages() {
messages = new String[2];
messageTimes = new Long[2];
}
/**
* Clear all stored commands
*/
public void clearCommands() {
commands = new String[2];
commandTimes = new Long[2];
}
/**
* Get the time the very last stored message was sent
*
* @return the last message's time
*/
public Long getLastMessageTime() {
return getMessageTime(0) == null ? -1 : getMessageTime(0);
}
/**
* Get the time the very last stored command was sent
*
* @return the last command's time
*/
public Long getLastCommandTime() {
return getCommandTime(0) == null ? -1 : getCommandTime(0);
}
private List<Group> getLevels() {
return config.getGroups().getGroups();
}
private boolean silentMode() {
return config.getConfig().silentMode.getValue();
}
public void setIsWaitingOnLevelSync(boolean b) {
this.isWaitingOnLevelSync = b;
}
public boolean isWaitingOnLevelSync() {
return isWaitingOnLevelSync;
}
public void setLevelSyncTimestamp(Timestamp timestamp) {
levelSyncTimestamp = timestamp;
}
public Timestamp getLevelSyncTimestamp() {
return levelSyncTimestamp;
}
@Override
public String toString() {
return "User {name = " + getName() + ", level = " + level + "}";
}
}
@@ -0,0 +1,576 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.util;
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 com.rammelkast.anticheatreloaded.AntiCheat;
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);
}
}
}
for (String msg : message) {
AntiCheat.getManager().log(msg);
}
}
/**
* Check if only the block beneath them is standable (includes water + lava)
* @param block the block to check (under)
* @return true if they cannot stand there
*/
public static boolean cantStandAtSingle(Block block)
{
// TODO: Implement Better to reduce false positives (done? lets test...)
Block otherBlock = block.getLocation().add(0, -0.5, 0).getBlock();
boolean center = otherBlock.getType() == Material.AIR;
return center;
}
/**
* 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) {
try {
Integer.parseInt(string);
return true;
} catch (Exception ex) {
return false;
}
}
/**
* Determine whether a String can be cast to a Double
*
* @param string text to check
* @return true if double
*/
public static boolean isDouble(String string) {
try {
Double.parseDouble(string);
return true;
} catch (Exception ex) {
return false;
}
}
/**
* 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);
if (enchantlvl > 0) {
result /= enchantlvl * enchantlvl + 1L;
}
result = result > 25000 ? 25000 : result < 0 ? 0 : result;
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(final String string) {
return new ArrayList<String>() {{ add(string); }};
}
/**
* 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,53 @@
package com.rammelkast.anticheatreloaded.util;
import java.util.EnumSet;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
public class VersionUtil {
public static String getVersion() {
return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
}
private static final EnumSet<Material> MOVE_UP_BLOCKS_1_8 = EnumSet.of(Material.ACACIA_STAIRS,
Material.BIRCH_WOOD_STAIRS, Material.BRICK_STAIRS, Material.COBBLESTONE_STAIRS, Material.DARK_OAK_STAIRS,
Material.JUNGLE_WOOD_STAIRS, Material.NETHER_BRICK_STAIRS, Material.QUARTZ_STAIRS,
Material.RED_SANDSTONE_STAIRS, Material.SANDSTONE_STAIRS, Material.SMOOTH_STAIRS,
Material.SPRUCE_WOOD_STAIRS, Material.WOOD_STAIRS);
public static boolean isFlying(Player p) {
if (getVersion().equals("v1_9_R1") || getVersion().equals("v1_10_R1") || getVersion().equals("v1_11_R1")) {
return p.isFlying() || p.isGliding() || p.hasPotionEffect(NMS_1_9_PLUS.LEVITATION);
} else {
return p.isFlying();
}
}
public static EnumSet<Material> getMoveUpBlocks() {
if (getVersion().equals("v1_9_R1") || getVersion().equals("v1_10_R1") || getVersion().equals("v1_11_R1")) {
return NMS_1_9_PLUS.MOVE_UP_BLOCKS_1_9;
} else {
return MOVE_UP_BLOCKS_1_8;
}
}
public static boolean isNewYSpeed() {
if (getVersion().equals("v1_9_R1") || getVersion().equals("v1_10_R1") || getVersion().equals("v1_11_R1")) {
return true;
} else {
return false;
}
}
public static long getHealTime() {
if (getVersion().equals("v1_9_R1") || getVersion().equals("v1_10_R1") || getVersion().equals("v1_11_R1")) {
return 495;
} else {
return 1995;
}
}
}
@@ -0,0 +1,230 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.util.enterprise;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitTask;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.util.User;
import com.rammelkast.anticheatreloaded.util.Utilities;
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 boolean syncLevels;
private long syncInterval;
private Connection connection;
private PreparedStatement eventBatch;
private BukkitTask eventTask;
private BukkitTask syncTask;
public Database(DatabaseType type, String hostname, int port, String username, String password, String prefix, String schema, String serverName, String logInterval, String logLife, boolean syncLevels, String syncInterval) {
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);
this.syncLevels = syncLevels;
this.syncInterval = Utilities.lifeToSeconds(syncInterval);
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);
}
if(syncLevels && syncInterval != 0) {
syncTask = Bukkit.getScheduler().runTaskTimerAsynchronously(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
syncUsers();
}
}, syncInterval * 20, syncInterval * 20);
}
AntiCheat.getPlugin().verboseLog("Connected to the database.");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void shutdown() {
if (eventTask != null) eventTask.cancel();
if (syncTask != null) syncTask.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.getUUID().toString());
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();
}
}
});
}
}
private void syncUsers() {
for (User user : AntiCheat.getManager().getUserManager().getUsers()) {
AntiCheat.getManager().getConfiguration().getLevels().updateLevelToUser(user);
}
}
}
@@ -0,0 +1,95 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.util.rule;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.util.User;
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 com.rammelkast.anticheatreloaded.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,215 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 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 com.rammelkast.anticheatreloaded.util.rule;
import org.bukkit.GameMode;
import com.rammelkast.anticheatreloaded.AntiCheat;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.util.Group;
import com.rammelkast.anticheatreloaded.util.User;
import com.rammelkast.anticheatreloaded.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 />
* <ul>
* <li>Check
* <ul>
* <li>Contains all valid checks as listed in {@link com.rammelkast.anticheatreloaded.check.CheckType}</li>
* <li>Will return the number of times this user has failed the given check</li>
* <li><b>Example:</b> Check_SPRINT</li>
* </ul>
* </li>
* <li>Player
* <ul>
* <li>Contains NAME, the name of the player</li>
* <li>Contains LEVEL*, the player's current level</li>
* <li>Contains GROUP*, the name of the player's current hack group</li>
* <li>Contains CHECK, the check that was just failed</li>
* <li>Contains GAMEMODE*, the player's current Game Mode (Survival, Creative, Adventure)/li>
* <li>Contains WORLD, the name of the world the player is in/li>
* <li>Contains HEALTH*, the player's current health/li>
* <li>A * denotes that this value can be set, for example Player_HEALTH = 20.0/li>
* </ul>
* </li>
* </ul>
* <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 com.rammelkast.anticheatreloaded.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 com.rammelkast.anticheatreloaded.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());
map.put("player_group", user.getGroup() != null ? user.getGroup().getName().toLowerCase() : "low");
map.put("player_uuid", user.getUUID().toString());
map.put("player_gamemode", user.getPlayer().getGameMode().toString());
map.put("player_world", user.getPlayer().getWorld().getName());
map.put("player_health", user.getPlayer().getHealth());
for (CheckType t : CheckType.values()) {
map.put("check_" + t.name().toLowerCase(), t.getUses(user.getUUID()));
}
return map;
}
protected void setVariable(String variable, String value, User user) {
if (variable.equals("player_level") && Utilities.isInt(value)) {
user.setLevel(Integer.parseInt(value));
} else if (variable.equals("player_group") && Utilities.isInt(value)) {
for (Group group : AntiCheat.getManager().getConfiguration().getGroups().getGroups()) {
if (group.getName().equalsIgnoreCase(value)) {
user.setLevel(group.getLevel());
}
}
} else if (variable.equals("player_gamemode")) {
try {
GameMode mode = GameMode.valueOf(value);
user.getPlayer().setGameMode(mode);
} catch (IllegalArgumentException ex) {
}
} else if (variable.equals("player_health") && Utilities.isDouble(value)) {
user.getPlayer().setHealth(Double.parseDouble(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 + "}";
}
}