Code Refactor - Whitespace Refactor

This commit is contained in:
Xephi 2014-08-08 23:14:56 +02:00
parent ec7ac60340
commit afc1ea9111
114 changed files with 8277 additions and 7103 deletions

View File

@ -155,15 +155,18 @@ public class AuthMe extends JavaPlugin {
Class.forName("org.apache.logging.log4j.core.Filter"); Class.forName("org.apache.logging.log4j.core.Filter");
setLog4JFilter(); setLog4JFilter();
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support is disabled"); ConsoleLogger
.info("You're using Minecraft 1.6.x or older, Log4J support is disabled");
} catch (NoClassDefFoundError e) { } catch (NoClassDefFoundError e) {
ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support is disabled"); ConsoleLogger
.info("You're using Minecraft 1.6.x or older, Log4J support is disabled");
} }
} }
// Load MailApi // Load MailApi
if(!Settings.getmailAccount.isEmpty() && !Settings.getmailPassword.isEmpty()) if (!Settings.getmailAccount.isEmpty()
mail = new SendMailSSL(this); && !Settings.getmailPassword.isEmpty()) mail = new SendMailSSL(
this);
// Check Citizens Version // Check Citizens Version
citizensVersion(); citizensVersion();
@ -229,8 +232,10 @@ public class AuthMe extends JavaPlugin {
PluginManager pm = getServer().getPluginManager(); PluginManager pm = getServer().getPluginManager();
if (Settings.bungee) { if (Settings.bungee) {
Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); Bukkit.getMessenger().registerOutgoingPluginChannel(this,
Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this)); "BungeeCord");
Bukkit.getMessenger().registerIncomingPluginChannel(this,
"BungeeCord", new BungeeCordMessage(this));
} }
if (pm.isPluginEnabled("Spout")) { if (pm.isPluginEnabled("Spout")) {
pm.registerEvents(new AuthMeSpoutListener(database), this); pm.registerEvents(new AuthMeSpoutListener(database), this);
@ -248,20 +253,24 @@ public class AuthMe extends JavaPlugin {
this.getCommand("authme").setExecutor(new AdminCommand(this, database)); this.getCommand("authme").setExecutor(new AdminCommand(this, database));
this.getCommand("register").setExecutor(new RegisterCommand(this)); this.getCommand("register").setExecutor(new RegisterCommand(this));
this.getCommand("login").setExecutor(new LoginCommand(this)); this.getCommand("login").setExecutor(new LoginCommand(this));
this.getCommand("changepassword").setExecutor(new ChangePasswordCommand(database, this)); this.getCommand("changepassword").setExecutor(
this.getCommand("logout").setExecutor(new LogoutCommand(this,database)); new ChangePasswordCommand(database, this));
this.getCommand("unregister").setExecutor(new UnregisterCommand(this, database)); this.getCommand("logout")
.setExecutor(new LogoutCommand(this, database));
this.getCommand("unregister").setExecutor(
new UnregisterCommand(this, database));
this.getCommand("passpartu").setExecutor(new PasspartuCommand(this)); this.getCommand("passpartu").setExecutor(new PasspartuCommand(this));
this.getCommand("email").setExecutor(new EmailCommand(this, database)); this.getCommand("email").setExecutor(new EmailCommand(this, database));
this.getCommand("captcha").setExecutor(new CaptchaCommand(this)); this.getCommand("captcha").setExecutor(new CaptchaCommand(this));
this.getCommand("converter").setExecutor(new ConverterCommand(this, database)); this.getCommand("converter").setExecutor(
new ConverterCommand(this, database));
if (!Settings.isForceSingleSessionEnabled) { if (!Settings.isForceSingleSessionEnabled) {
ConsoleLogger.showError("ATTENTION by disabling ForceSingleSession, your server protection is set to low"); ConsoleLogger
.showError("ATTENTION by disabling ForceSingleSession, your server protection is set to low");
} }
if (Settings.reloadSupport) if (Settings.reloadSupport) try {
try {
onReload(); onReload();
if (server.getOnlinePlayers().length < 1) { if (server.getOnlinePlayers().length < 1) {
try { try {
@ -272,8 +281,7 @@ public class AuthMe extends JavaPlugin {
} catch (NullPointerException ex) { } catch (NullPointerException ex) {
} }
if (Settings.usePurge) if (Settings.usePurge) autoPurge();
autoPurge();
// Download GeoIp.dat file // Download GeoIp.dat file
downloadGeoIp(); downloadGeoIp();
@ -284,28 +292,35 @@ public class AuthMe extends JavaPlugin {
dataManager = new DataManager(this, database); dataManager = new DataManager(this, database);
dataManager.start(); dataManager.start();
ConsoleLogger.info("Authme " + this.getDescription().getVersion() + " enabled"); ConsoleLogger.info("Authme " + this.getDescription().getVersion()
+ " enabled");
} }
private void setLog4JFilter() { private void setLog4JFilter() {
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override @Override
public void run() { public void run() {
org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger(); org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) LogManager
.getRootLogger();
coreLogger.addFilter(new Log4JFilter()); coreLogger.addFilter(new Log4JFilter());
} }
}); });
} }
public void checkVault() { public void checkVault() {
if (this.getServer().getPluginManager().getPlugin("Vault") != null && this.getServer().getPluginManager().getPlugin("Vault").isEnabled()) { if (this.getServer().getPluginManager().getPlugin("Vault") != null
RegisteredServiceProvider<Permission> permissionProvider = && this.getServer().getPluginManager().getPlugin("Vault")
getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); .isEnabled()) {
RegisteredServiceProvider<Permission> permissionProvider = getServer()
.getServicesManager().getRegistration(
net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null) { if (permissionProvider != null) {
permission = permissionProvider.getProvider(); permission = permissionProvider.getProvider();
ConsoleLogger.info("Vault plugin detected, hook with " + permission.getName() + " system"); ConsoleLogger.info("Vault plugin detected, hook with "
+ permission.getName() + " system");
} else { } else {
ConsoleLogger.showError("Vault plugin is detected but not the permissions plugin!"); ConsoleLogger
.showError("Vault plugin is detected but not the permissions plugin!");
} }
} else { } else {
permission = null; permission = null;
@ -317,7 +332,9 @@ public class AuthMe extends JavaPlugin {
this.ChestShop = 0; this.ChestShop = 0;
return; return;
} }
if (this.getServer().getPluginManager().getPlugin("ChestShop") != null && this.getServer().getPluginManager().getPlugin("ChestShop").isEnabled()) { if (this.getServer().getPluginManager().getPlugin("ChestShop") != null
&& this.getServer().getPluginManager().getPlugin("ChestShop")
.isEnabled()) {
try { try {
String ver = com.Acrobot.ChestShop.ChestShop.getVersion(); String ver = com.Acrobot.ChestShop.ChestShop.getVersion();
try { try {
@ -325,7 +342,8 @@ public class AuthMe extends JavaPlugin {
if (version >= 3.50) { if (version >= 3.50) {
this.ChestShop = version; this.ChestShop = version;
} else { } else {
ConsoleLogger.showError("Please Update your ChestShop version!"); ConsoleLogger
.showError("Please Update your ChestShop version!");
} }
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
try { try {
@ -333,12 +351,14 @@ public class AuthMe extends JavaPlugin {
if (version >= 3.50) { if (version >= 3.50) {
this.ChestShop = version; this.ChestShop = version;
} else { } else {
ConsoleLogger.showError("Please Update your ChestShop version!"); ConsoleLogger
.showError("Please Update your ChestShop version!");
} }
} catch (NumberFormatException nfee) { } catch (NumberFormatException nfee) {
} }
} }
} catch (Exception e) {} } catch (Exception e) {
}
} else { } else {
this.ChestShop = 0; this.ChestShop = 0;
} }
@ -349,10 +369,14 @@ public class AuthMe extends JavaPlugin {
multiverse = null; multiverse = null;
return; return;
} }
if (this.getServer().getPluginManager().getPlugin("Multiverse-Core") != null && this.getServer().getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { if (this.getServer().getPluginManager().getPlugin("Multiverse-Core") != null
&& this.getServer().getPluginManager()
.getPlugin("Multiverse-Core").isEnabled()) {
try { try {
multiverse = (MultiverseCore) this.getServer().getPluginManager().getPlugin("Multiverse-Core"); multiverse = (MultiverseCore) this.getServer()
ConsoleLogger.info("Hook with Multiverse-Core for SpawnLocations"); .getPluginManager().getPlugin("Multiverse-Core");
ConsoleLogger
.info("Hook with Multiverse-Core for SpawnLocations");
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
multiverse = null; multiverse = null;
} catch (ClassCastException cce) { } catch (ClassCastException cce) {
@ -366,9 +390,12 @@ public class AuthMe extends JavaPlugin {
} }
public void checkEssentials() { public void checkEssentials() {
if (this.getServer().getPluginManager().getPlugin("Essentials") != null && this.getServer().getPluginManager().getPlugin("Essentials").isEnabled()) { if (this.getServer().getPluginManager().getPlugin("Essentials") != null
&& this.getServer().getPluginManager().getPlugin("Essentials")
.isEnabled()) {
try { try {
ess = (Essentials) this.getServer().getPluginManager().getPlugin("Essentials"); ess = (Essentials) this.getServer().getPluginManager()
.getPlugin("Essentials");
ConsoleLogger.info("Hook with Essentials plugin"); ConsoleLogger.info("Hook with Essentials plugin");
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
ess = null; ess = null;
@ -380,13 +407,16 @@ public class AuthMe extends JavaPlugin {
} else { } else {
ess = null; ess = null;
} }
if (this.getServer().getPluginManager().getPlugin("EssentialsSpawn") != null && this.getServer().getPluginManager().getPlugin("EssentialsSpawn").isEnabled()) { if (this.getServer().getPluginManager().getPlugin("EssentialsSpawn") != null
&& this.getServer().getPluginManager()
.getPlugin("EssentialsSpawn").isEnabled()) {
try { try {
essentialsSpawn = new EssSpawn().getLocation(); essentialsSpawn = new EssSpawn().getLocation();
ConsoleLogger.info("Hook with EssentialsSpawn plugin"); ConsoleLogger.info("Hook with EssentialsSpawn plugin");
} catch (Exception e) { } catch (Exception e) {
essentialsSpawn = null; essentialsSpawn = null;
ConsoleLogger.showError("Error while reading /plugins/Essentials/spawn.yml file "); ConsoleLogger
.showError("Error while reading /plugins/Essentials/spawn.yml file ");
} }
} else { } else {
ess = null; ess = null;
@ -398,8 +428,11 @@ public class AuthMe extends JavaPlugin {
this.notifications = null; this.notifications = null;
return; return;
} }
if (this.getServer().getPluginManager().getPlugin("Notifications") != null && this.getServer().getPluginManager().getPlugin("Notifications").isEnabled()) { if (this.getServer().getPluginManager().getPlugin("Notifications") != null
this.notifications = (Notifications) this.getServer().getPluginManager().getPlugin("Notifications"); && this.getServer().getPluginManager()
.getPlugin("Notifications").isEnabled()) {
this.notifications = (Notifications) this.getServer()
.getPluginManager().getPlugin("Notifications");
ConsoleLogger.info("Successfully hook with Notifications"); ConsoleLogger.info("Successfully hook with Notifications");
} else { } else {
this.notifications = null; this.notifications = null;
@ -407,7 +440,9 @@ public class AuthMe extends JavaPlugin {
} }
public void combatTag() { public void combatTag() {
if (this.getServer().getPluginManager().getPlugin("CombatTag") != null && this.getServer().getPluginManager().getPlugin("CombatTag").isEnabled()) { if (this.getServer().getPluginManager().getPlugin("CombatTag") != null
&& this.getServer().getPluginManager().getPlugin("CombatTag")
.isEnabled()) {
this.CombatTag = 1; this.CombatTag = 1;
} else { } else {
this.CombatTag = 0; this.CombatTag = 0;
@ -415,8 +450,11 @@ public class AuthMe extends JavaPlugin {
} }
public void citizensVersion() { public void citizensVersion() {
if (this.getServer().getPluginManager().getPlugin("Citizens") != null && this.getServer().getPluginManager().getPlugin("Citizens").isEnabled()) { if (this.getServer().getPluginManager().getPlugin("Citizens") != null
Citizens cit = (Citizens) this.getServer().getPluginManager().getPlugin("Citizens"); && this.getServer().getPluginManager().getPlugin("Citizens")
.isEnabled()) {
Citizens cit = (Citizens) this.getServer().getPluginManager()
.getPlugin("Citizens");
String ver = cit.getDescription().getVersion(); String ver = cit.getDescription().getVersion();
String[] args = ver.split("\\."); String[] args = ver.split("\\.");
if (args[0].contains("1")) { if (args[0].contains("1")) {
@ -431,8 +469,8 @@ public class AuthMe extends JavaPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
if (Bukkit.getOnlinePlayers().length != 0) if (Bukkit.getOnlinePlayers().length != 0) for (Player player : Bukkit
for(Player player : Bukkit.getOnlinePlayers()) { .getOnlinePlayers()) {
this.savePlayer(player); this.savePlayer(player);
} }
@ -441,13 +479,11 @@ public class AuthMe extends JavaPlugin {
} }
if (databaseThread != null) { if (databaseThread != null) {
if (databaseThread.isAlive()) if (databaseThread.isAlive()) databaseThread.interrupt();
databaseThread.interrupt();
} }
if (dataManager != null) { if (dataManager != null) {
if (dataManager.isAlive()) if (dataManager.isAlive()) dataManager.interrupt();
dataManager.interrupt();
} }
if (Settings.isBackupActivated && Settings.isBackupOnStop) { if (Settings.isBackupActivated && Settings.isBackupOnStop) {
@ -455,7 +491,8 @@ public class AuthMe extends JavaPlugin {
if (Backup) ConsoleLogger.info("Backup Complete"); if (Backup) ConsoleLogger.info("Backup Complete");
else ConsoleLogger.showError("Error while making Backup"); else ConsoleLogger.showError("Error while making Backup");
} }
ConsoleLogger.info("Authme " + this.getDescription().getVersion() + " disabled"); ConsoleLogger.info("Authme " + this.getDescription().getVersion()
+ " disabled");
} }
private void onReload() { private void onReload() {
@ -465,9 +502,10 @@ public class AuthMe extends JavaPlugin {
if (database.isLogged(player.getName().toLowerCase())) { if (database.isLogged(player.getName().toLowerCase())) {
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
PlayerAuth pAuth = database.getAuth(name); PlayerAuth pAuth = database.getAuth(name);
if(pAuth == null) if (pAuth == null) break;
break; PlayerAuth auth = new PlayerAuth(name, pAuth.getHash(),
PlayerAuth auth = new PlayerAuth(name, pAuth.getHash(), pAuth.getIp(), new Date().getTime(), pAuth.getEmail(), player.getName()); pAuth.getIp(), new Date().getTime(),
pAuth.getEmail(), player.getName());
database.updateSession(auth); database.updateSession(auth);
PlayerCache.getInstance().addPlayer(auth); PlayerCache.getInstance().addPlayer(auth);
} }
@ -483,30 +521,38 @@ public class AuthMe extends JavaPlugin {
return authme; return authme;
} }
public void savePlayer(Player player) throws IllegalStateException, NullPointerException { public void savePlayer(Player player) throws IllegalStateException,
NullPointerException {
try { try {
if ((citizens.isNPC(player, this)) || (Utils.getInstance().isUnrestricted(player)) || (CombatTagComunicator.isNPC(player))) { if ((citizens.isNPC(player, this))
|| (Utils.getInstance().isUnrestricted(player))
|| (CombatTagComunicator.isNPC(player))) {
return; return;
} }
} catch (Exception e) { } } catch (Exception e) {
}
try { try {
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead() && Settings.isSaveQuitLocationEnabled) { if (PlayerCache.getInstance().isAuthenticated(name)
final PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), player.getWorld().getName()); && !player.isDead() && Settings.isSaveQuitLocationEnabled) {
final PlayerAuth auth = new PlayerAuth(player.getName()
.toLowerCase(), player.getLocation().getX(), player
.getLocation().getY(), player.getLocation().getZ(),
player.getWorld().getName());
database.updateQuitLoc(auth); database.updateQuitLoc(auth);
} }
if (LimboCache.getInstance().hasLimboPlayer(name)) if (LimboCache.getInstance().hasLimboPlayer(name)) {
{ LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); name);
if (Settings.protectInventoryBeforeLogInEnabled.booleanValue()) { if (Settings.protectInventoryBeforeLogInEnabled.booleanValue()) {
player.getInventory().setArmorContents(limbo.getArmour()); player.getInventory().setArmorContents(limbo.getArmour());
player.getInventory().setContents(limbo.getInventory()); player.getInventory().setContents(limbo.getInventory());
} }
if (!Settings.noTeleport) if (!Settings.noTeleport) player.teleport(limbo.getLoc());
player.teleport(limbo.getLoc());
this.utils.addNormal(player, limbo.getGroup()); this.utils.addNormal(player, limbo.getGroup());
player.setOp(limbo.getOperator()); player.setOp(limbo.getOperator());
this.plugin.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId()); this.plugin.getServer().getScheduler()
.cancelTask(limbo.getTimeoutTaskId());
LimboCache.getInstance().deleteLimboPlayer(name); LimboCache.getInstance().deleteLimboPlayer(name);
if (this.playerBackup.doesCacheExist(name)) { if (this.playerBackup.doesCacheExist(name)) {
this.playerBackup.removeCache(name); this.playerBackup.removeCache(name);
@ -554,8 +600,7 @@ public class AuthMe extends JavaPlugin {
} }
public boolean authmePermissible(Player player, String perm) { public boolean authmePermissible(Player player, String perm) {
if (player.hasPermission(perm)) if (player.hasPermission(perm)) return true;
return true;
else if (permission != null) { else if (permission != null) {
return permission.playerHas(player, perm); return permission.playerHas(player, perm);
} }
@ -578,24 +623,23 @@ public class AuthMe extends JavaPlugin {
calendar.add(Calendar.DATE, -(Settings.purgeDelay)); calendar.add(Calendar.DATE, -(Settings.purgeDelay));
long until = calendar.getTimeInMillis(); long until = calendar.getTimeInMillis();
List<String> cleared = this.database.autoPurgeDatabase(until); List<String> cleared = this.database.autoPurgeDatabase(until);
ConsoleLogger.info("AutoPurgeDatabase : " + cleared.size() + " accounts removed."); ConsoleLogger.info("AutoPurgeDatabase : " + cleared.size()
if (cleared.isEmpty()) + " accounts removed.");
return; if (cleared.isEmpty()) return;
if (Settings.purgeEssentialsFile && this.ess != null) if (Settings.purgeEssentialsFile && this.ess != null) dataManager
dataManager.purgeEssentials(cleared); .purgeEssentials(cleared);
if (Settings.purgePlayerDat) if (Settings.purgePlayerDat) dataManager.purgeDat(cleared);
dataManager.purgeDat(cleared); if (Settings.purgeLimitedCreative) dataManager
if (Settings.purgeLimitedCreative) .purgeLimitedCreative(cleared);
dataManager.purgeLimitedCreative(cleared); if (Settings.purgeAntiXray) dataManager.purgeAntiXray(cleared);
if (Settings.purgeAntiXray)
dataManager.purgeAntiXray(cleared);
} }
public Location getSpawnLocation(Player player) { public Location getSpawnLocation(Player player) {
World world = player.getWorld(); World world = player.getWorld();
String[] spawnPriority = Settings.spawnPriority.split(","); String[] spawnPriority = Settings.spawnPriority.split(",");
if (spawnPriority.length < 4) { if (spawnPriority.length < 4) {
ConsoleLogger.showError("Check your config for spawnPriority, you need to put all of 4 spawn priorities"); ConsoleLogger
.showError("Check your config for spawnPriority, you need to put all of 4 spawn priorities");
ConsoleLogger.showError("Defaulting Spawn to world's one"); ConsoleLogger.showError("Defaulting Spawn to world's one");
return world.getSpawnLocation(); return world.getSpawnLocation();
} }
@ -603,17 +647,14 @@ public class AuthMe extends JavaPlugin {
int i = 3; int i = 3;
for (i = 3; i >= 0; i--) { for (i = 3; i >= 0; i--) {
String s = spawnPriority[i]; String s = spawnPriority[i];
if (s.equalsIgnoreCase("default") && getDefaultSpawn(world) != null) if (s.equalsIgnoreCase("default") && getDefaultSpawn(world) != null) spawnLoc = getDefaultSpawn(world);
spawnLoc = getDefaultSpawn(world); if (s.equalsIgnoreCase("multiverse")
if (s.equalsIgnoreCase("multiverse") && getMultiverseSpawn(world) != null) && getMultiverseSpawn(world) != null) spawnLoc = getMultiverseSpawn(world);
spawnLoc = getMultiverseSpawn(world); if (s.equalsIgnoreCase("essentials")
if (s.equalsIgnoreCase("essentials") && getEssentialsSpawn() != null) && getEssentialsSpawn() != null) spawnLoc = getEssentialsSpawn();
spawnLoc = getEssentialsSpawn(); if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null) spawnLoc = getAuthMeSpawn(player);
if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null)
spawnLoc = getAuthMeSpawn(player);
} }
if (spawnLoc == null) if (spawnLoc == null) spawnLoc = world.getSpawnLocation();
spawnLoc = world.getSpawnLocation();
return spawnLoc; return spawnLoc;
} }
@ -624,7 +665,8 @@ public class AuthMe extends JavaPlugin {
private Location getMultiverseSpawn(World world) { private Location getMultiverseSpawn(World world) {
if (multiverse != null && Settings.multiverse) { if (multiverse != null && Settings.multiverse) {
try { try {
return multiverse.getMVWorldManager().getMVWorld(world).getSpawnLocation(); return multiverse.getMVWorldManager().getMVWorld(world)
.getSpawnLocation();
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
} catch (ClassCastException cce) { } catch (ClassCastException cce) {
} catch (NoClassDefFoundError ncdfe) { } catch (NoClassDefFoundError ncdfe) {
@ -634,21 +676,23 @@ public class AuthMe extends JavaPlugin {
} }
private Location getEssentialsSpawn() { private Location getEssentialsSpawn() {
if (essentialsSpawn != null) if (essentialsSpawn != null) return essentialsSpawn;
return essentialsSpawn;
return null; return null;
} }
private Location getAuthMeSpawn(Player player) { private Location getAuthMeSpawn(Player player) {
if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) && (Spawn.getInstance().getFirstSpawn() != null)) if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player
return Spawn.getInstance().getFirstSpawn(); .hasPlayedBefore())
if (Spawn.getInstance().getSpawn() != null) && (Spawn.getInstance().getFirstSpawn() != null)) return Spawn
return Spawn.getInstance().getSpawn(); .getInstance().getFirstSpawn();
if (Spawn.getInstance().getSpawn() != null) return Spawn.getInstance()
.getSpawn();
return null; return null;
} }
public void downloadGeoIp() { public void downloadGeoIp() {
ConsoleLogger.info("LICENSE : This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com"); ConsoleLogger
.info("LICENSE : This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com");
File file = new File(getDataFolder(), "GeoIP.dat"); File file = new File(getDataFolder(), "GeoIP.dat");
if (!file.exists()) { if (!file.exists()) {
try { try {
@ -658,8 +702,7 @@ public class AuthMe extends JavaPlugin {
conn.setConnectTimeout(10000); conn.setConnectTimeout(10000);
conn.connect(); conn.connect();
InputStream input = conn.getInputStream(); InputStream input = conn.getInputStream();
if (url.endsWith(".gz")) if (url.endsWith(".gz")) input = new GZIPInputStream(input);
input = new GZIPInputStream(input);
OutputStream output = new FileOutputStream(file); OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[2048]; byte[] buffer = new byte[2048];
int length = input.read(buffer); int length = input.read(buffer);
@ -669,29 +712,30 @@ public class AuthMe extends JavaPlugin {
} }
output.close(); output.close();
input.close(); input.close();
} catch (Exception e) {} } catch (Exception e) {
}
} }
} }
public String getCountryCode(String ip) { public String getCountryCode(String ip) {
try { try {
if (ls == null) if (ls == null) ls = new LookupService(new File(getDataFolder(),
ls = new LookupService(new File(getDataFolder(), "GeoIP.dat")); "GeoIP.dat"));
String code = ls.getCountry(ip).getCode(); String code = ls.getCountry(ip).getCode();
if (code != null && !code.isEmpty()) if (code != null && !code.isEmpty()) return code;
return code; } catch (Exception e) {
} catch (Exception e) {} }
return null; return null;
} }
public String getCountryName(String ip) { public String getCountryName(String ip) {
try { try {
if (ls == null) if (ls == null) ls = new LookupService(new File(getDataFolder(),
ls = new LookupService(new File(getDataFolder(), "GeoIP.dat")); "GeoIP.dat"));
String code = ls.getCountry(ip).getName(); String code = ls.getCountry(ip).getName();
if (code != null && !code.isEmpty()) if (code != null && !code.isEmpty()) return code;
return code; } catch (Exception e) {
} catch (Exception e) {} }
return null; return null;
} }
@ -701,19 +745,19 @@ public class AuthMe extends JavaPlugin {
} }
private void recallEmail() { private void recallEmail() {
if (!Settings.recallEmail) if (!Settings.recallEmail) return;
return;
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override @Override
public void run() { public void run() {
for (Player player : Bukkit.getOnlinePlayers()) { for (Player player : Bukkit.getOnlinePlayers()) {
if (player.isOnline()) { if (player.isOnline()) {
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (database.isAuthAvailable(name)) if (database.isAuthAvailable(name)) if (PlayerCache
if (PlayerCache.getInstance().isAuthenticated(name)) { .getInstance().isAuthenticated(name)) {
String email = database.getAuth(name).getEmail(); String email = database.getAuth(name).getEmail();
if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com")) if (email == null || email.isEmpty()
m._(player, "add_email"); || email.equalsIgnoreCase("your@email.com")) m
._(player, "add_email");
} }
} }
} }
@ -725,15 +769,22 @@ public class AuthMe extends JavaPlugin {
try { try {
message = message.replace("&", "\u00a7"); message = message.replace("&", "\u00a7");
message = message.replace("{PLAYER}", player.getName()); message = message.replace("{PLAYER}", player.getName());
message = message.replace("{ONLINE}", ""+this.getServer().getOnlinePlayers().length); message = message.replace("{ONLINE}", ""
message = message.replace("{MAXPLAYERS}", ""+this.getServer().getMaxPlayers()); + this.getServer().getOnlinePlayers().length);
message = message.replace("{MAXPLAYERS}", ""
+ this.getServer().getMaxPlayers());
message = message.replace("{IP}", getIP(player)); message = message.replace("{IP}", getIP(player));
message = message.replace("{LOGINS}", ""+PlayerCache.getInstance().getLogged()); message = message.replace("{LOGINS}", ""
+ PlayerCache.getInstance().getLogged());
message = message.replace("{WORLD}", player.getWorld().getName()); message = message.replace("{WORLD}", player.getWorld().getName());
message = message.replace("{SERVER}", this.getServer().getServerName()); message = message.replace("{SERVER}", this.getServer()
message = message.replace("{VERSION}", this.getServer().getBukkitVersion()); .getServerName());
message = message.replace("{COUNTRY}", this.getCountryName(getIP(player))); message = message.replace("{VERSION}", this.getServer()
} catch (Exception e) {} .getBukkitVersion());
message = message.replace("{COUNTRY}",
this.getCountryName(getIP(player)));
} catch (Exception e) {
}
return message; return message;
} }
@ -741,51 +792,53 @@ public class AuthMe extends JavaPlugin {
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
String ip = player.getAddress().getAddress().getHostAddress(); String ip = player.getAddress().getAddress().getHostAddress();
if (Settings.bungee) { if (Settings.bungee) {
if (realIp.containsKey(name)) if (realIp.containsKey(name)) ip = realIp.get(name);
ip = realIp.get(name);
} }
if (Settings.checkVeryGames) if (Settings.checkVeryGames) if (getVeryGamesIP(player) != null) ip = getVeryGamesIP(player);
if (getVeryGamesIP(player) != null)
ip = getVeryGamesIP(player);
return ip; return ip;
} }
public boolean isLoggedIp(String name, String ip) { public boolean isLoggedIp(String name, String ip) {
int count = 0; int count = 0;
for (Player player : this.getServer().getOnlinePlayers()) { for (Player player : this.getServer().getOnlinePlayers()) {
if(ip.equalsIgnoreCase(getIP(player)) && database.isLogged(player.getName().toLowerCase()) && !player.getName().equalsIgnoreCase(name)) if (ip.equalsIgnoreCase(getIP(player))
count++; && database.isLogged(player.getName().toLowerCase())
&& !player.getName().equalsIgnoreCase(name)) count++;
} }
if (count >= Settings.getMaxLoginPerIp) if (count >= Settings.getMaxLoginPerIp) return true;
return true;
return false; return false;
} }
public boolean hasJoinedIp(String name, String ip) { public boolean hasJoinedIp(String name, String ip) {
int count = 0; int count = 0;
for (Player player : this.getServer().getOnlinePlayers()) { for (Player player : this.getServer().getOnlinePlayers()) {
if(ip.equalsIgnoreCase(getIP(player)) && !player.getName().equalsIgnoreCase(name)) if (ip.equalsIgnoreCase(getIP(player))
count++; && !player.getName().equalsIgnoreCase(name)) count++;
} }
if (count >= Settings.getMaxJoinPerIp) if (count >= Settings.getMaxJoinPerIp) return true;
return true;
return false; return false;
} }
/** /**
* Get Player real IP through VeryGames method * Get Player real IP through VeryGames method
* @param Player player *
* @param Player
* player
*/ */
public String getVeryGamesIP(Player player) { public String getVeryGamesIP(Player player) {
String realIP = null; String realIP = null;
String sUrl = vgUrl; String sUrl = vgUrl;
sUrl = sUrl.replace("%IP%", player.getAddress().getAddress().getHostAddress()).replace("%PORT%", ""+player.getAddress().getPort()); sUrl = sUrl.replace("%IP%",
player.getAddress().getAddress().getHostAddress()).replace(
"%PORT%", "" + player.getAddress().getPort());
try { try {
URL url = new URL(sUrl); URL url = new URL(sUrl);
URLConnection urlc = url.openConnection(); URLConnection urlc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(
urlc.getInputStream()));
String inputLine = in.readLine(); String inputLine = in.readLine();
if (inputLine != null && !inputLine.isEmpty() && !inputLine.equalsIgnoreCase("error")) { if (inputLine != null && !inputLine.isEmpty()
&& !inputLine.equalsIgnoreCase("error")) {
realIP = inputLine; realIP = inputLine;
} }
} catch (Exception e) { } catch (Exception e) {

View File

@ -9,7 +9,8 @@ import java.util.logging.LogRecord;
*/ */
public class ConsoleFilter implements Filter { public class ConsoleFilter implements Filter {
public ConsoleFilter() {} public ConsoleFilter() {
}
@Override @Override
public boolean isLoggable(LogRecord record) { public boolean isLoggable(LogRecord record) {
@ -17,8 +18,15 @@ public class ConsoleFilter implements Filter {
if (record == null || record.getMessage() == null) return true; if (record == null || record.getMessage() == null) return true;
String logM = record.getMessage().toLowerCase(); String logM = record.getMessage().toLowerCase();
if (!logM.contains("issued server command:")) return true; if (!logM.contains("issued server command:")) return true;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") if (!logM.contains("/login ") && !logM.contains("/l ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ")&& !logM.contains("/authme reg ")&& !logM.contains("/authme cp ") && !logM.contains("/register ")) return true; && !logM.contains("/reg ")
&& !logM.contains("/changepassword ")
&& !logM.contains("/unregister ")
&& !logM.contains("/authme register ")
&& !logM.contains("/authme changepassword ")
&& !logM.contains("/authme reg ")
&& !logM.contains("/authme cp ")
&& !logM.contains("/register ")) return true;
String playername = record.getMessage().split(" ")[0]; String playername = record.getMessage().split(" ")[0];
record.setMessage(playername + " issued an AuthMe command!"); record.setMessage(playername + " issued an AuthMe command!");
return true; return true;

View File

@ -12,7 +12,6 @@ import org.bukkit.Bukkit;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class ConsoleLogger { public class ConsoleLogger {
private static final Logger log = Logger.getLogger("AuthMe"); private static final Logger log = Logger.getLogger("AuthMe");
@ -22,8 +21,13 @@ public class ConsoleLogger {
log.info("[AuthMe] " + message); log.info("[AuthMe] " + message);
if (Settings.useLogging) { if (Settings.useLogging) {
Calendar date = Calendar.getInstance(); Calendar date = Calendar.getInstance();
final String actually = "[" + DateFormat.getDateInstance().format(date.getTime()) + ", " + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND) + "] " + message; final String actually = "["
Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() { + DateFormat.getDateInstance().format(date.getTime())
+ ", " + date.get(Calendar.HOUR_OF_DAY) + ":"
+ date.get(Calendar.MINUTE) + ":"
+ date.get(Calendar.SECOND) + "] " + message;
Bukkit.getScheduler().runTaskAsynchronously(
AuthMe.getInstance(), new Runnable() {
@Override @Override
public void run() { public void run() {
writeLog(actually); writeLog(actually);
@ -38,8 +42,13 @@ public class ConsoleLogger {
log.warning("[AuthMe] ERROR: " + message); log.warning("[AuthMe] ERROR: " + message);
if (Settings.useLogging) { if (Settings.useLogging) {
Calendar date = Calendar.getInstance(); Calendar date = Calendar.getInstance();
final String actually = "[" + DateFormat.getDateInstance().format(date.getTime()) + ", " + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND) + "] ERROR : " + message; final String actually = "["
Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() { + DateFormat.getDateInstance().format(date.getTime())
+ ", " + date.get(Calendar.HOUR_OF_DAY) + ":"
+ date.get(Calendar.MINUTE) + ":"
+ date.get(Calendar.SECOND) + "] ERROR : " + message;
Bukkit.getScheduler().runTaskAsynchronously(
AuthMe.getInstance(), new Runnable() {
@Override @Override
public void run() { public void run() {
writeLog(actually); writeLog(actually);
@ -51,7 +60,8 @@ public class ConsoleLogger {
public static void writeLog(String string) { public static void writeLog(String string) {
try { try {
FileWriter fw = new FileWriter(AuthMe.getInstance().getDataFolder() + File.separator + "authme.log", true); FileWriter fw = new FileWriter(AuthMe.getInstance().getDataFolder()
+ File.separator + "authme.log", true);
BufferedWriter w = new BufferedWriter(fw); BufferedWriter w = new BufferedWriter(fw);
w.write(string); w.write(string);
w.newLine(); w.newLine();

View File

@ -19,12 +19,15 @@ public class DataManager extends Thread {
this.database = database; this.database = database;
} }
public void run() {} public void run() {
}
public OfflinePlayer getOfflinePlayer(String name) { public OfflinePlayer getOfflinePlayer(String name) {
OfflinePlayer result = null; OfflinePlayer result = null;
try { try {
if (org.bukkit.Bukkit.class.getMethod("getOfflinePlayer", new Class[]{String.class}).isAnnotationPresent(Deprecated.class)) { if (org.bukkit.Bukkit.class.getMethod("getOfflinePlayer",
new Class[] { String.class }).isAnnotationPresent(
Deprecated.class)) {
for (OfflinePlayer op : Bukkit.getOfflinePlayers()) for (OfflinePlayer op : Bukkit.getOfflinePlayers())
if (op.getName().equalsIgnoreCase(name)) { if (op.getName().equalsIgnoreCase(name)) {
result = op; result = op;
@ -45,13 +48,16 @@ public class DataManager extends Thread {
org.bukkit.OfflinePlayer player = getOfflinePlayer(name); org.bukkit.OfflinePlayer player = getOfflinePlayer(name);
if (player == null) continue; if (player == null) continue;
String playerName = player.getName(); String playerName = player.getName();
File playerFile = new File("." + File.separator + "plugins" + File.separator + "AntiXRayData" + File.separator + "PlayerData" + File.separator + playerName); File playerFile = new File("." + File.separator + "plugins"
+ File.separator + "AntiXRayData" + File.separator
+ "PlayerData" + File.separator + playerName);
if (playerFile.exists()) { if (playerFile.exists()) {
playerFile.delete(); playerFile.delete();
i++; i++;
} }
} }
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " AntiXRayData Files"); ConsoleLogger.info("AutoPurgeDatabase : Remove " + i
+ " AntiXRayData Files");
} }
public void purgeLimitedCreative(List<String> cleared) { public void purgeLimitedCreative(List<String> cleared) {
@ -60,23 +66,32 @@ public class DataManager extends Thread {
org.bukkit.OfflinePlayer player = getOfflinePlayer(name); org.bukkit.OfflinePlayer player = getOfflinePlayer(name);
if (player == null) continue; if (player == null) continue;
String playerName = player.getName(); String playerName = player.getName();
File playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + ".yml"); File playerFile = new File("." + File.separator + "plugins"
+ File.separator + "LimitedCreative" + File.separator
+ "inventories" + File.separator + playerName + ".yml");
if (playerFile.exists()) { if (playerFile.exists()) {
playerFile.delete(); playerFile.delete();
i++; i++;
} }
playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + "_creative.yml"); playerFile = new File("." + File.separator + "plugins"
+ File.separator + "LimitedCreative" + File.separator
+ "inventories" + File.separator + playerName
+ "_creative.yml");
if (playerFile.exists()) { if (playerFile.exists()) {
playerFile.delete(); playerFile.delete();
i++; i++;
} }
playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + "_adventure.yml"); playerFile = new File("." + File.separator + "plugins"
+ File.separator + "LimitedCreative" + File.separator
+ "inventories" + File.separator + playerName
+ "_adventure.yml");
if (playerFile.exists()) { if (playerFile.exists()) {
playerFile.delete(); playerFile.delete();
i++; i++;
} }
} }
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " LimitedCreative Survival, Creative and Adventure files"); ConsoleLogger.info("AutoPurgeDatabase : Remove " + i
+ " LimitedCreative Survival, Creative and Adventure files");
} }
public void purgeDat(List<String> cleared) { public void purgeDat(List<String> cleared) {
@ -85,7 +100,9 @@ public class DataManager extends Thread {
org.bukkit.OfflinePlayer player = getOfflinePlayer(name); org.bukkit.OfflinePlayer player = getOfflinePlayer(name);
if (player == null) continue; if (player == null) continue;
String playerName = player.getName(); String playerName = player.getName();
File playerFile = new File (plugin.getServer().getWorldContainer() + File.separator + Settings.defaultWorld + File.separator + "players" + File.separator + playerName + ".dat"); File playerFile = new File(plugin.getServer().getWorldContainer()
+ File.separator + Settings.defaultWorld + File.separator
+ "players" + File.separator + playerName + ".dat");
if (playerFile.exists()) { if (playerFile.exists()) {
playerFile.delete(); playerFile.delete();
i++; i++;
@ -97,12 +114,15 @@ public class DataManager extends Thread {
public void purgeEssentials(List<String> cleared) { public void purgeEssentials(List<String> cleared) {
int i = 0; int i = 0;
for (String name : cleared) { for (String name : cleared) {
File playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml"); File playerFile = new File(plugin.ess.getDataFolder()
+ File.separator + "userdata" + File.separator + name
+ ".yml");
if (playerFile.exists()) { if (playerFile.exists()) {
playerFile.delete(); playerFile.delete();
i++; i++;
} }
} }
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " EssentialsFiles"); ConsoleLogger.info("AutoPurgeDatabase : Remove " + i
+ " EssentialsFiles");
} }
} }

View File

@ -12,16 +12,25 @@ import org.apache.logging.log4j.message.Message;
*/ */
public class Log4JFilter implements org.apache.logging.log4j.core.Filter { public class Log4JFilter implements org.apache.logging.log4j.core.Filter {
public Log4JFilter() {} public Log4JFilter() {
}
@Override @Override
public Result filter(LogEvent record) { public Result filter(LogEvent record) {
try { try {
if (record == null || record.getMessage() == null) return Result.NEUTRAL; if (record == null || record.getMessage() == null) return Result.NEUTRAL;
String logM = record.getMessage().getFormattedMessage().toLowerCase(); String logM = record.getMessage().getFormattedMessage()
.toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL; if (!logM.contains("issued server command:")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") if (!logM.contains("/login ") && !logM.contains("/l ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ")&& !logM.contains("/authme reg ")&& !logM.contains("/authme cp ") && !logM.contains("/register ")) return Result.NEUTRAL; && !logM.contains("/reg ")
&& !logM.contains("/changepassword ")
&& !logM.contains("/unregister ")
&& !logM.contains("/authme register ")
&& !logM.contains("/authme changepassword ")
&& !logM.contains("/authme reg ")
&& !logM.contains("/authme cp ")
&& !logM.contains("/register ")) return Result.NEUTRAL;
return Result.DENY; return Result.DENY;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return Result.NEUTRAL; return Result.NEUTRAL;
@ -35,8 +44,15 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter {
if (message == null) return Result.NEUTRAL; if (message == null) return Result.NEUTRAL;
String logM = message.toLowerCase(); String logM = message.toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL; if (!logM.contains("issued server command:")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") if (!logM.contains("/login ") && !logM.contains("/l ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ")&& !logM.contains("/authme reg ")&& !logM.contains("/authme cp ") && !logM.contains("/register ")) return Result.NEUTRAL; && !logM.contains("/reg ")
&& !logM.contains("/changepassword ")
&& !logM.contains("/unregister ")
&& !logM.contains("/authme register ")
&& !logM.contains("/authme changepassword ")
&& !logM.contains("/authme reg ")
&& !logM.contains("/authme cp ")
&& !logM.contains("/register ")) return Result.NEUTRAL;
return Result.DENY; return Result.DENY;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return Result.NEUTRAL; return Result.NEUTRAL;
@ -50,8 +66,15 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter {
if (message == null) return Result.NEUTRAL; if (message == null) return Result.NEUTRAL;
String logM = message.toString().toLowerCase(); String logM = message.toString().toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL; if (!logM.contains("issued server command:")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") if (!logM.contains("/login ") && !logM.contains("/l ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ")&& !logM.contains("/authme reg ")&& !logM.contains("/authme cp ") && !logM.contains("/register ")) return Result.NEUTRAL; && !logM.contains("/reg ")
&& !logM.contains("/changepassword ")
&& !logM.contains("/unregister ")
&& !logM.contains("/authme register ")
&& !logM.contains("/authme changepassword ")
&& !logM.contains("/authme reg ")
&& !logM.contains("/authme cp ")
&& !logM.contains("/register ")) return Result.NEUTRAL;
return Result.DENY; return Result.DENY;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return Result.NEUTRAL; return Result.NEUTRAL;
@ -65,8 +88,15 @@ public class Log4JFilter implements org.apache.logging.log4j.core.Filter {
if (message == null) return Result.NEUTRAL; if (message == null) return Result.NEUTRAL;
String logM = message.getFormattedMessage().toLowerCase(); String logM = message.getFormattedMessage().toLowerCase();
if (!logM.contains("issued server command:")) return Result.NEUTRAL; if (!logM.contains("issued server command:")) return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") if (!logM.contains("/login ") && !logM.contains("/l ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ")&& !logM.contains("/authme reg ")&& !logM.contains("/authme cp ") && !logM.contains("/register ")) return Result.NEUTRAL; && !logM.contains("/reg ")
&& !logM.contains("/changepassword ")
&& !logM.contains("/unregister ")
&& !logM.contains("/authme register ")
&& !logM.contains("/authme changepassword ")
&& !logM.contains("/authme reg ")
&& !logM.contains("/authme cp ")
&& !logM.contains("/register ")) return Result.NEUTRAL;
return Result.DENY; return Result.DENY;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return Result.NEUTRAL; return Result.NEUTRAL;

View File

@ -23,7 +23,8 @@ public class PerformBackup {
private String tblname = Settings.getMySQLTablename; private String tblname = Settings.getMySQLTablename;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
String dateString = format.format(new Date()); String dateString = format.format(new Date());
private String path = AuthMe.getInstance().getDataFolder()+"/backups/backup"+dateString; private String path = AuthMe.getInstance().getDataFolder()
+ "/backups/backup" + dateString;
private AuthMe instance; private AuthMe instance;
public PerformBackup(AuthMe instance) { public PerformBackup(AuthMe instance) {
@ -33,11 +34,14 @@ public class PerformBackup {
public boolean DoBackup() { public boolean DoBackup() {
switch (Settings.getDataSource) { switch (Settings.getDataSource) {
case FILE: return FileBackup("auths.db"); case FILE:
return FileBackup("auths.db");
case MYSQL: return MySqlBackup(); case MYSQL:
return MySqlBackup();
case SQLITE: return FileBackup(Settings.getMySQLDatabase+".db"); case SQLITE:
return FileBackup(Settings.getMySQLDatabase + ".db");
} }
@ -45,12 +49,15 @@ public class PerformBackup {
} }
private boolean MySqlBackup() { private boolean MySqlBackup() {
File dirBackup = new File(AuthMe.getInstance().getDataFolder()+"/backups"); File dirBackup = new File(AuthMe.getInstance().getDataFolder()
+ "/backups");
if(!dirBackup.exists()) if (!dirBackup.exists()) dirBackup.mkdir();
dirBackup.mkdir();
if (checkWindows(Settings.backupWindowsPath)) { if (checkWindows(Settings.backupWindowsPath)) {
String executeCmd = Settings.backupWindowsPath+"\\bin\\mysqldump.exe -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path+".sql"; String executeCmd = Settings.backupWindowsPath
+ "\\bin\\mysqldump.exe -u " + dbUserName + " -p"
+ dbPassword + " " + dbName + " --tables " + tblname
+ " -r " + path + ".sql";
Process runtimeProcess; Process runtimeProcess;
try { try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd); runtimeProcess = Runtime.getRuntime().exec(executeCmd);
@ -65,7 +72,9 @@ public class PerformBackup {
ex.printStackTrace(); ex.printStackTrace();
} }
} else { } else {
String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path+".sql"; String executeCmd = "mysqldump -u " + dbUserName + " -p"
+ dbPassword + " " + dbName + " --tables " + tblname
+ " -r " + path + ".sql";
Process runtimeProcess; Process runtimeProcess;
try { try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd); runtimeProcess = Runtime.getRuntime().exec(executeCmd);
@ -84,10 +93,10 @@ public class PerformBackup {
} }
private boolean FileBackup(String backend) { private boolean FileBackup(String backend) {
File dirBackup = new File(AuthMe.getInstance().getDataFolder()+"/backups"); File dirBackup = new File(AuthMe.getInstance().getDataFolder()
+ "/backups");
if(!dirBackup.exists()) if (!dirBackup.exists()) dirBackup.mkdir();
dirBackup.mkdir();
try { try {
copy(new File("plugins/AuthMe/" + backend), new File(path + ".db")); copy(new File("plugins/AuthMe/" + backend), new File(path + ".db"));
@ -100,8 +109,8 @@ public class PerformBackup {
} }
/* /*
* Check if we are under Windows and correct location * Check if we are under Windows and correct location of mysqldump.exe
* of mysqldump.exe otherwise return error. * otherwise return error.
*/ */
private boolean checkWindows(String windowsPath) { private boolean checkWindows(String windowsPath) {
String isWin = System.getProperty("os.name").toLowerCase(); String isWin = System.getProperty("os.name").toLowerCase();
@ -109,7 +118,8 @@ public class PerformBackup {
if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) { if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) {
return true; return true;
} else { } else {
ConsoleLogger.showError("Mysql Windows Path is incorrect please check it"); ConsoleLogger
.showError("Mysql Windows Path is incorrect please check it");
return true; return true;
} }
} else return false; } else return false;

View File

@ -31,7 +31,8 @@ public class SendMailSSL {
public void main(final PlayerAuth auth, final String newPass) { public void main(final PlayerAuth auth, final String newPass) {
String sendername; String sendername;
if (Settings.getmailSenderName.isEmpty() || Settings.getmailSenderName == null) { if (Settings.getmailSenderName.isEmpty()
|| Settings.getmailSenderName == null) {
sendername = Settings.getmailAccount; sendername = Settings.getmailAccount;
} else { } else {
sendername = Settings.getmailSenderName; sendername = Settings.getmailSenderName;
@ -39,7 +40,8 @@ public class SendMailSSL {
Properties props = new Properties(); Properties props = new Properties();
props.put("mail.smtp.host", Settings.getmailSMTP); props.put("mail.smtp.host", Settings.getmailSMTP);
props.put("mail.smtp.socketFactory.port", String.valueOf(Settings.getMailPort)); props.put("mail.smtp.socketFactory.port",
String.valueOf(Settings.getMailPort));
props.put("mail.smtp.socketFactory.class", props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory"); "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true"); props.put("mail.smtp.auth", "true");
@ -48,7 +50,9 @@ public class SendMailSSL {
Session session = Session.getInstance(props, Session session = Session.getInstance(props,
new javax.mail.Authenticator() { new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() { protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Settings.getmailAccount,Settings.getmailPassword); return new PasswordAuthentication(
Settings.getmailAccount,
Settings.getmailPassword);
} }
}); });
@ -56,7 +60,8 @@ public class SendMailSSL {
final Message message = new MimeMessage(session); final Message message = new MimeMessage(session);
try { try {
message.setFrom(new InternetAddress(Settings.getmailAccount, sendername)); message.setFrom(new InternetAddress(Settings.getmailAccount,
sendername));
} catch (UnsupportedEncodingException uee) { } catch (UnsupportedEncodingException uee) {
message.setFrom(new InternetAddress(Settings.getmailAccount)); message.setFrom(new InternetAddress(Settings.getmailAccount));
} }
@ -66,7 +71,8 @@ public class SendMailSSL {
message.setSentDate(new Date()); message.setSentDate(new Date());
String text = Settings.getMailText; String text = Settings.getMailText;
text = text.replace("<playername>", auth.getNickname()); text = text.replace("<playername>", auth.getNickname());
text = text.replace("<servername>", plugin.getServer().getServerName()); text = text.replace("<servername>", plugin.getServer()
.getServerName());
text = text.replace("<generatedpass>", newPass); text = text.replace("<generatedpass>", newPass);
message.setContent(text, "text/html"); message.setContent(text, "text/html");
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@ -79,8 +85,8 @@ public class SendMailSSL {
} }
} }
}); });
if(!Settings.noConsoleSpam) if (!Settings.noConsoleSpam) ConsoleLogger.info("Email sent to : "
ConsoleLogger.info("Email sent to : " + auth.getNickname()); + auth.getNickname());
} catch (MessagingException e) { } catch (MessagingException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View File

@ -33,15 +33,16 @@ public class Utils {
} }
public void setGroup(String player, groupType group) { public void setGroup(String player, groupType group) {
if(!Settings.isPermissionCheckEnabled) if (!Settings.isPermissionCheckEnabled) return;
return; if (plugin.permission == null) return;
if(plugin.permission == null)
return;
try { try {
World world = null; World world = null;
currentGroup = plugin.permission.getPrimaryGroup(world, player); currentGroup = plugin.permission.getPrimaryGroup(world, player);
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!"); ConsoleLogger
.showError("Your permission system ("
+ plugin.permission.getName()
+ ") do not support Group system with that config... unhook!");
plugin.permission = null; plugin.permission = null;
return; return;
} }
@ -50,23 +51,27 @@ public class Utils {
switch (group) { switch (group) {
case UNREGISTERED: { case UNREGISTERED: {
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, Settings.unRegisteredGroup); plugin.permission.playerAddGroup(world, name,
Settings.unRegisteredGroup);
break; break;
} }
case REGISTERED: { case REGISTERED: {
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, Settings.getRegisteredGroup); plugin.permission.playerAddGroup(world, name,
Settings.getRegisteredGroup);
break; break;
} }
case NOTLOGGEDIN: { case NOTLOGGEDIN: {
if (!useGroupSystem()) break; if (!useGroupSystem()) break;
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(world, name, currentGroup);
plugin.permission.playerAddGroup(world, name, Settings.getUnloggedinGroup); plugin.permission.playerAddGroup(world, name,
Settings.getUnloggedinGroup);
break; break;
} }
case LOGGEDIN: { case LOGGEDIN: {
if (!useGroupSystem()) break; if (!useGroupSystem()) break;
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name.toLowerCase()); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(
name.toLowerCase());
if (limbo == null) break; if (limbo == null) break;
String realGroup = limbo.getGroup(); String realGroup = limbo.getGroup();
plugin.permission.playerRemoveGroup(world, name, currentGroup); plugin.permission.playerRemoveGroup(world, name, currentGroup);
@ -84,11 +89,17 @@ public class Utils {
if (plugin.permission == null) return false; if (plugin.permission == null) return false;
World world = null; World world = null;
try { try {
if(plugin.permission.playerRemoveGroup(world,player.getName().toString(),Settings.getUnloggedinGroup) && plugin.permission.playerAddGroup(world,player.getName().toString(),group)) { if (plugin.permission.playerRemoveGroup(world, player.getName()
.toString(), Settings.getUnloggedinGroup)
&& plugin.permission.playerAddGroup(world, player.getName()
.toString(), group)) {
return true; return true;
} }
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!"); ConsoleLogger
.showError("Your permission system ("
+ plugin.permission.getName()
+ ") do not support Group system with that config... unhook!");
plugin.permission = null; plugin.permission = null;
return false; return false;
} }
@ -107,12 +118,10 @@ public class Utils {
} }
public boolean isUnrestricted(Player player) { public boolean isUnrestricted(Player player) {
if(!Settings.isAllowRestrictedIp) if (!Settings.isAllowRestrictedIp) return false;
return false; if (Settings.getUnrestrictedName.isEmpty()
if(Settings.getUnrestrictedName.isEmpty() || Settings.getUnrestrictedName == null) || Settings.getUnrestrictedName == null) return false;
return false; if (Settings.getUnrestrictedName.contains(player.getName())) return true;
if(Settings.getUnrestrictedName.contains(player.getName()))
return true;
return false; return false;
} }
@ -122,21 +131,20 @@ public class Utils {
} }
private boolean useGroupSystem() { private boolean useGroupSystem() {
if(Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty()) if (Settings.isPermissionCheckEnabled
return true; && !Settings.getUnloggedinGroup.isEmpty()) return true;
return false; return false;
} }
public void packCoords(double x, double y, double z, String w, final Player pl) public void packCoords(double x, double y, double z, String w,
{ final Player pl) {
World theWorld; World theWorld;
if (w.equals("unavailableworld")) { if (w.equals("unavailableworld")) {
theWorld = pl.getWorld(); theWorld = pl.getWorld();
} else { } else {
theWorld = Bukkit.getWorld(w); theWorld = Bukkit.getWorld(w);
} }
if (theWorld == null) if (theWorld == null) theWorld = pl.getWorld();
theWorld = pl.getWorld();
final World world = theWorld; final World world = theWorld;
final Location locat = new Location(world, x, y, z); final Location locat = new Location(world, x, y, z);
@ -146,8 +154,8 @@ public class Utils {
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, locat); AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, locat);
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getChunk().isLoaded()) if (!tpEvent.getTo().getChunk().isLoaded()) tpEvent.getTo()
tpEvent.getTo().getChunk().load(); .getChunk().load();
pl.teleport(tpEvent.getTo()); pl.teleport(tpEvent.getTo());
} }
} }
@ -156,19 +164,18 @@ public class Utils {
/* /*
* Random Token for passpartu * Random Token for passpartu
*
*/ */
public boolean obtainToken() { public boolean obtainToken() {
File file = new File("plugins/AuthMe/passpartu.token"); File file = new File("plugins/AuthMe/passpartu.token");
if (file.exists()) if (file.exists()) file.delete();
file.delete();
FileWriter writer = null; FileWriter writer = null;
try { try {
file.createNewFile(); file.createNewFile();
writer = new FileWriter(file); writer = new FileWriter(file);
String token = generateToken(); String token = generateToken();
writer.write(token + ":" + System.currentTimeMillis() / 1000 + API.newline); writer.write(token + ":" + System.currentTimeMillis() / 1000
+ API.newline);
writer.flush(); writer.flush();
ConsoleLogger.info("[AuthMe] Security passpartu token: " + token); ConsoleLogger.info("[AuthMe] Security passpartu token: " + token);
writer.close(); writer.close();
@ -185,11 +192,9 @@ public class Utils {
public boolean readToken(String inputToken) { public boolean readToken(String inputToken) {
File file = new File("plugins/AuthMe/passpartu.token"); File file = new File("plugins/AuthMe/passpartu.token");
if (!file.exists()) if (!file.exists()) return false;
return false;
if (inputToken.isEmpty()) if (inputToken.isEmpty()) return false;
return false;
Scanner reader = null; Scanner reader = null;
try { try {
reader = new Scanner(file); reader = new Scanner(file);
@ -197,7 +202,9 @@ public class Utils {
final String line = reader.nextLine(); final String line = reader.nextLine();
if (line.contains(":")) { if (line.contains(":")) {
String[] tokenInfo = line.split(":"); String[] tokenInfo = line.split(":");
if(tokenInfo[0].equals(inputToken) && System.currentTimeMillis()/1000-30 <= Integer.parseInt(tokenInfo[1]) ) { if (tokenInfo[0].equals(inputToken)
&& System.currentTimeMillis() / 1000 - 30 <= Integer
.parseInt(tokenInfo[1])) {
file.delete(); file.delete();
reader.close(); reader.close();
return true; return true;
@ -229,8 +236,9 @@ public class Utils {
* Used for force player GameMode * Used for force player GameMode
*/ */
public static void forceGM(Player player) { public static void forceGM(Player player) {
if (!AuthMe.getInstance().authmePermissible(player, "authme.bypassforcesurvival")) if (!AuthMe.getInstance().authmePermissible(player,
player.setGameMode(GameMode.SURVIVAL); "authme.bypassforcesurvival")) player
.setGameMode(GameMode.SURVIVAL);
} }
public enum groupType { public enum groupType {

View File

@ -15,7 +15,6 @@ import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class API { public class API {
public static final String newline = System.getProperty("line.separator"); public static final String newline = System.getProperty("line.separator");
@ -26,12 +25,15 @@ public class API {
API.instance = instance; API.instance = instance;
API.database = database; API.database = database;
} }
/** /**
* Hook into AuthMe * Hook into AuthMe
*
* @return AuthMe instance * @return AuthMe instance
*/ */
public static AuthMe hookAuthMe() { public static AuthMe hookAuthMe() {
Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("AuthMe"); Plugin plugin = Bukkit.getServer().getPluginManager()
.getPlugin("AuthMe");
if (plugin == null || !(plugin instanceof AuthMe)) { if (plugin == null || !(plugin instanceof AuthMe)) {
return null; return null;
} }
@ -48,7 +50,8 @@ public class API {
* @return true if player is authenticate * @return true if player is authenticate
*/ */
public static boolean isAuthenticated(Player player) { public static boolean isAuthenticated(Player player) {
return PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase()); return PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase());
} }
/** /**
@ -58,8 +61,7 @@ public class API {
*/ */
@Deprecated @Deprecated
public boolean isaNPC(Player player) { public boolean isaNPC(Player player) {
if (instance.getCitizensCommunicator().isNPC(player, instance)) if (instance.getCitizensCommunicator().isNPC(player, instance)) return true;
return true;
return CombatTagComunicator.isNPC(player); return CombatTagComunicator.isNPC(player);
} }
@ -69,8 +71,7 @@ public class API {
* @return true if player is a npc * @return true if player is a npc
*/ */
public boolean isNPC(Player player) { public boolean isNPC(Player player) {
if (instance.getCitizensCommunicator().isNPC(player, instance)) if (instance.getCitizensCommunicator().isNPC(player, instance)) return true;
return true;
return CombatTagComunicator.isNPC(player); return CombatTagComunicator.isNPC(player);
} }
@ -85,10 +86,13 @@ public class API {
public static Location getLastLocation(Player player) { public static Location getLastLocation(Player player) {
try { try {
PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase()); PlayerAuth auth = PlayerCache.getInstance().getAuth(
player.getName().toLowerCase());
if (auth != null) { if (auth != null) {
Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY() , auth.getQuitLocZ()); Location loc = new Location(Bukkit.getWorld(auth.getWorld()),
auth.getQuitLocX(), auth.getQuitLocY(),
auth.getQuitLocZ());
return loc; return loc;
} else { } else {
return null; return null;
@ -99,7 +103,8 @@ public class API {
} }
} }
public static void setPlayerInventory(Player player, ItemStack[] content, ItemStack[] armor) { public static void setPlayerInventory(Player player, ItemStack[] content,
ItemStack[] armor) {
try { try {
player.getInventory().setContents(content); player.getInventory().setContents(content);
player.getInventory().setArmorContents(armor); player.getInventory().setArmorContents(armor);
@ -118,15 +123,18 @@ public class API {
} }
/** /**
* @param String playerName, String passwordToCheck * @param String
* playerName, String passwordToCheck
* @return true if the password is correct , false else * @return true if the password is correct , false else
*/ */
public static boolean checkPassword(String playerName, String passwordToCheck) { public static boolean checkPassword(String playerName,
String passwordToCheck) {
if (!isRegistered(playerName)) return false; if (!isRegistered(playerName)) return false;
String player = playerName.toLowerCase(); String player = playerName.toLowerCase();
PlayerAuth auth = database.getAuth(player); PlayerAuth auth = database.getAuth(player);
try { try {
return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName); return PasswordSecurity.comparePasswordWithHash(passwordToCheck,
auth.getHash(), playerName);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
return false; return false;
} }
@ -134,17 +142,21 @@ public class API {
/** /**
* Register a player * Register a player
* @param String playerName, String password *
* @param String
* playerName, String password
* @return true if the player is register correctly * @return true if the player is register correctly
*/ */
public static boolean registerPlayer(String playerName, String password) { public static boolean registerPlayer(String playerName, String password) {
try { try {
String name = playerName.toLowerCase(); String name = playerName.toLowerCase();
String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); String hash = PasswordSecurity.getHash(Settings.getPasswordHash,
password, name);
if (isRegistered(name)) { if (isRegistered(name)) {
return false; return false;
} }
PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0, "your@email.com", getPlayerRealName(name)); PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0,
"your@email.com", getPlayerRealName(name));
if (!database.saveAuth(auth)) { if (!database.saveAuth(auth)) {
return false; return false;
} }
@ -156,21 +168,25 @@ public class API {
/** /**
* Get Player realName from lowerCase nickname * Get Player realName from lowerCase nickname
* @param String playerName *
* return String player real name * @param String
* playerName return String player real name
*/ */
public static String getPlayerRealName(String nickname) { public static String getPlayerRealName(String nickname) {
try { try {
String realName = instance.dataManager.getOfflinePlayer(nickname).getName(); String realName = instance.dataManager.getOfflinePlayer(nickname)
if (realName != null && !realName.isEmpty()) .getName();
return realName; if (realName != null && !realName.isEmpty()) return realName;
} catch (NullPointerException npe) {} } catch (NullPointerException npe) {
}
return nickname; return nickname;
} }
/** /**
* Force a player to login * Force a player to login
* @param Player player *
* @param Player
* player
*/ */
public static void forceLogin(Player player) { public static void forceLogin(Player player) {
instance.management.performLogin(player, "dontneed", true); instance.management.performLogin(player, "dontneed", true);

View File

@ -19,7 +19,8 @@ public class PlayerAuth {
private String email = "your@email.com"; private String email = "your@email.com";
private String realName = ""; private String realName = "";
public PlayerAuth(String nickname, String hash, String ip, long lastLogin, String email, String realName) { public PlayerAuth(String nickname, String hash, String ip, long lastLogin,
String email, String realName) {
this.nickname = nickname; this.nickname = nickname;
this.hash = hash; this.hash = hash;
this.ip = ip; this.ip = ip;
@ -29,7 +30,8 @@ public class PlayerAuth {
} }
public PlayerAuth(String nickname, double x, double y, double z, String world) { public PlayerAuth(String nickname, double x, double y, double z,
String world) {
this.nickname = nickname; this.nickname = nickname;
this.x = x; this.x = x;
this.y = y; this.y = y;
@ -39,7 +41,9 @@ public class PlayerAuth {
} }
public PlayerAuth(String nickname, String hash, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) { public PlayerAuth(String nickname, String hash, String ip, long lastLogin,
double x, double y, double z, String world, String email,
String realName) {
this.nickname = nickname; this.nickname = nickname;
this.hash = hash; this.hash = hash;
this.ip = ip; this.ip = ip;
@ -53,7 +57,9 @@ public class PlayerAuth {
} }
public PlayerAuth(String nickname, String hash, String salt, int groupId, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) { public PlayerAuth(String nickname, String hash, String salt, int groupId,
String ip, long lastLogin, double x, double y, double z,
String world, String email, String realName) {
this.nickname = nickname; this.nickname = nickname;
this.hash = hash; this.hash = hash;
this.ip = ip; this.ip = ip;
@ -69,7 +75,8 @@ public class PlayerAuth {
} }
public PlayerAuth(String nickname, String hash, String salt, int groupId , String ip, long lastLogin, String realName) { public PlayerAuth(String nickname, String hash, String salt, int groupId,
String ip, long lastLogin, String realName) {
this.nickname = nickname; this.nickname = nickname;
this.hash = hash; this.hash = hash;
this.ip = ip; this.ip = ip;
@ -80,7 +87,8 @@ public class PlayerAuth {
} }
public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin, String realName) { public PlayerAuth(String nickname, String hash, String salt, String ip,
long lastLogin, String realName) {
this.nickname = nickname; this.nickname = nickname;
this.hash = hash; this.hash = hash;
this.ip = ip; this.ip = ip;
@ -90,7 +98,9 @@ public class PlayerAuth {
} }
public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) { public PlayerAuth(String nickname, String hash, String salt, String ip,
long lastLogin, double x, double y, double z, String world,
String email, String realName) {
this.nickname = nickname; this.nickname = nickname;
this.hash = hash; this.hash = hash;
this.ip = ip; this.ip = ip;
@ -119,8 +129,7 @@ public class PlayerAuth {
} }
public String getIp() { public String getIp() {
if (ip == null || ip.isEmpty()) if (ip == null || ip.isEmpty()) ip = "127.0.0.1";
ip = "127.0.0.1";
return ip; return ip;
} }
@ -130,7 +139,8 @@ public class PlayerAuth {
public String getHash() { public String getHash() {
if (Settings.getPasswordHash == HashAlgorithm.MD5VB) { if (Settings.getPasswordHash == HashAlgorithm.MD5VB) {
if(salt != null && !salt.isEmpty() && Settings.getPasswordHash == HashAlgorithm.MD5VB) { if (salt != null && !salt.isEmpty()
&& Settings.getPasswordHash == HashAlgorithm.MD5VB) {
vBhash = "$MD5vb$" + salt + "$" + hash; vBhash = "$MD5vb$" + salt + "$" + hash;
return vBhash; return vBhash;
} }
@ -149,28 +159,34 @@ public class PlayerAuth {
public double getQuitLocX() { public double getQuitLocX() {
return x; return x;
} }
public double getQuitLocY() { public double getQuitLocY() {
return y; return y;
} }
public double getQuitLocZ() { public double getQuitLocZ() {
return z; return z;
} }
public String getEmail() { public String getEmail() {
return email; return email;
} }
public void setQuitLocX(double d) { public void setQuitLocX(double d) {
this.x = d; this.x = d;
} }
public void setQuitLocY(double d) { public void setQuitLocY(double d) {
this.y = d; this.y = d;
} }
public void setQuitLocZ(double d) { public void setQuitLocZ(double d) {
this.z = d; this.z = d;
} }
public long getLastLogin() { public long getLastLogin() {
try { try {
if (Long.valueOf(lastLogin) == null) if (Long.valueOf(lastLogin) == null) lastLogin = 0L;
lastLogin = 0L;
} catch (NullPointerException e) { } catch (NullPointerException e) {
lastLogin = 0L; lastLogin = 0L;
} }
@ -203,13 +219,15 @@ public class PlayerAuth {
return false; return false;
} }
PlayerAuth other = (PlayerAuth) obj; PlayerAuth other = (PlayerAuth) obj;
return other.getIp().equals(this.ip) && other.getNickname().equals(this.nickname); return other.getIp().equals(this.ip)
&& other.getNickname().equals(this.nickname);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int hashCode = 7; int hashCode = 7;
hashCode = 71 * hashCode + (this.nickname != null ? this.nickname.hashCode() : 0); hashCode = 71 * hashCode
+ (this.nickname != null ? this.nickname.hashCode() : 0);
hashCode = 71 * hashCode + (this.ip != null ? this.ip.hashCode() : 0); hashCode = 71 * hashCode + (this.ip != null ? this.ip.hashCode() : 0);
return hashCode; return hashCode;
} }
@ -224,8 +242,10 @@ public class PlayerAuth {
@Override @Override
public String toString() { public String toString() {
String s = "Player : " + nickname + " ! IP : " + ip + " ! LastLogin : " + lastLogin + " ! LastPosition : " + x + "," + y + "," + z + "," + world String s = "Player : " + nickname + " ! IP : " + ip + " ! LastLogin : "
+ " ! Email : " + email + " ! Hash : " + hash + " ! Salt : " + salt + " ! RealName : " + realName; + lastLogin + " ! LastPosition : " + x + "," + y + "," + z
+ "," + world + " ! Email : " + email + " ! Hash : " + hash
+ " ! Salt : " + salt + " ! RealName : " + realName;
return s; return s;
} }

View File

@ -15,7 +15,8 @@ public class DataFileCache {
this.armor = armor; this.armor = armor;
} }
public DataFileCache(ItemStack[] inventory, ItemStack[] armor, String group, boolean operator, boolean flying){ public DataFileCache(ItemStack[] inventory, ItemStack[] armor,
String group, boolean operator, boolean flying) {
this.inventory = inventory; this.inventory = inventory;
this.armor = armor; this.armor = armor;
this.group = group; this.group = group;

View File

@ -18,6 +18,7 @@ import fr.xephi.authme.api.API;
public class FileCache { public class FileCache {
private AuthMe plugin = AuthMe.getInstance(); private AuthMe plugin = AuthMe.getInstance();
public FileCache() { public FileCache() {
final File folder = new File("cache"); final File folder = new File("cache");
if (!folder.exists()) { if (!folder.exists()) {
@ -25,9 +26,9 @@ public class FileCache {
} }
} }
public void createCache(String playername, DataFileCache playerData, String group, boolean operator, boolean flying) { public void createCache(String playername, DataFileCache playerData,
final File file = new File("cache/" + playername String group, boolean operator, boolean flying) {
+ ".cache"); final File file = new File("cache/" + playername + ".cache");
if (file.exists()) { if (file.exists()) {
return; return;
@ -40,13 +41,11 @@ public class FileCache {
writer = new FileWriter(file); writer = new FileWriter(file);
String s = group + ";"; String s = group + ";";
if (operator) if (operator) s = s + "1";
s = s + "1";
else s = s + "0"; else s = s + "0";
// line format Group|OperatorStatus|isFlying // line format Group|OperatorStatus|isFlying
if(flying) if (flying) writer.write(s + ";1" + API.newline);
writer.write(s+";1" + API.newline);
else writer.write(s + ";0" + API.newline); else writer.write(s + ";0" + API.newline);
writer.flush(); writer.flush();
@ -65,23 +64,26 @@ public class FileCache {
amount = invstack[i].getAmount(); amount = invstack[i].getAmount();
durability = invstack[i].getDurability(); durability = invstack[i].getDurability();
for (Enchantment e : invstack[i].getEnchantments().keySet()) { for (Enchantment e : invstack[i].getEnchantments().keySet()) {
enchList = enchList.concat(e.getName()+":"+invstack[i].getEnchantmentLevel(e)+":"); enchList = enchList.concat(e.getName() + ":"
+ invstack[i].getEnchantmentLevel(e) + ":");
} }
if (enchList.length() > 1) if (enchList.length() > 1) enchList = enchList.substring(0,
enchList = enchList.substring(0, enchList.length() - 1); enchList.length() - 1);
if (invstack[i].hasItemMeta()) { if (invstack[i].hasItemMeta()) {
if (invstack[i].getItemMeta().hasDisplayName()) { if (invstack[i].getItemMeta().hasDisplayName()) {
name = invstack[i].getItemMeta().getDisplayName(); name = invstack[i].getItemMeta().getDisplayName();
} }
if (invstack[i].getItemMeta().hasLore()) { if (invstack[i].getItemMeta().hasLore()) {
for (String lore : invstack[i].getItemMeta().getLore()) { for (String lore : invstack[i].getItemMeta()
.getLore()) {
lores = lore + "%newline%"; lores = lore + "%newline%";
} }
} }
} }
} }
String writeItem = "i" + ":" + itemid + ":" + amount + ":" String writeItem = "i" + ":" + itemid + ":" + amount + ":"
+ durability + ":"+ enchList + ";" + name + "\\*" + lores + "\r\n"; + durability + ":" + enchList + ";" + name + "\\*"
+ lores + "\r\n";
writer.write(writeItem); writer.write(writeItem);
writer.flush(); writer.flush();
} }
@ -99,24 +101,28 @@ public class FileCache {
itemid = armorstack[i].getType().name(); itemid = armorstack[i].getType().name();
amount = armorstack[i].getAmount(); amount = armorstack[i].getAmount();
durability = armorstack[i].getDurability(); durability = armorstack[i].getDurability();
for(Enchantment e : armorstack[i].getEnchantments().keySet()) { for (Enchantment e : armorstack[i].getEnchantments()
enchList = enchList.concat(e.getName()+":"+armorstack[i].getEnchantmentLevel(e)+":"); .keySet()) {
enchList = enchList.concat(e.getName() + ":"
+ armorstack[i].getEnchantmentLevel(e) + ":");
} }
if (enchList.length() > 1) if (enchList.length() > 1) enchList = enchList.substring(0,
enchList = enchList.substring(0, enchList.length() - 1); enchList.length() - 1);
if (armorstack[i].hasItemMeta()) { if (armorstack[i].hasItemMeta()) {
if (armorstack[i].getItemMeta().hasDisplayName()) { if (armorstack[i].getItemMeta().hasDisplayName()) {
name = armorstack[i].getItemMeta().getDisplayName(); name = armorstack[i].getItemMeta().getDisplayName();
} }
if (armorstack[i].getItemMeta().hasLore()) { if (armorstack[i].getItemMeta().hasLore()) {
for (String lore : armorstack[i].getItemMeta().getLore()) { for (String lore : armorstack[i].getItemMeta()
.getLore()) {
lores = lore + "%newline%"; lores = lore + "%newline%";
} }
} }
} }
} }
String writeItem = "w" + ":" + itemid + ":" + amount + ":" String writeItem = "w" + ":" + itemid + ":" + amount + ":"
+ durability + ":"+ enchList + ";" + name + "\\*" + lores + "\r\n"; + durability + ":" + enchList + ";" + name + "\\*"
+ lores + "\r\n";
writer.write(writeItem); writer.write(writeItem);
writer.flush(); writer.flush();
} }
@ -127,8 +133,7 @@ public class FileCache {
} }
public DataFileCache readCache(String playername) { public DataFileCache readCache(String playername) {
final File file = new File("cache/" + playername final File file = new File("cache/" + playername + ".cache");
+ ".cache");
ItemStack[] stacki = new ItemStack[36]; ItemStack[] stacki = new ItemStack[36];
ItemStack[] stacka = new ItemStack[4]; ItemStack[] stacka = new ItemStack[4];
@ -149,7 +154,8 @@ public class FileCache {
String line = reader.nextLine(); String line = reader.nextLine();
if (!line.contains(":")) { if (!line.contains(":")) {
// the fist line represent the player group, operator status and flying status // the fist line represent the player group, operator status
// and flying status
final String[] playerInfo = line.split(";"); final String[] playerInfo = line.split(";");
group = playerInfo[0]; group = playerInfo[0];
@ -157,8 +163,7 @@ public class FileCache {
op = true; op = true;
} else op = false; } else op = false;
if (playerInfo.length > 2) { if (playerInfo.length > 2) {
if (Integer.parseInt(playerInfo[2]) == 1) if (Integer.parseInt(playerInfo[2]) == 1) flying = true;
flying = true;
else flying = false; else flying = false;
} }
@ -179,18 +184,22 @@ public class FileCache {
line = line.split(";")[0]; line = line.split(";")[0];
} }
final String[] in = line.split(":"); final String[] in = line.split(":");
// can enchant item? size ofstring in file - 4 all / 2 = number of enchant // can enchant item? size ofstring in file - 4 all / 2 = number
// of enchant
if (in[0].equals("i")) { if (in[0].equals("i")) {
stacki[i] = new ItemStack(Material.getMaterial(in[1]), stacki[i] = new ItemStack(Material.getMaterial(in[1]),
Integer.parseInt(in[2]), Short.parseShort((in[3]))); Integer.parseInt(in[2]), Short.parseShort((in[3])));
if (in.length > 4 && !in[4].isEmpty()) { if (in.length > 4 && !in[4].isEmpty()) {
for (int k = 4; k < in.length - 1; k++) { for (int k = 4; k < in.length - 1; k++) {
stacki[i].addUnsafeEnchantment(Enchantment.getByName(in[k]) ,Integer.parseInt(in[k+1])); stacki[i].addUnsafeEnchantment(
Enchantment.getByName(in[k]),
Integer.parseInt(in[k + 1]));
k++; k++;
} }
} }
try { try {
ItemMeta meta = plugin.getServer().getItemFactory().getItemMeta(stacki[i].getType()); ItemMeta meta = plugin.getServer().getItemFactory()
.getItemMeta(stacki[i].getType());
if (!name.isEmpty()) { if (!name.isEmpty()) {
meta.setDisplayName(name); meta.setDisplayName(name);
} }
@ -201,23 +210,25 @@ public class FileCache {
} }
meta.setLore(loreList); meta.setLore(loreList);
} }
if (meta != null) if (meta != null) stacki[i].setItemMeta(meta);
stacki[i].setItemMeta(meta); } catch (Exception e) {
} catch (Exception e) {} }
i++; i++;
} else { } else {
stacka[a] = new ItemStack(Material.getMaterial(in[1]), stacka[a] = new ItemStack(Material.getMaterial(in[1]),
Integer.parseInt(in[2]), Short.parseShort((in[3]))); Integer.parseInt(in[2]), Short.parseShort((in[3])));
if (in.length > 4 && !in[4].isEmpty()) { if (in.length > 4 && !in[4].isEmpty()) {
for (int k = 4; k < in.length - 1; k++) { for (int k = 4; k < in.length - 1; k++) {
stacka[a].addUnsafeEnchantment(Enchantment.getByName(in[k]) ,Integer.parseInt(in[k+1])); stacka[a].addUnsafeEnchantment(
Enchantment.getByName(in[k]),
Integer.parseInt(in[k + 1]));
k++; k++;
} }
} }
try { try {
ItemMeta meta = plugin.getServer().getItemFactory().getItemMeta(stacka[a].getType()); ItemMeta meta = plugin.getServer().getItemFactory()
if (!name.isEmpty()) .getItemMeta(stacka[a].getType());
meta.setDisplayName(name); if (!name.isEmpty()) meta.setDisplayName(name);
if (!lores.isEmpty()) { if (!lores.isEmpty()) {
List<String> loreList = new ArrayList<String>(); List<String> loreList = new ArrayList<String>();
for (String s : lores.split("%newline%")) { for (String s : lores.split("%newline%")) {
@ -225,9 +236,9 @@ public class FileCache {
} }
meta.setLore(loreList); meta.setLore(loreList);
} }
if (meta != null) if (meta != null) stacki[i].setItemMeta(meta);
stacki[i].setItemMeta(meta); } catch (Exception e) {
} catch (Exception e) {} }
a++; a++;
} }
} }
@ -242,8 +253,7 @@ public class FileCache {
} }
public void removeCache(String playername) { public void removeCache(String playername) {
final File file = new File("cache/" + playername final File file = new File("cache/" + playername + ".cache");
+ ".cache");
if (file.exists()) { if (file.exists()) {
file.delete(); file.delete();
@ -251,8 +261,7 @@ public class FileCache {
} }
public boolean doesCacheExist(String playername) { public boolean doesCacheExist(String playername) {
final File file = new File("cache/" + playername final File file = new File("cache/" + playername + ".cache");
+ ".cache");
if (file.exists()) { if (file.exists()) {
return true; return true;

View File

@ -15,7 +15,6 @@ import fr.xephi.authme.events.ResetInventoryEvent;
import fr.xephi.authme.events.StoreInventoryEvent; import fr.xephi.authme.events.StoreInventoryEvent;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class LimboCache { public class LimboCache {
private static LimboCache singleton = null; private static LimboCache singleton = null;
@ -39,9 +38,11 @@ public class LimboCache {
boolean flying; boolean flying;
if (playerData.doesCacheExist(name)) { if (playerData.doesCacheExist(name)) {
StoreInventoryEvent event = new StoreInventoryEvent(player, playerData); StoreInventoryEvent event = new StoreInventoryEvent(player,
playerData);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) { if (!event.isCancelled() && event.getInventory() != null
&& event.getArmor() != null) {
inv = event.getInventory(); inv = event.getInventory();
arm = event.getArmor(); arm = event.getArmor();
} else { } else {
@ -54,31 +55,34 @@ public class LimboCache {
} else { } else {
StoreInventoryEvent event = new StoreInventoryEvent(player); StoreInventoryEvent event = new StoreInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) { if (!event.isCancelled() && event.getInventory() != null
&& event.getArmor() != null) {
inv = event.getInventory(); inv = event.getInventory();
arm = event.getArmor(); arm = event.getArmor();
} else { } else {
inv = null; inv = null;
arm = null; arm = null;
} }
if(player.isOp()) if (player.isOp()) operator = true;
operator = true;
else operator = false; else operator = false;
if(player.isFlying()) if (player.isFlying()) flying = true;
flying = true;
else flying = false; else flying = false;
if (plugin.permission != null) { if (plugin.permission != null) {
try { try {
playerGroup = plugin.permission.getPrimaryGroup(player); playerGroup = plugin.permission.getPrimaryGroup(player);
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!"); ConsoleLogger
.showError("Your permission system ("
+ plugin.permission.getName()
+ ") do not support Group system with that config... unhook!");
plugin.permission = null; plugin.permission = null;
} }
} }
} }
if (Settings.isForceSurvivalModeEnabled) { if (Settings.isForceSurvivalModeEnabled) {
if(Settings.isResetInventoryIfCreative && player.getGameMode() == GameMode.CREATIVE ) { if (Settings.isResetInventoryIfCreative
&& player.getGameMode() == GameMode.CREATIVE) {
ResetInventoryEvent event = new ResetInventoryEvent(player); ResetInventoryEvent event = new ResetInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {
@ -91,11 +95,13 @@ public class LimboCache {
if (player.isDead()) { if (player.isDead()) {
loc = plugin.getSpawnLocation(player); loc = plugin.getSpawnLocation(player);
} }
cache.put(player.getName().toLowerCase(), new LimboPlayer(name, loc, inv, arm, gameMode, operator, playerGroup, flying)); cache.put(player.getName().toLowerCase(), new LimboPlayer(name, loc,
inv, arm, gameMode, operator, playerGroup, flying));
} }
public void addLimboPlayer(Player player, String group) { public void addLimboPlayer(Player player, String group) {
cache.put(player.getName().toLowerCase(), new LimboPlayer(player.getName().toLowerCase(), group)); cache.put(player.getName().toLowerCase(), new LimboPlayer(player
.getName().toLowerCase(), group));
} }
public void deleteLimboPlayer(String name) { public void deleteLimboPlayer(String name) {

View File

@ -17,7 +17,9 @@ public class LimboPlayer {
private String group = ""; private String group = "";
private boolean flying = false; private boolean flying = false;
public LimboPlayer(String name, Location loc, ItemStack[] inventory, ItemStack[] armour, GameMode gameMode, boolean operator, String group, boolean flying) { public LimboPlayer(String name, Location loc, ItemStack[] inventory,
ItemStack[] armour, GameMode gameMode, boolean operator,
String group, boolean flying) {
this.name = name; this.name = name;
this.loc = loc; this.loc = loc;
this.inventory = inventory; this.inventory = inventory;
@ -28,7 +30,8 @@ public class LimboPlayer {
this.flying = flying; this.flying = flying;
} }
public LimboPlayer(String name, Location loc, GameMode gameMode, boolean operator, String group, boolean flying) { public LimboPlayer(String name, Location loc, GameMode gameMode,
boolean operator, String group, boolean flying) {
this.name = name; this.name = name;
this.loc = loc; this.loc = loc;
this.gameMode = gameMode; this.gameMode = gameMode;

View File

@ -43,7 +43,6 @@ import fr.xephi.authme.settings.SpoutCfg;
import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask; import fr.xephi.authme.task.TimeoutTask;
public class AdminCommand implements CommandExecutor { public class AdminCommand implements CommandExecutor {
public AuthMe plugin; public AuthMe plugin;
@ -57,7 +56,8 @@ public class AdminCommand implements CommandExecutor {
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (args.length == 0) { if (args.length == 0) {
sender.sendMessage("Usage: /authme reload - Reload the config"); sender.sendMessage("Usage: /authme reload - Reload the config");
sender.sendMessage("/authme register <playername> <password> - Register a player"); sender.sendMessage("/authme register <playername> <password> - Register a player");
@ -76,26 +76,32 @@ public class AdminCommand implements CommandExecutor {
return true; return true;
} }
if (!plugin.authmePermissible(sender, "authme.admin." + args[0].toLowerCase())) { if (!plugin.authmePermissible(sender,
"authme.admin." + args[0].toLowerCase())) {
m._(sender, "no_perm"); m._(sender, "no_perm");
return true; return true;
} }
if((sender instanceof ConsoleCommandSender) && args[0].equalsIgnoreCase("passpartuToken")) { if ((sender instanceof ConsoleCommandSender)
&& args[0].equalsIgnoreCase("passpartuToken")) {
if (args.length > 1) { if (args.length > 1) {
System.out.println("[AuthMe] command usage: /authme passpartuToken"); System.out
.println("[AuthMe] command usage: /authme passpartuToken");
return true; return true;
} }
if (Utils.getInstance().obtainToken()) { if (Utils.getInstance().obtainToken()) {
System.out.println("[AuthMe] You have 30s for insert this token ingame with /passpartu [token]"); System.out
.println("[AuthMe] You have 30s for insert this token ingame with /passpartu [token]");
} else { } else {
System.out.println("[AuthMe] Security error on passpartu token, redo it. "); System.out
.println("[AuthMe] Security error on passpartu token, redo it. ");
} }
return true; return true;
} }
if (args[0].equalsIgnoreCase("version")) { if (args[0].equalsIgnoreCase("version")) {
sender.sendMessage("AuthMe Version: "+AuthMe.getInstance().getDescription().getVersion()); sender.sendMessage("AuthMe Version: "
+ AuthMe.getInstance().getDescription().getVersion());
return true; return true;
} }
@ -109,15 +115,16 @@ public class AdminCommand implements CommandExecutor {
calendar.add(Calendar.DATE, -(Integer.parseInt(args[1]))); calendar.add(Calendar.DATE, -(Integer.parseInt(args[1])));
long until = calendar.getTimeInMillis(); long until = calendar.getTimeInMillis();
List<String> purged = database.autoPurgeDatabase(until); List<String> purged = database.autoPurgeDatabase(until);
sender.sendMessage("Deleted " + purged.size() + " user accounts"); sender.sendMessage("Deleted " + purged.size()
if (Settings.purgeEssentialsFile && plugin.ess != null) + " user accounts");
plugin.dataManager.purgeEssentials(purged); if (Settings.purgeEssentialsFile && plugin.ess != null) plugin.dataManager
if (Settings.purgePlayerDat) .purgeEssentials(purged);
plugin.dataManager.purgeDat(purged); if (Settings.purgePlayerDat) plugin.dataManager
if (Settings.purgeLimitedCreative) .purgeDat(purged);
plugin.dataManager.purgeLimitedCreative(purged); if (Settings.purgeLimitedCreative) plugin.dataManager
if (Settings.purgeAntiXray) .purgeLimitedCreative(purged);
plugin.dataManager.purgeAntiXray(purged); if (Settings.purgeAntiXray) plugin.dataManager
.purgeAntiXray(purged);
return true; return true;
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
sender.sendMessage("Usage: /authme purge <DAYS>"); sender.sendMessage("Usage: /authme purge <DAYS>");
@ -138,7 +145,8 @@ public class AdminCommand implements CommandExecutor {
fos.write(buf, 0, i); fos.write(buf, 0, i);
} }
} catch (Exception e) { } catch (Exception e) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Failed to load config from JAR"); Logger.getLogger(JavaPlugin.class.getName()).log(
Level.SEVERE, "Failed to load config from JAR");
} finally { } finally {
try { try {
if (fis != null) { if (fis != null) {
@ -151,7 +159,8 @@ public class AdminCommand implements CommandExecutor {
} }
} }
} }
YamlConfiguration newConfig = YamlConfiguration.loadConfiguration(newConfigFile); YamlConfiguration newConfig = YamlConfiguration
.loadConfiguration(newConfigFile);
Settings.reloadConfigOptions(newConfig); Settings.reloadConfigOptions(newConfig);
m.reLoad(); m.reLoad();
s.reLoad(); s.reLoad();
@ -167,10 +176,16 @@ public class AdminCommand implements CommandExecutor {
long lastLogin = player.getLastLogin(); long lastLogin = player.getLastLogin();
Date d = new Date(lastLogin); Date d = new Date(lastLogin);
final long diff = System.currentTimeMillis() - lastLogin; final long diff = System.currentTimeMillis() - lastLogin;
final String msg = (int)(diff / 86400000) + " days " + (int)(diff / 3600000 % 24) + " hours " + (int)(diff / 60000 % 60) + " mins " + (int)(diff / 1000 % 60) + " secs."; final String msg = (int) (diff / 86400000) + " days "
+ (int) (diff / 3600000 % 24) + " hours "
+ (int) (diff / 60000 % 60) + " mins "
+ (int) (diff / 1000 % 60) + " secs.";
String lastIP = player.getIp(); String lastIP = player.getIp();
sender.sendMessage("[AuthMe] " + args[1].toLowerCase() + " lastlogin : " + d.toString()); sender.sendMessage("[AuthMe] " + args[1].toLowerCase()
sender.sendMessage("[AuthMe] The player : " + player.getNickname() + " is unlogged since " + msg); + " lastlogin : " + d.toString());
sender.sendMessage("[AuthMe] The player : "
+ player.getNickname() + " is unlogged since "
+ msg);
sender.sendMessage("[AuthMe] LastPlayer IP : " + lastIP); sender.sendMessage("[AuthMe] LastPlayer IP : " + lastIP);
} else { } else {
m._(sender, "unknown_user"); m._(sender, "unknown_user");
@ -189,25 +204,31 @@ public class AdminCommand implements CommandExecutor {
if (!args[1].contains(".")) { if (!args[1].contains(".")) {
final CommandSender fSender = sender; final CommandSender fSender = sender;
final String[] arguments = args; final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override @Override
public void run() { public void run() {
PlayerAuth pAuth = null; PlayerAuth pAuth = null;
String message = "[AuthMe] "; String message = "[AuthMe] ";
try { try {
pAuth = database.getAuth(arguments[1].toLowerCase()); pAuth = database.getAuth(arguments[1]
.toLowerCase());
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
fSender.sendMessage("[AuthMe] This player is unknown"); fSender.sendMessage("[AuthMe] This player is unknown");
return; return;
} }
if (pAuth != null) { if (pAuth != null) {
List<String> accountList = database.getAllAuthsByName(pAuth); List<String> accountList = database
if (accountList.isEmpty() || accountList == null) { .getAllAuthsByName(pAuth);
if (accountList.isEmpty()
|| accountList == null) {
fSender.sendMessage("[AuthMe] This player is unknown"); fSender.sendMessage("[AuthMe] This player is unknown");
return; return;
} }
if (accountList.size() == 1) { if (accountList.size() == 1) {
fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player"); fSender.sendMessage("[AuthMe] "
+ arguments[1]
+ " is a single account player");
return; return;
} }
int i = 0; int i = 0;
@ -220,7 +241,11 @@ public class AdminCommand implements CommandExecutor {
message = message + "."; message = message + ".";
} }
} }
fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts"); fSender.sendMessage("[AuthMe] "
+ arguments[1]
+ " has "
+ String.valueOf(accountList.size())
+ " accounts");
fSender.sendMessage(message); fSender.sendMessage(message);
} else { } else {
fSender.sendMessage("[AuthMe] This player is unknown"); fSender.sendMessage("[AuthMe] This player is unknown");
@ -232,18 +257,23 @@ public class AdminCommand implements CommandExecutor {
} else { } else {
final CommandSender fSender = sender; final CommandSender fSender = sender;
final String[] arguments = args; final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override @Override
public void run() { public void run() {
String message = "[AuthMe] "; String message = "[AuthMe] ";
if (arguments[1] != null) { if (arguments[1] != null) {
List<String> accountList = database.getAllAuthsByIp(arguments[1]); List<String> accountList = database
if (accountList.isEmpty() || accountList == null) { .getAllAuthsByIp(arguments[1]);
if (accountList.isEmpty()
|| accountList == null) {
fSender.sendMessage("[AuthMe] Please put a valid IP"); fSender.sendMessage("[AuthMe] Please put a valid IP");
return; return;
} }
if (accountList.size() == 1) { if (accountList.size() == 1) {
fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player"); fSender.sendMessage("[AuthMe] "
+ arguments[1]
+ " is a single account player");
return; return;
} }
int i = 0; int i = 0;
@ -256,7 +286,11 @@ public class AdminCommand implements CommandExecutor {
message = message + "."; message = message + ".";
} }
} }
fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts"); fSender.sendMessage("[AuthMe] "
+ arguments[1]
+ " has "
+ String.valueOf(accountList.size())
+ " accounts");
fSender.sendMessage(message); fSender.sendMessage(message);
} else { } else {
fSender.sendMessage("[AuthMe] Please put a valid IP"); fSender.sendMessage("[AuthMe] Please put a valid IP");
@ -266,7 +300,8 @@ public class AdminCommand implements CommandExecutor {
}); });
return true; return true;
} }
} else if (args[0].equalsIgnoreCase("register") || args[0].equalsIgnoreCase("reg")) { } else if (args[0].equalsIgnoreCase("register")
|| args[0].equalsIgnoreCase("reg")) {
if (args.length != 3) { if (args.length != 3) {
sender.sendMessage("Usage: /authme register playername password"); sender.sendMessage("Usage: /authme register playername password");
return true; return true;
@ -277,12 +312,14 @@ public class AdminCommand implements CommandExecutor {
m._(sender, "user_regged"); m._(sender, "user_regged");
return true; return true;
} }
String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name); String hash = PasswordSecurity.getHash(
PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0L, "your@email.com", API.getPlayerRealName(name)); Settings.getPasswordHash, args[2], name);
if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null) PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0L,
auth.setSalt(PasswordSecurity.userSalt.get(name)); "your@email.com", API.getPlayerRealName(name));
else if (PasswordSecurity.userSalt.containsKey(name)
auth.setSalt(""); && PasswordSecurity.userSalt.get(name) != null) auth
.setSalt(PasswordSecurity.userSalt.get(name));
else auth.setSalt("");
if (!database.saveAuth(auth)) { if (!database.saveAuth(auth)) {
m._(sender, "error"); m._(sender, "error");
return true; return true;
@ -305,7 +342,8 @@ public class AdminCommand implements CommandExecutor {
m._(sender, "unknown_user"); m._(sender, "unknown_user");
return true; return true;
} }
sender.sendMessage("[AuthMe] " + args[1] + " email : " + getAuth.getEmail()); sender.sendMessage("[AuthMe] " + args[1] + " email : "
+ getAuth.getEmail());
return true; return true;
} else if (args[0].equalsIgnoreCase("chgemail")) { } else if (args[0].equalsIgnoreCase("chgemail")) {
if (args.length != 3) { if (args.length != 3) {
@ -323,15 +361,17 @@ public class AdminCommand implements CommandExecutor {
m._(sender, "error"); m._(sender, "error");
return true; return true;
} }
if (PlayerCache.getInstance().getAuth(playername) != null) if (PlayerCache.getInstance().getAuth(playername) != null) PlayerCache
PlayerCache.getInstance().updatePlayer(getAuth); .getInstance().updatePlayer(getAuth);
return true; return true;
} else if (args[0].equalsIgnoreCase("setspawn")) { } else if (args[0].equalsIgnoreCase("setspawn")) {
try { try {
if (sender instanceof Player) { if (sender instanceof Player) {
if (Spawn.getInstance().setSpawn(((Player) sender).getLocation())) if (Spawn.getInstance().setSpawn(
sender.sendMessage("[AuthMe] Correctly define new spawn"); ((Player) sender).getLocation())) sender
else sender.sendMessage("[AuthMe] SetSpawn fail , please retry"); .sendMessage("[AuthMe] Correctly define new spawn");
else sender
.sendMessage("[AuthMe] SetSpawn fail , please retry");
} else { } else {
sender.sendMessage("[AuthMe] Please use that command in game"); sender.sendMessage("[AuthMe] Please use that command in game");
} }
@ -342,9 +382,11 @@ public class AdminCommand implements CommandExecutor {
} else if (args[0].equalsIgnoreCase("setfirstspawn")) { } else if (args[0].equalsIgnoreCase("setfirstspawn")) {
try { try {
if (sender instanceof Player) { if (sender instanceof Player) {
if (Spawn.getInstance().setFirstSpawn(((Player) sender).getLocation())) if (Spawn.getInstance().setFirstSpawn(
sender.sendMessage("[AuthMe] Correctly define new first spawn"); ((Player) sender).getLocation())) sender
else sender.sendMessage("[AuthMe] SetFirstSpawn fail , please retry"); .sendMessage("[AuthMe] Correctly define new first spawn");
else sender
.sendMessage("[AuthMe] SetFirstSpawn fail , please retry");
} else { } else {
sender.sendMessage("[AuthMe] Please use that command in game"); sender.sendMessage("[AuthMe] Please use that command in game");
} }
@ -361,28 +403,30 @@ public class AdminCommand implements CommandExecutor {
if (database instanceof Thread) { if (database instanceof Thread) {
database.purgeBanned(bP); database.purgeBanned(bP);
} else { } else {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { Bukkit.getScheduler().runTaskAsynchronously(plugin,
new Runnable() {
@Override @Override
public void run() { public void run() {
database.purgeBanned(bP); database.purgeBanned(bP);
} }
}); });
} }
if (Settings.purgeEssentialsFile && plugin.ess != null) if (Settings.purgeEssentialsFile && plugin.ess != null) plugin.dataManager
plugin.dataManager.purgeEssentials(bannedPlayers); .purgeEssentials(bannedPlayers);
if (Settings.purgePlayerDat) if (Settings.purgePlayerDat) plugin.dataManager
plugin.dataManager.purgeDat(bannedPlayers); .purgeDat(bannedPlayers);
if (Settings.purgeLimitedCreative) if (Settings.purgeLimitedCreative) plugin.dataManager
plugin.dataManager.purgeLimitedCreative(bannedPlayers); .purgeLimitedCreative(bannedPlayers);
if (Settings.purgeAntiXray) if (Settings.purgeAntiXray) plugin.dataManager
plugin.dataManager.purgeAntiXray(bannedPlayers); .purgeAntiXray(bannedPlayers);
return true; return true;
} else if (args[0].equalsIgnoreCase("spawn")) { } else if (args[0].equalsIgnoreCase("spawn")) {
try { try {
if (sender instanceof Player) { if (sender instanceof Player) {
if (Spawn.getInstance().getSpawn() != null) if (Spawn.getInstance().getSpawn() != null) ((Player) sender)
((Player) sender).teleport(Spawn.getInstance().getSpawn()); .teleport(Spawn.getInstance().getSpawn());
else sender.sendMessage("[AuthMe] Spawn fail , please try to define the spawn"); else sender
.sendMessage("[AuthMe] Spawn fail , please try to define the spawn");
} else { } else {
sender.sendMessage("[AuthMe] Please use that command in game"); sender.sendMessage("[AuthMe] Please use that command in game");
} }
@ -393,9 +437,10 @@ public class AdminCommand implements CommandExecutor {
} else if (args[0].equalsIgnoreCase("firstspawn")) { } else if (args[0].equalsIgnoreCase("firstspawn")) {
try { try {
if (sender instanceof Player) { if (sender instanceof Player) {
if (Spawn.getInstance().getFirstSpawn() != null) if (Spawn.getInstance().getFirstSpawn() != null) ((Player) sender)
((Player) sender).teleport(Spawn.getInstance().getFirstSpawn()); .teleport(Spawn.getInstance().getFirstSpawn());
else sender.sendMessage("[AuthMe] Spawn fail , please try to define the first spawn"); else sender
.sendMessage("[AuthMe] Spawn fail , please try to define the first spawn");
} else { } else {
sender.sendMessage("[AuthMe] Please use that command in game"); sender.sendMessage("[AuthMe] Please use that command in game");
} }
@ -403,14 +448,16 @@ public class AdminCommand implements CommandExecutor {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
} }
return true; return true;
} else if (args[0].equalsIgnoreCase("changepassword") || args[0].equalsIgnoreCase("cp")) { } else if (args[0].equalsIgnoreCase("changepassword")
|| args[0].equalsIgnoreCase("cp")) {
if (args.length != 3) { if (args.length != 3) {
sender.sendMessage("Usage: /authme changepassword playername newpassword"); sender.sendMessage("Usage: /authme changepassword playername newpassword");
return true; return true;
} }
try { try {
String name = args[1].toLowerCase(); String name = args[1].toLowerCase();
String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name); String hash = PasswordSecurity.getHash(
Settings.getPasswordHash, args[2], name);
PlayerAuth auth = null; PlayerAuth auth = null;
if (PlayerCache.getInstance().isAuthenticated(name)) { if (PlayerCache.getInstance().isAuthenticated(name)) {
auth = PlayerCache.getInstance().getAuth(name); auth = PlayerCache.getInstance().getAuth(name);
@ -437,7 +484,9 @@ public class AdminCommand implements CommandExecutor {
m._(sender, "error"); m._(sender, "error");
} }
return true; return true;
} else if (args[0].equalsIgnoreCase("unregister") || args[0].equalsIgnoreCase("unreg") || args[0].equalsIgnoreCase("del") ) { } else if (args[0].equalsIgnoreCase("unregister")
|| args[0].equalsIgnoreCase("unreg")
|| args[0].equalsIgnoreCase("del")) {
if (args.length != 2) { if (args.length != 2) {
sender.sendMessage("Usage: /authme unregister playername"); sender.sendMessage("Usage: /authme unregister playername");
return true; return true;
@ -452,10 +501,13 @@ public class AdminCommand implements CommandExecutor {
Utils.getInstance().setGroup(name, groupType.UNREGISTERED); Utils.getInstance().setGroup(name, groupType.UNREGISTERED);
if (target != null) { if (target != null) {
if (target.isOnline()) { if (target.isOnline()) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled
&& !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(target); Location spawn = plugin.getSpawnLocation(target);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(target, target.getLocation(), spawn, false); SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(
plugin.getServer().getPluginManager().callEvent(tpEvent); target, target.getLocation(), spawn, false);
plugin.getServer().getPluginManager()
.callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
target.teleport(tpEvent.getTo()); target.teleport(tpEvent.getTo());
} }
@ -465,12 +517,23 @@ public class AdminCommand implements CommandExecutor {
int interval = Settings.getWarnMessageInterval; int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = sender.getServer().getScheduler(); BukkitScheduler sched = sender.getServer().getScheduler();
if (delay != 0) { if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay); int id = sched.scheduleSyncDelayedTask(plugin,
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); new TimeoutTask(plugin, name), delay);
LimboCache.getInstance().getLimboPlayer(name)
.setTimeoutTaskId(id);
} }
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("reg_msg"), interval))); LimboCache
if (Settings.applyBlindEffect) .getInstance()
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); .getLimboPlayer(name)
.setMessageTaskId(
sched.scheduleSyncDelayedTask(
plugin,
new MessageTask(plugin, name, m
._("reg_msg"), interval)));
if (Settings.applyBlindEffect) target
.addPotionEffect(new PotionEffect(
PotionEffectType.BLINDNESS,
Settings.getRegistrationTimeout * 20, 2));
m._(target, "unregistered"); m._(target, "unregistered");
} else { } else {
// Player isn't online, do nothing else // Player isn't online, do nothing else
@ -490,7 +553,8 @@ public class AdminCommand implements CommandExecutor {
String name = args[1].toLowerCase(); String name = args[1].toLowerCase();
PlayerAuth auth = database.getAuth(name); PlayerAuth auth = database.getAuth(name);
if (auth == null) { if (auth == null) {
sender.sendMessage("The player " + name + " is not registered "); sender.sendMessage("The player " + name
+ " is not registered ");
return true; return true;
} }
auth.setQuitLocX(0); auth.setQuitLocX(0);
@ -500,10 +564,11 @@ public class AdminCommand implements CommandExecutor {
database.updateQuitLoc(auth); database.updateQuitLoc(auth);
sender.sendMessage(name + " 's last pos location is now reset"); sender.sendMessage(name + " 's last pos location is now reset");
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.showError("An error occured while trying to reset location or player do not exist, please see below: "); ConsoleLogger
.showError("An error occured while trying to reset location or player do not exist, please see below: ");
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (sender instanceof Player) if (sender instanceof Player) sender
sender.sendMessage("An error occured while trying to reset location or player do not exist, please see logs"); .sendMessage("An error occured while trying to reset location or player do not exist, please see logs");
} }
return true; return true;
} else if (args[0].equalsIgnoreCase("switchantibot")) { } else if (args[0].equalsIgnoreCase("switchantibot")) {
@ -530,8 +595,11 @@ public class AdminCommand implements CommandExecutor {
} }
if (Bukkit.getPlayer(args[1]) != null) { if (Bukkit.getPlayer(args[1]) != null) {
Player player = Bukkit.getPlayer(args[1]); Player player = Bukkit.getPlayer(args[1]);
sender.sendMessage(player.getName() + " actual ip is : " + player.getAddress().getAddress().getHostAddress() + ":" + player.getAddress().getPort()); sender.sendMessage(player.getName() + " actual ip is : "
sender.sendMessage(player.getName() + " real ip is : " + plugin.getIP(player)); + player.getAddress().getAddress().getHostAddress()
+ ":" + player.getAddress().getPort());
sender.sendMessage(player.getName() + " real ip is : "
+ plugin.getIP(player));
return true; return true;
} else { } else {
sender.sendMessage("This player is not actually online"); sender.sendMessage("This player is not actually online");
@ -553,7 +621,8 @@ public class AdminCommand implements CommandExecutor {
auth.setQuitLocZ(0D); auth.setQuitLocZ(0D);
auth.setWorld("world"); auth.setWorld("world");
database.updateQuitLoc(auth); database.updateQuitLoc(auth);
sender.sendMessage("[AuthMe] Successfully reset position for " + auth.getNickname()); sender.sendMessage("[AuthMe] Successfully reset position for "
+ auth.getNickname());
return true; return true;
} else { } else {
sender.sendMessage("Usage: /authme reload|register playername password|changepassword playername password|unregister playername"); sender.sendMessage("Usage: /authme reload|register playername password|changepassword playername password|unregister playername");

View File

@ -11,7 +11,6 @@ import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages; import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class CaptchaCommand implements CommandExecutor { public class CaptchaCommand implements CommandExecutor {
public AuthMe plugin; public AuthMe plugin;
@ -23,8 +22,8 @@ public class CaptchaCommand implements CommandExecutor {
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, public boolean onCommand(CommandSender sender, Command cmnd, String label,
String label, String[] args) { String[] args) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
return true; return true;
@ -62,7 +61,8 @@ public class CaptchaCommand implements CommandExecutor {
plugin.cap.remove(name); plugin.cap.remove(name);
plugin.cap.put(name, rdm.nextString()); plugin.cap.put(name, rdm.nextString());
for (String s : m._("wrong_captcha")) { for (String s : m._("wrong_captcha")) {
player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name))); player.sendMessage(s.replace("THE_CAPTCHA",
plugin.cap.get(name)));
} }
return true; return true;
} }

View File

@ -18,7 +18,6 @@ import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Messages; import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class ChangePasswordCommand implements CommandExecutor { public class ChangePasswordCommand implements CommandExecutor {
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
@ -31,7 +30,8 @@ public class ChangePasswordCommand implements CommandExecutor {
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
return true; return true;
} }
@ -54,15 +54,17 @@ public class ChangePasswordCommand implements CommandExecutor {
} }
try { try {
String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, args[1], name); String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash,
args[1], name);
if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) { if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache
.getInstance().getAuth(name).getHash(), player.getName())) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(name); PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
auth.setHash(hashnew); auth.setHash(hashnew);
if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null) if (PasswordSecurity.userSalt.containsKey(name)
auth.setSalt(PasswordSecurity.userSalt.get(name)); && PasswordSecurity.userSalt.get(name) != null) auth
else .setSalt(PasswordSecurity.userSalt.get(name));
auth.setSalt(""); else auth.setSalt("");
if (!database.updatePassword(auth)) { if (!database.updatePassword(auth)) {
m._(player, "error"); m._(player, "error");
return true; return true;
@ -72,7 +74,9 @@ public class ChangePasswordCommand implements CommandExecutor {
m._(player, "pwd_changed"); m._(player, "pwd_changed");
ConsoleLogger.info(player.getName() + " changed his password"); ConsoleLogger.info(player.getName() + " changed his password");
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " change his password!")); plugin.notifications.showNotification(new Notification(
"[AuthMe] " + player.getName()
+ " change his password!"));
} }
} else { } else {
m._(player, "wrong_pwd"); m._(player, "wrong_pwd");

View File

@ -18,7 +18,6 @@ import fr.xephi.authme.converter.xAuthConverter;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.settings.Messages; import fr.xephi.authme.settings.Messages;
public class ConverterCommand implements CommandExecutor { public class ConverterCommand implements CommandExecutor {
private AuthMe plugin; private AuthMe plugin;
@ -31,7 +30,8 @@ public class ConverterCommand implements CommandExecutor {
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, final String[] args) { public boolean onCommand(CommandSender sender, Command cmnd, String label,
final String[] args) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
return true; return true;
} }
@ -74,7 +74,8 @@ public class ConverterCommand implements CommandExecutor {
case vauth: case vauth:
converter = new vAuthConverter(plugin, database, sender); converter = new vAuthConverter(plugin, database, sender);
break; break;
default: break; default:
break;
} }
if (converter == null) { if (converter == null) {
m._(sender, "error"); m._(sender, "error");
@ -87,13 +88,9 @@ public class ConverterCommand implements CommandExecutor {
public enum ConvertType { public enum ConvertType {
ftsql("flattosql"), ftsql("flattosql"), ftsqlite("flattosqlite"), xauth("xauth"), crazylogin(
ftsqlite("flattosqlite"), "crazylogin"), rakamak("rakamak"), royalauth("royalauth"), vauth(
xauth("xauth"), "vauth");
crazylogin("crazylogin"),
rakamak("rakamak"),
royalauth("royalauth"),
vauth("vauth");
String name; String name;

View File

@ -34,7 +34,8 @@ public class EmailCommand implements CommandExecutor {
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
return true; return true;
} }
@ -60,14 +61,18 @@ public class EmailCommand implements CommandExecutor {
return true; return true;
} }
if (Settings.getmaxRegPerEmail > 0) { if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(sender, "authme.allow2accounts") && data.getAllAuthsByEmail(args[1]).size() >= Settings.getmaxRegPerEmail) { if (!plugin.authmePermissible(sender, "authme.allow2accounts")
&& data.getAllAuthsByEmail(args[1]).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg"); m._(player, "max_reg");
return true; return true;
} }
} }
if(args[1].equals(args[2]) && PlayerCache.getInstance().isAuthenticated(name)) { if (args[1].equals(args[2])
&& PlayerCache.getInstance().isAuthenticated(name)) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(name); PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
if (auth.getEmail() == null || (!auth.getEmail().equals("your@email.com") && !auth.getEmail().isEmpty())) { if (auth.getEmail() == null
|| (!auth.getEmail().equals("your@email.com") && !auth
.getEmail().isEmpty())) {
m._(player, "usage_email_change"); m._(player, "usage_email_change");
return true; return true;
} }
@ -98,14 +103,17 @@ public class EmailCommand implements CommandExecutor {
return true; return true;
} }
if (Settings.getmaxRegPerEmail > 0) { if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(sender, "authme.allow2accounts") && data.getAllAuthsByEmail(args[2]).size() >= Settings.getmaxRegPerEmail) { if (!plugin.authmePermissible(sender, "authme.allow2accounts")
&& data.getAllAuthsByEmail(args[2]).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg"); m._(player, "max_reg");
return true; return true;
} }
} }
if (PlayerCache.getInstance().isAuthenticated(name)) { if (PlayerCache.getInstance().isAuthenticated(name)) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(name); PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
if (auth.getEmail() == null || auth.getEmail().equals("your@email.com") || auth.getEmail().isEmpty()) { if (auth.getEmail() == null
|| auth.getEmail().equals("your@email.com")
|| auth.getEmail().isEmpty()) {
m._(player, "usage_email_add"); m._(player, "usage_email_add");
return true; return true;
} }
@ -150,9 +158,11 @@ public class EmailCommand implements CommandExecutor {
return true; return true;
} }
try { try {
RandomString rand = new RandomString(Settings.getRecoveryPassLength); RandomString rand = new RandomString(
Settings.getRecoveryPassLength);
String thePass = rand.nextString(); String thePass = rand.nextString();
String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, thePass, name); String hashnew = PasswordSecurity.getHash(
Settings.getPasswordHash, thePass, name);
PlayerAuth auth = null; PlayerAuth auth = null;
if (PlayerCache.getInstance().isAuthenticated(name)) { if (PlayerCache.getInstance().isAuthenticated(name)) {
auth = PlayerCache.getInstance().getAuth(name); auth = PlayerCache.getInstance().getAuth(name);
@ -162,12 +172,16 @@ public class EmailCommand implements CommandExecutor {
m._(player, "unknown_user"); m._(player, "unknown_user");
return true; return true;
} }
if (Settings.getmailAccount.equals("") || Settings.getmailAccount.isEmpty()) { if (Settings.getmailAccount.equals("")
|| Settings.getmailAccount.isEmpty()) {
m._(player, "error"); m._(player, "error");
return true; return true;
} }
if (!args[1].equalsIgnoreCase(auth.getEmail()) || args[1].equalsIgnoreCase("your@email.com") || auth.getEmail().equalsIgnoreCase("your@email.com")) { if (!args[1].equalsIgnoreCase(auth.getEmail())
|| args[1].equalsIgnoreCase("your@email.com")
|| auth.getEmail().equalsIgnoreCase(
"your@email.com")) {
m._(player, "email_invalid"); m._(player, "email_invalid");
return true; return true;
} }
@ -177,7 +191,8 @@ public class EmailCommand implements CommandExecutor {
finalauth.setHash(hashnew); finalauth.setHash(hashnew);
data.updatePassword(auth); data.updatePassword(auth);
} else { } else {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { Bukkit.getScheduler().runTaskAsynchronously(plugin,
new Runnable() {
@Override @Override
public void run() { public void run() {
finalauth.setHash(finalhashnew); finalauth.setHash(finalhashnew);

View File

@ -8,7 +8,6 @@ import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.settings.Messages; import fr.xephi.authme.settings.Messages;
public class LoginCommand implements CommandExecutor { public class LoginCommand implements CommandExecutor {
private AuthMe plugin; private AuthMe plugin;
@ -19,7 +18,8 @@ public class LoginCommand implements CommandExecutor {
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, final String[] args) { public boolean onCommand(CommandSender sender, Command cmnd, String label,
final String[] args) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
return true; return true;
} }

View File

@ -27,7 +27,6 @@ import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask; import fr.xephi.authme.task.TimeoutTask;
public class LogoutCommand implements CommandExecutor { public class LogoutCommand implements CommandExecutor {
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
@ -42,7 +41,8 @@ public class LogoutCommand implements CommandExecutor {
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
return true; return true;
} }
@ -73,45 +73,54 @@ public class LogoutCommand implements CommandExecutor {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawnLoc = plugin.getSpawnLocation(player); Location spawnLoc = plugin.getSpawnLocation(player);
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, spawnLoc); AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player,
spawnLoc);
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (tpEvent.getTo() != null) if (tpEvent.getTo() != null) player.teleport(tpEvent.getTo());
player.teleport(tpEvent.getTo());
} }
} }
if (LimboCache.getInstance().hasLimboPlayer(name)) if (LimboCache.getInstance().hasLimboPlayer(name)) LimboCache
LimboCache.getInstance().deleteLimboPlayer(name); .getInstance().deleteLimboPlayer(name);
LimboCache.getInstance().addLimboPlayer(player); LimboCache.getInstance().addLimboPlayer(player);
utils.setGroup(player, groupType.NOTLOGGEDIN); utils.setGroup(player, groupType.NOTLOGGEDIN);
if (Settings.protectInventoryBeforeLogInEnabled) { if (Settings.protectInventoryBeforeLogInEnabled) {
player.getInventory().clear(); player.getInventory().clear();
// create cache file for handling lost of inventories on unlogged in status // create cache file for handling lost of inventories on unlogged in
DataFileCache playerData = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(),LimboCache.getInstance().getLimboPlayer(name).getArmour()); // status
playerBackup.createCache(name, playerData, LimboCache.getInstance().getLimboPlayer(name).getGroup(),LimboCache.getInstance().getLimboPlayer(name).getOperator(),LimboCache.getInstance().getLimboPlayer(name).isFlying()); DataFileCache playerData = new DataFileCache(LimboCache
.getInstance().getLimboPlayer(name).getInventory(),
LimboCache.getInstance().getLimboPlayer(name).getArmour());
playerBackup.createCache(name, playerData, LimboCache.getInstance()
.getLimboPlayer(name).getGroup(), LimboCache.getInstance()
.getLimboPlayer(name).getOperator(), LimboCache
.getInstance().getLimboPlayer(name).isFlying());
} }
int delay = Settings.getRegistrationTimeout * 20; int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval; int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = sender.getServer().getScheduler(); BukkitScheduler sched = sender.getServer().getScheduler();
if (delay != 0) { if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay); int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(
plugin, name), delay);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
} }
int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("login_msg"), interval)); int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask(
plugin, name, m._("login_msg"), interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
try { try {
if (player.isInsideVehicle()) if (player.isInsideVehicle()) player.getVehicle().eject();
player.getVehicle().eject();
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
} }
if (Settings.applyBlindEffect) if (Settings.applyBlindEffect) player.addPotionEffect(new PotionEffect(
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); PotionEffectType.BLINDNESS,
Settings.getRegistrationTimeout * 20, 2));
m._(player, "logout"); m._(player, "logout");
ConsoleLogger.info(player.getDisplayName() + " logged out"); ConsoleLogger.info(player.getDisplayName() + " logged out");
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " logged out!")); plugin.notifications.showNotification(new Notification("[AuthMe] "
+ player.getName() + " logged out!"));
} }
return true; return true;
} }

View File

@ -10,7 +10,6 @@ import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.settings.Messages; import fr.xephi.authme.settings.Messages;
/** /**
* *
* @author stefano * @author stefano
@ -25,21 +24,24 @@ public class PasspartuCommand implements CommandExecutor {
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) { if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
m._(sender, "no_perm"); m._(sender, "no_perm");
return true; return true;
} }
if (PlayerCache.getInstance().isAuthenticated(sender.getName().toLowerCase())) { if (PlayerCache.getInstance().isAuthenticated(
sender.getName().toLowerCase())) {
return true; return true;
} }
if ((sender instanceof Player) && args.length == 1) { if ((sender instanceof Player) && args.length == 1) {
if (utils.readToken(args[0])) { if (utils.readToken(args[0])) {
// bypass login! // bypass login!
plugin.management.performLogin((Player) sender, "dontneed", true); plugin.management.performLogin((Player) sender, "dontneed",
true);
return true; return true;
} }
sender.sendMessage("Time is expired or Token is Wrong!"); sender.sendMessage("Time is expired or Token is Wrong!");

View File

@ -11,7 +11,6 @@ import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages; import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class RegisterCommand implements CommandExecutor { public class RegisterCommand implements CommandExecutor {
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
@ -23,7 +22,8 @@ public class RegisterCommand implements CommandExecutor {
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
sender.sendMessage("Player Only! Use 'authme register <playername> <password>' instead"); sender.sendMessage("Player Only! Use 'authme register <playername> <password>' instead");
return true; return true;
@ -57,12 +57,13 @@ public class RegisterCommand implements CommandExecutor {
plugin.management.performRegister(player, thePass, email); plugin.management.performRegister(player, thePass, email);
return true; return true;
} }
if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2)) { if (args.length == 0
|| (Settings.getEnablePasswordVerifier && args.length < 2)) {
m._(player, "usage_reg"); m._(player, "usage_reg");
return true; return true;
} }
if (args.length > 1 && Settings.getEnablePasswordVerifier) if (args.length > 1 && Settings.getEnablePasswordVerifier) if (!args[0]
if(!args[0].equals(args[1])) { .equals(args[1])) {
m._(player, "password_error"); m._(player, "password_error");
return true; return true;
} }

View File

@ -29,7 +29,6 @@ import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask; import fr.xephi.authme.task.TimeoutTask;
public class UnregisterCommand implements CommandExecutor { public class UnregisterCommand implements CommandExecutor {
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
@ -43,7 +42,8 @@ public class UnregisterCommand implements CommandExecutor {
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmnd, String label,
String[] args) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
return true; return true;
} }
@ -66,16 +66,20 @@ public class UnregisterCommand implements CommandExecutor {
return true; return true;
} }
try { try {
if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) { if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache
.getInstance().getAuth(name).getHash(), player.getName())) {
if (!database.removeAuth(name)) { if (!database.removeAuth(name)) {
player.sendMessage("error"); player.sendMessage("error");
return true; return true;
} }
if (Settings.isForcedRegistrationEnabled) { if (Settings.isForcedRegistrationEnabled) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled
&& !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(player); Location spawn = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false); SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(
plugin.getServer().getPluginManager().callEvent(tpEvent); player, player.getLocation(), spawn, false);
plugin.getServer().getPluginManager()
.callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }
@ -83,47 +87,72 @@ public class UnregisterCommand implements CommandExecutor {
player.getInventory().setContents(new ItemStack[36]); player.getInventory().setContents(new ItemStack[36]);
player.getInventory().setArmorContents(new ItemStack[4]); player.getInventory().setArmorContents(new ItemStack[4]);
player.saveData(); player.saveData();
PlayerCache.getInstance().removePlayer(player.getName().toLowerCase()); PlayerCache.getInstance().removePlayer(
if (!Settings.getRegisteredGroup.isEmpty()) player.getName().toLowerCase());
Utils.getInstance().setGroup(player, groupType.UNREGISTERED); if (!Settings.getRegisteredGroup.isEmpty()) Utils
.getInstance().setGroup(player,
groupType.UNREGISTERED);
LimboCache.getInstance().addLimboPlayer(player); LimboCache.getInstance().addLimboPlayer(player);
int delay = Settings.getRegistrationTimeout * 20; int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval; int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = sender.getServer().getScheduler(); BukkitScheduler sched = sender.getServer().getScheduler();
if (delay != 0) { if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay); int id = sched.scheduleSyncDelayedTask(plugin,
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); new TimeoutTask(plugin, name), delay);
LimboCache.getInstance().getLimboPlayer(name)
.setTimeoutTaskId(id);
} }
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("reg_msg"), interval))); LimboCache
.getInstance()
.getLimboPlayer(name)
.setMessageTaskId(
sched.scheduleSyncDelayedTask(
plugin,
new MessageTask(plugin, name, m
._("reg_msg"), interval)));
m._(player, "unregistered"); m._(player, "unregistered");
ConsoleLogger.info(player.getDisplayName() + " unregistered himself"); ConsoleLogger.info(player.getDisplayName()
+ " unregistered himself");
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " unregistered himself!")); plugin.notifications.showNotification(new Notification(
"[AuthMe] " + player.getName()
+ " unregistered himself!"));
} }
return true; return true;
} }
if (!Settings.unRegisteredGroup.isEmpty()) { if (!Settings.unRegisteredGroup.isEmpty()) {
Utils.getInstance().setGroup(player, Utils.groupType.UNREGISTERED); Utils.getInstance().setGroup(player,
Utils.groupType.UNREGISTERED);
} }
PlayerCache.getInstance().removePlayer(player.getName().toLowerCase()); PlayerCache.getInstance().removePlayer(
// check if Player cache File Exist and delete it, preventing duplication of items player.getName().toLowerCase());
// check if Player cache File Exist and delete it, preventing
// duplication of items
if (playerCache.doesCacheExist(name)) { if (playerCache.doesCacheExist(name)) {
playerCache.removeCache(name); playerCache.removeCache(name);
} }
if (Settings.applyBlindEffect) if (Settings.applyBlindEffect) player
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); .addPotionEffect(new PotionEffect(
PotionEffectType.BLINDNESS,
Settings.getRegistrationTimeout * 20, 2));
m._(player, "unregistered"); m._(player, "unregistered");
ConsoleLogger.info(player.getDisplayName() + " unregistered himself"); ConsoleLogger.info(player.getDisplayName()
+ " unregistered himself");
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " unregistered himself!")); plugin.notifications.showNotification(new Notification(
"[AuthMe] " + player.getName()
+ " unregistered himself!"));
} }
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(player); Location spawn = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false); SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player,
player.getLocation(), spawn, false);
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { if (!tpEvent.getTo().getWorld()
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); .getChunkAt(tpEvent.getTo()).isLoaded()) {
tpEvent.getTo().getWorld()
.getChunkAt(tpEvent.getTo()).load();
} }
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }

View File

@ -23,7 +23,8 @@ public class CrazyLoginConverter implements Converter {
public DataSource database; public DataSource database;
public CommandSender sender; public CommandSender sender;
public CrazyLoginConverter (AuthMe instance, DataSource database, CommandSender sender) { public CrazyLoginConverter(AuthMe instance, DataSource database,
CommandSender sender) {
this.instance = instance; this.instance = instance;
this.database = database; this.database = database;
this.sender = sender; this.sender = sender;
@ -40,9 +41,11 @@ public class CrazyLoginConverter implements Converter {
public void run() { public void run() {
fileName = Settings.crazyloginFileName; fileName = Settings.crazyloginFileName;
try { try {
source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName); source = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + fileName);
if (!source.exists()) { if (!source.exists()) {
sender.sendMessage("Error while trying to import datas, please put " + fileName + " in AuthMe folder!"); sender.sendMessage("Error while trying to import datas, please put "
+ fileName + " in AuthMe folder!");
return; return;
} }
source.createNewFile(); source.createNewFile();
@ -52,22 +55,23 @@ public class CrazyLoginConverter implements Converter {
while ((line = users.readLine()) != null) { while ((line = users.readLine()) != null) {
if (line.contains("|")) { if (line.contains("|")) {
String[] args = line.split("\\|"); String[] args = line.split("\\|");
if (args.length < 2) if (args.length < 2) continue;
continue; if (args[0].equalsIgnoreCase("name")) continue;
if (args[0].equalsIgnoreCase("name"))
continue;
String player = args[0].toLowerCase(); String player = args[0].toLowerCase();
String psw = args[1]; String psw = args[1];
try { try {
if (player != null && psw != null) { if (player != null && psw != null) {
PlayerAuth auth = new PlayerAuth(player, psw, "127.0.0.1", System.currentTimeMillis()); PlayerAuth auth = new PlayerAuth(player, psw,
"127.0.0.1", System.currentTimeMillis());
database.saveAuth(auth); database.saveAuth(auth);
} }
} catch (Exception e) {} } catch (Exception e) {
}
} }
} }
users.close(); users.close();
ConsoleLogger.info("CrazyLogin database has been imported correctly"); ConsoleLogger
.info("CrazyLogin database has been imported correctly");
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) { } catch (IOException ex) {

View File

@ -12,7 +12,6 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
/** /**
* *
* @author Xephi59 * @author Xephi59
@ -52,48 +51,78 @@ public class FlatToSql implements Converter {
@Override @Override
public void run() { public void run() {
try { try {
source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db"); source = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + "auths.db");
source.createNewFile(); source.createNewFile();
output = new File(AuthMe.getInstance().getDataFolder() + File.separator + "authme.sql"); output = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + "authme.sql");
BufferedReader br = null; BufferedReader br = null;
BufferedWriter sql = null; BufferedWriter sql = null;
br = new BufferedReader(new FileReader(source)); br = new BufferedReader(new FileReader(source));
sql = new BufferedWriter(new FileWriter(output)); sql = new BufferedWriter(new FileWriter(output));
String createDB = "CREATE TABLE IF NOT EXISTS " + tableName + " (" String createDB = "CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ columnID + " INTEGER AUTO_INCREMENT," + columnID + " INTEGER AUTO_INCREMENT," + columnName
+ columnName + " VARCHAR(255) NOT NULL UNIQUE," + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword
+ columnPassword + " VARCHAR(255) NOT NULL," + " VARCHAR(255) NOT NULL," + columnIp
+ columnIp + " VARCHAR(40) NOT NULL DEFAULT '127.0.0.1'," + " VARCHAR(40) NOT NULL DEFAULT '127.0.0.1',"
+ columnLastLogin + " BIGINT NOT NULL DEFAULT '" + System.currentTimeMillis() + "'," + columnLastLogin + " BIGINT NOT NULL DEFAULT '"
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + System.currentTimeMillis() + "'," + lastlocX
+ lastlocY + " DOUBLE NOT NULL DEFAULT '0.0'," + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY
+ lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ
+ lastlocWorld + " VARCHAR(255) DEFAULT 'world'," + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld
+ columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + " VARCHAR(255) DEFAULT 'world'," + columnEmail
+ columnLogged + " SMALLINT NOT NULL DEFAULT '0'," + " VARCHAR(255) DEFAULT 'your@email.com'," + columnLogged
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));"; + " SMALLINT NOT NULL DEFAULT '0',"
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID
+ "));";
sql.write(createDB); sql.write(createDB);
String line; String line;
String newline; String newline;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
sql.newLine(); sql.newLine();
String[] args = line.split(":"); String[] args = line.split(":");
if (args.length == 4) if (args.length == 4) newline = "INSERT INTO " + tableName
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", 0.0, 0.0, 0.0, 'world', 'your@email.com', 0);"; + "(" + columnName + "," + columnPassword + ","
else if (args.length == 7) + columnIp + "," + columnLastLogin + "," + lastlocX
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", 'world', 'your@email.com', 0);"; + "," + lastlocY + "," + lastlocZ + "," + lastlocWorld
else if (args.length == 8) + "," + columnEmail + "," + columnLogged
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", '" + args[7] + "', 'your@email.com', 0);"; + ") VALUES ('" + args[0] + "', '" + args[1] + "', '"
else if (args.length == 9) + args[2] + "', " + args[3]
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", '" + args[7] + "', '" + args[8] + "', 0);"; + ", 0.0, 0.0, 0.0, 'world', 'your@email.com', 0);";
else else if (args.length == 7) newline = "INSERT INTO " + tableName
newline = ""; + "(" + columnName + "," + columnPassword + ","
if (newline != "") + columnIp + "," + columnLastLogin + "," + lastlocX
sql.write(newline); + "," + lastlocY + "," + lastlocZ + "," + lastlocWorld
+ "," + columnEmail + "," + columnLogged
+ ") VALUES ('" + args[0] + "', '" + args[1] + "', '"
+ args[2] + "', " + args[3] + ", " + args[4] + ", "
+ args[5] + ", " + args[6]
+ ", 'world', 'your@email.com', 0);";
else if (args.length == 8) newline = "INSERT INTO " + tableName
+ "(" + columnName + "," + columnPassword + ","
+ columnIp + "," + columnLastLogin + "," + lastlocX
+ "," + lastlocY + "," + lastlocZ + "," + lastlocWorld
+ "," + columnEmail + "," + columnLogged
+ ") VALUES ('" + args[0] + "', '" + args[1] + "', '"
+ args[2] + "', " + args[3] + ", " + args[4] + ", "
+ args[5] + ", " + args[6] + ", '" + args[7]
+ "', 'your@email.com', 0);";
else if (args.length == 9) newline = "INSERT INTO " + tableName
+ "(" + columnName + "," + columnPassword + ","
+ columnIp + "," + columnLastLogin + "," + lastlocX
+ "," + lastlocY + "," + lastlocZ + "," + lastlocWorld
+ "," + columnEmail + "," + columnLogged
+ ") VALUES ('" + args[0] + "', '" + args[1] + "', '"
+ args[2] + "', " + args[3] + ", " + args[4] + ", "
+ args[5] + ", " + args[6] + ", '" + args[7] + "', '"
+ args[8] + "', 0);";
else newline = "";
if (newline != "") sql.write(newline);
} }
sql.close(); sql.close();
br.close(); br.close();
ConsoleLogger.info("The FlatFile has been converted to authme.sql file"); ConsoleLogger
.info("The FlatFile has been converted to authme.sql file");
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) { } catch (IOException ex) {

View File

@ -18,7 +18,6 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class FlatToSqlite implements Converter { public class FlatToSqlite implements Converter {
public CommandSender sender; public CommandSender sender;
@ -57,20 +56,24 @@ public class FlatToSqlite implements Converter {
columnEmail = Settings.getMySQLColumnEmail; columnEmail = Settings.getMySQLColumnEmail;
columnID = Settings.getMySQLColumnId; columnID = Settings.getMySQLColumnId;
ConsoleLogger.info("Converting FlatFile to SQLite ..."); ConsoleLogger.info("Converting FlatFile to SQLite ...");
if (new File(AuthMe.getInstance().getDataFolder() + File.separator + database + ".db").exists()) { if (new File(AuthMe.getInstance().getDataFolder() + File.separator
sender.sendMessage("The Database " + database + ".db can't be created cause the file already exist"); + database + ".db").exists()) {
sender.sendMessage("The Database " + database
+ ".db can't be created cause the file already exist");
return; return;
} }
try { try {
connect(); connect();
setup(); setup();
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.showError("Problem while trying to convert to sqlite !"); ConsoleLogger
.showError("Problem while trying to convert to sqlite !");
sender.sendMessage("Problem while trying to convert to sqlite !"); sender.sendMessage("Problem while trying to convert to sqlite !");
return; return;
} }
try { try {
source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db"); source = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + "auths.db");
source.createNewFile(); source.createNewFile();
BufferedReader br = new BufferedReader(new FileReader(source)); BufferedReader br = new BufferedReader(new FileReader(source));
String line; String line;
@ -78,24 +81,35 @@ public class FlatToSqlite implements Converter {
String newline; String newline;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
String[] args = line.split(":"); String[] args = line.split(":");
if (args.length == 4) if (args.length == 4) newline = "INSERT INTO " + tableName
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", 0, 0, 0, 'world', 'your@email.com');"; + " VALUES (" + i + ", '" + args[0] + "', '" + args[1]
else if (args.length == 7) + "', '" + args[2] + "', " + args[3]
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", 'world', 'your@email.com');"; + ", 0, 0, 0, 'world', 'your@email.com');";
else if (args.length == 8) else if (args.length == 7) newline = "INSERT INTO " + tableName
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", '" + args[7] + "', 'your@email.com');"; + " VALUES (" + i + ", '" + args[0] + "', '" + args[1]
else if (args.length == 9) + "', '" + args[2] + "', " + args[3] + ", " + args[4]
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + ", '" + args[7] + "', '" + args[8] + "');"; + ", " + args[5] + ", " + args[6]
else + ", 'world', 'your@email.com');";
newline = ""; else if (args.length == 8) newline = "INSERT INTO " + tableName
if (newline != "") + " VALUES (" + i + ", '" + args[0] + "', '" + args[1]
saveAuth(newline); + "', '" + args[2] + "', " + args[3] + ", " + args[4]
+ ", " + args[5] + ", " + args[6] + ", '" + args[7]
+ "', 'your@email.com');";
else if (args.length == 9) newline = "INSERT INTO " + tableName
+ " VALUES (" + i + ", '" + args[0] + "', '" + args[1]
+ "', '" + args[2] + "', " + args[3] + ", " + args[4]
+ ", " + args[5] + ", " + args[6] + ", '" + args[7]
+ "', '" + args[8] + "');";
else newline = "";
if (newline != "") saveAuth(newline);
i = i + 1; i = i + 1;
} }
br.close(); br.close();
ConsoleLogger.info("The FlatFile has been converted to " + database + ".db file"); ConsoleLogger.info("The FlatFile has been converted to " + database
+ ".db file");
close(); close();
sender.sendMessage("The FlatFile has been converted to " + database + ".db file"); sender.sendMessage("The FlatFile has been converted to " + database
+ ".db file");
return; return;
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
@ -106,10 +120,12 @@ public class FlatToSqlite implements Converter {
return; return;
} }
private synchronized static void connect() throws ClassNotFoundException, SQLException { private synchronized static void connect() throws ClassNotFoundException,
SQLException {
Class.forName("org.sqlite.JDBC"); Class.forName("org.sqlite.JDBC");
ConsoleLogger.info("SQLite driver loaded"); ConsoleLogger.info("SQLite driver loaded");
con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/"+database+".db"); con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/"
+ database + ".db");
} }
private synchronized static void setup() throws SQLException { private synchronized static void setup() throws SQLException {
@ -118,18 +134,19 @@ public class FlatToSqlite implements Converter {
try { try {
st = con.createStatement(); st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ columnID + " INTEGER AUTO_INCREMENT," + columnID + " INTEGER AUTO_INCREMENT," + columnName
+ columnName + " VARCHAR(255) NOT NULL UNIQUE," + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword
+ columnPassword + " VARCHAR(255) NOT NULL," + " VARCHAR(255) NOT NULL," + columnIp
+ columnIp + " VARCHAR(40) NOT NULL," + " VARCHAR(40) NOT NULL," + columnLastLogin + " BIGINT,"
+ columnLastLogin + " BIGINT," + lastlocX + " smallint(6) DEFAULT '0'," + lastlocY
+ lastlocX + " smallint(6) DEFAULT '0'," + " smallint(6) DEFAULT '0'," + lastlocZ
+ lastlocY + " smallint(6) DEFAULT '0'," + " smallint(6) DEFAULT '0'," + lastlocWorld
+ lastlocZ + " smallint(6) DEFAULT '0'," + " VARCHAR(255) DEFAULT 'world'," + columnEmail
+ lastlocWorld + " VARCHAR(255) DEFAULT 'world'," + " VARCHAR(255) DEFAULT 'your@email.com',"
+ columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));"); + "));");
rs = con.getMetaData().getColumns(null, null, tableName, columnPassword); rs = con.getMetaData().getColumns(null, null, tableName,
columnPassword);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnPassword + " VARCHAR(255) NOT NULL;"); + columnPassword + " VARCHAR(255) NOT NULL;");
@ -141,7 +158,8 @@ public class FlatToSqlite implements Converter {
+ columnIp + " VARCHAR(40) NOT NULL;"); + columnIp + " VARCHAR(40) NOT NULL;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin); rs = con.getMetaData().getColumns(null, null, tableName,
columnLastLogin);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnLastLogin + " BIGINT;"); + columnLastLogin + " BIGINT;");
@ -149,19 +167,29 @@ public class FlatToSqlite implements Converter {
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " smallint(6) NOT NULL DEFAULT '0'; " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ "ALTER TABLE " + tableName + " ADD COLUMN " + lastlocY + " smallint(6) NOT NULL DEFAULT '0'; " + lastlocX + " smallint(6) NOT NULL DEFAULT '0'; "
+ "ALTER TABLE " + tableName + " ADD COLUMN " + lastlocZ + " smallint(6) NOT NULL DEFAULT '0';"); + "ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocY + " smallint(6) NOT NULL DEFAULT '0'; "
+ "ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocZ + " smallint(6) NOT NULL DEFAULT '0';");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld); rs = con.getMetaData().getColumns(null, null, tableName,
lastlocWorld);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER " + lastlocZ + ";"); st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocWorld
+ " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER "
+ lastlocZ + ";");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnEmail); rs = con.getMetaData().getColumns(null, null, tableName,
columnEmail);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';"); st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com';");
} }
} finally { } finally {
close(rs); close(rs);

View File

@ -29,7 +29,8 @@ public class RakamakConverter implements Converter {
public DataSource database; public DataSource database;
public CommandSender sender; public CommandSender sender;
public RakamakConverter (AuthMe instance, DataSource database, CommandSender sender) { public RakamakConverter(AuthMe instance, DataSource database,
CommandSender sender) {
this.instance = instance; this.instance = instance;
this.database = database; this.database = database;
this.sender = sender; this.sender = sender;
@ -54,8 +55,10 @@ public class RakamakConverter implements Converter {
HashMap<String, String> playerIP = new HashMap<String, String>(); HashMap<String, String> playerIP = new HashMap<String, String>();
HashMap<String, String> playerPSW = new HashMap<String, String>(); HashMap<String, String> playerPSW = new HashMap<String, String>();
try { try {
source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName); source = new File(AuthMe.getInstance().getDataFolder()
ipfiles = new File(AuthMe.getInstance().getDataFolder() + File.separator + ipFileName); + File.separator + fileName);
ipfiles = new File(AuthMe.getInstance().getDataFolder()
+ File.separator + ipFileName);
source.createNewFile(); source.createNewFile();
ipfiles.createNewFile(); ipfiles.createNewFile();
BufferedReader users = null; BufferedReader users = null;
@ -77,7 +80,8 @@ public class RakamakConverter implements Converter {
if (line.contains("=")) { if (line.contains("=")) {
String[] arguments = line.split("="); String[] arguments = line.split("=");
try { try {
playerPSW.put(arguments[0],PasswordSecurity.getHash(hash, arguments[1], arguments[0])); playerPSW.put(arguments[0], PasswordSecurity.getHash(
hash, arguments[1], arguments[0]));
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
} }
@ -93,9 +97,10 @@ public class RakamakConverter implements Converter {
} else { } else {
ip = "127.0.0.1"; ip = "127.0.0.1";
} }
PlayerAuth auth = new PlayerAuth(player, psw, ip, System.currentTimeMillis()); PlayerAuth auth = new PlayerAuth(player, psw, ip,
if (PasswordSecurity.userSalt.containsKey(player)) System.currentTimeMillis());
auth.setSalt(PasswordSecurity.userSalt.get(player)); if (PasswordSecurity.userSalt.containsKey(player)) auth
.setSalt(PasswordSecurity.userSalt.get(player));
database.saveAuth(auth); database.saveAuth(auth);
} }
ConsoleLogger.info("Rakamak database has been imported correctly"); ConsoleLogger.info("Rakamak database has been imported correctly");

View File

@ -25,16 +25,19 @@ public class RoyalAuthConverter implements Converter {
try { try {
String name = o.getName().toLowerCase(); String name = o.getName().toLowerCase();
String separator = File.separator; String separator = File.separator;
File file = new File("." + separator + "plugins" + separator + "RoyalAuth" + separator + "userdata" + separator + name + ".yml"); File file = new File("." + separator + "plugins" + separator
if (data.isAuthAvailable(name)) + "RoyalAuth" + separator + "userdata" + separator
continue; + name + ".yml");
if (!file.exists()) if (data.isAuthAvailable(name)) continue;
continue; if (!file.exists()) continue;
RoyalAuthYamlReader ra = new RoyalAuthYamlReader(file); RoyalAuthYamlReader ra = new RoyalAuthYamlReader(file);
PlayerAuth auth = new PlayerAuth(name, ra.getHash(), "127.0.0.1", ra.getLastLogin(), "your@email.com", o.getName()); PlayerAuth auth = new PlayerAuth(name, ra.getHash(),
"127.0.0.1", ra.getLastLogin(), "your@email.com",
o.getName());
data.saveAuth(auth); data.saveAuth(auth);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.showError("Error while trying to import "+ o.getName() + " RoyalAuth datas"); ConsoleLogger.showError("Error while trying to import "
+ o.getName() + " RoyalAuth datas");
} }
} }
} }

View File

@ -25,7 +25,8 @@ public class newxAuthToFlat {
public DataSource database; public DataSource database;
public CommandSender sender; public CommandSender sender;
public newxAuthToFlat(AuthMe instance, DataSource database, CommandSender sender) { public newxAuthToFlat(AuthMe instance, DataSource database,
CommandSender sender) {
this.instance = instance; this.instance = instance;
this.database = database; this.database = database;
this.sender = sender; this.sender = sender;
@ -50,7 +51,8 @@ public class newxAuthToFlat {
String pl = getIdPlayer(id); String pl = getIdPlayer(id);
String psw = getPassword(id); String psw = getPassword(id);
if (psw != null && !psw.isEmpty() && pl != null) { if (psw != null && !psw.isEmpty() && pl != null) {
PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0, "your@email.com", API.getPlayerRealName(pl)); PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0,
"your@email.com", API.getPlayerRealName(pl));
database.saveAuth(auth); database.saveAuth(auth);
} }
} }
@ -63,17 +65,19 @@ public class newxAuthToFlat {
public String getIdPlayer(int id) { public String getIdPlayer(int id) {
String realPass = ""; String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection(); Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format("SELECT `playername` FROM `%s` WHERE `id` = ?", String sql = String.format(
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT)); "SELECT `playername` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
ps.setInt(1, id); ps.setInt(1, id);
rs = ps.executeQuery(); rs = ps.executeQuery();
if (!rs.next()) if (!rs.next()) return null;
return null;
realPass = rs.getString("playername").toLowerCase(); realPass = rs.getString("playername").toLowerCase();
} catch (SQLException e) { } catch (SQLException e) {
xAuthLog.severe("Failed to retrieve name for account: " + id, e); xAuthLog.severe("Failed to retrieve name for account: " + id, e);
@ -86,12 +90,13 @@ public class newxAuthToFlat {
public List<Integer> getXAuthPlayers() { public List<Integer> getXAuthPlayers() {
List<Integer> xP = new ArrayList<Integer>(); List<Integer> xP = new ArrayList<Integer>();
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection(); Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format("SELECT * FROM `%s`", String sql = String.format("SELECT * FROM `%s`", xAuth.getPlugin()
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT)); .getDatabaseController().getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
rs = ps.executeQuery(); rs = ps.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -108,20 +113,23 @@ public class newxAuthToFlat {
public String getPassword(int accountId) { public String getPassword(int accountId) {
String realPass = ""; String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection(); Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format("SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?", String sql = String.format(
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT)); "SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
ps.setInt(1, accountId); ps.setInt(1, accountId);
rs = ps.executeQuery(); rs = ps.executeQuery();
if (!rs.next()) if (!rs.next()) return null;
return null;
realPass = rs.getString("password"); realPass = rs.getString("password");
} catch (SQLException e) { } catch (SQLException e) {
xAuthLog.severe("Failed to retrieve password hash for account: " + accountId, e); xAuthLog.severe("Failed to retrieve password hash for account: "
+ accountId, e);
return null; return null;
} finally { } finally {
xAuth.getPlugin().getDatabaseController().close(conn, ps, rs); xAuth.getPlugin().getDatabaseController().close(conn, ps, rs);

View File

@ -19,7 +19,6 @@ import fr.xephi.authme.api.API;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
/** /**
* *
* @author Xephi59 * @author Xephi59
@ -30,7 +29,8 @@ public class oldxAuthToFlat {
public DataSource database; public DataSource database;
public CommandSender sender; public CommandSender sender;
public oldxAuthToFlat(AuthMe instance, DataSource database, CommandSender sender) { public oldxAuthToFlat(AuthMe instance, DataSource database,
CommandSender sender) {
this.instance = instance; this.instance = instance;
this.database = database; this.database = database;
this.sender = sender; this.sender = sender;
@ -55,7 +55,8 @@ public class oldxAuthToFlat {
String pl = getIdPlayer(id); String pl = getIdPlayer(id);
String psw = getPassword(id); String psw = getPassword(id);
if (psw != null && !psw.isEmpty() && pl != null) { if (psw != null && !psw.isEmpty() && pl != null) {
PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0, "your@email.com", API.getPlayerRealName(pl)); PlayerAuth auth = new PlayerAuth(pl, psw, "198.18.0.1", 0,
"your@email.com", API.getPlayerRealName(pl));
database.saveAuth(auth); database.saveAuth(auth);
} }
} }
@ -68,17 +69,19 @@ public class oldxAuthToFlat {
public String getIdPlayer(int id) { public String getIdPlayer(int id) {
String realPass = ""; String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection(); Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format("SELECT `playername` FROM `%s` WHERE `id` = ?", String sql = String.format(
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT)); "SELECT `playername` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
ps.setInt(1, id); ps.setInt(1, id);
rs = ps.executeQuery(); rs = ps.executeQuery();
if (!rs.next()) if (!rs.next()) return null;
return null;
realPass = rs.getString("playername").toLowerCase(); realPass = rs.getString("playername").toLowerCase();
} catch (SQLException e) { } catch (SQLException e) {
xAuthLog.severe("Failed to retrieve name for account: " + id, e); xAuthLog.severe("Failed to retrieve name for account: " + id, e);
@ -91,12 +94,13 @@ public class oldxAuthToFlat {
public List<Integer> getXAuthPlayers() { public List<Integer> getXAuthPlayers() {
List<Integer> xP = new ArrayList<Integer>(); List<Integer> xP = new ArrayList<Integer>();
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection(); Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format("SELECT * FROM `%s`", String sql = String.format("SELECT * FROM `%s`", xAuth.getPlugin()
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT)); .getDatabaseController().getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
rs = ps.executeQuery(); rs = ps.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -113,20 +117,23 @@ public class oldxAuthToFlat {
public String getPassword(int accountId) { public String getPassword(int accountId) {
String realPass = ""; String realPass = "";
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection(); Connection conn = xAuth.getPlugin().getDatabaseController()
.getConnection();
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
String sql = String.format("SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?", String sql = String.format(
xAuth.getPlugin().getDatabaseController().getTable(Table.ACCOUNT)); "SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?",
xAuth.getPlugin().getDatabaseController()
.getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql); ps = conn.prepareStatement(sql);
ps.setInt(1, accountId); ps.setInt(1, accountId);
rs = ps.executeQuery(); rs = ps.executeQuery();
if (!rs.next()) if (!rs.next()) return null;
return null;
realPass = rs.getString("password"); realPass = rs.getString("password");
} catch (SQLException e) { } catch (SQLException e) {
xAuthLog.severe("Failed to retrieve password hash for account: " + accountId, e); xAuthLog.severe("Failed to retrieve password hash for account: "
+ accountId, e);
return null; return null;
} finally { } finally {
xAuth.getPlugin().getDatabaseController().close(conn, ps, rs); xAuth.getPlugin().getDatabaseController().close(conn, ps, rs);

View File

@ -12,7 +12,8 @@ public class vAuthConverter implements Converter {
public DataSource database; public DataSource database;
public CommandSender sender; public CommandSender sender;
public vAuthConverter(AuthMe plugin, DataSource database, CommandSender sender) { public vAuthConverter(AuthMe plugin, DataSource database,
CommandSender sender) {
this.plugin = plugin; this.plugin = plugin;
this.database = database; this.database = database;
this.sender = sender; this.sender = sender;

View File

@ -20,14 +20,16 @@ public class vAuthFileReader {
public DataSource database; public DataSource database;
public CommandSender sender; public CommandSender sender;
public vAuthFileReader(AuthMe plugin, DataSource database, CommandSender sender) { public vAuthFileReader(AuthMe plugin, DataSource database,
CommandSender sender) {
this.plugin = plugin; this.plugin = plugin;
this.database = database; this.database = database;
this.sender = sender; this.sender = sender;
} }
public void convert() throws IOException { public void convert() throws IOException {
final File file = new File(plugin.getDataFolder().getParent() + "/vAuth/passwords.yml"); final File file = new File(plugin.getDataFolder().getParent()
+ "/vAuth/passwords.yml");
Scanner scanner = null; Scanner scanner = null;
try { try {
scanner = new Scanner(file); scanner = new Scanner(file);
@ -39,16 +41,21 @@ public class vAuthFileReader {
if (isUUIDinstance(password)) { if (isUUIDinstance(password)) {
String pname = null; String pname = null;
try { try {
pname = Bukkit.getOfflinePlayer(UUID.fromString(name)).getName(); pname = Bukkit.getOfflinePlayer(UUID.fromString(name))
.getName();
} catch (Exception e) { } catch (Exception e) {
pname = getName(UUID.fromString(name)); pname = getName(UUID.fromString(name));
} catch (NoSuchMethodError e) { } catch (NoSuchMethodError e) {
pname = getName(UUID.fromString(name)); pname = getName(UUID.fromString(name));
} }
if (pname == null) continue; if (pname == null) continue;
auth = new PlayerAuth(pname.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", pname); auth = new PlayerAuth(pname.toLowerCase(), password,
"127.0.0.1", System.currentTimeMillis(),
"your@email.com", pname);
} else { } else {
auth = new PlayerAuth(name, password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", API.getPlayerRealName(name)); auth = new PlayerAuth(name, password, "127.0.0.1",
System.currentTimeMillis(), "your@email.com",
API.getPlayerRealName(name));
} }
if (auth != null) database.saveAuth(auth); if (auth != null) database.saveAuth(auth);
} }

View File

@ -11,7 +11,8 @@ public class xAuthConverter implements Converter {
public DataSource database; public DataSource database;
public CommandSender sender; public CommandSender sender;
public xAuthConverter(AuthMe plugin, DataSource database, CommandSender sender) { public xAuthConverter(AuthMe plugin, DataSource database,
CommandSender sender) {
this.plugin = plugin; this.plugin = plugin;
this.database = database; this.database = database;
this.sender = sender; this.sender = sender;
@ -21,12 +22,14 @@ public class xAuthConverter implements Converter {
public void run() { public void run() {
try { try {
Class.forName("com.cypherx.xauth.xAuth"); Class.forName("com.cypherx.xauth.xAuth");
oldxAuthToFlat converter = new oldxAuthToFlat(plugin, database, sender); oldxAuthToFlat converter = new oldxAuthToFlat(plugin, database,
sender);
converter.convert(); converter.convert();
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
try { try {
Class.forName("de.luricos.bukkit.xAuth.xAuth"); Class.forName("de.luricos.bukkit.xAuth.xAuth");
newxAuthToFlat converter = new newxAuthToFlat(plugin, database, sender); newxAuthToFlat converter = new newxAuthToFlat(plugin, database,
sender);
converter.convert(); converter.convert();
} catch (ClassNotFoundException ce) { } catch (ClassNotFoundException ce) {
sender.sendMessage("xAuth has not been found, please put xAuth.jar in your plugin folder and restart!"); sender.sendMessage("xAuth has not been found, please put xAuth.jar in your plugin folder and restart!");

View File

@ -9,7 +9,6 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.auth.PlayerCache;
public class CacheDataSource implements DataSource { public class CacheDataSource implements DataSource {
private DataSource source; private DataSource source;
@ -33,8 +32,7 @@ public class CacheDataSource implements DataSource {
return cache.get(user.toLowerCase()); return cache.get(user.toLowerCase());
} else { } else {
PlayerAuth auth = source.getAuth(user.toLowerCase()); PlayerAuth auth = source.getAuth(user.toLowerCase());
if (auth != null) if (auth != null) cache.put(user.toLowerCase(), auth);
cache.put(user.toLowerCase(), auth);
return auth; return auth;
} }
} }
@ -51,8 +49,8 @@ public class CacheDataSource implements DataSource {
@Override @Override
public synchronized boolean updatePassword(PlayerAuth auth) { public synchronized boolean updatePassword(PlayerAuth auth) {
if (source.updatePassword(auth)) { if (source.updatePassword(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get(
cache.get(auth.getNickname()).setHash(auth.getHash()); auth.getNickname()).setHash(auth.getHash());
return true; return true;
} }
return false; return false;
@ -149,8 +147,8 @@ public class CacheDataSource implements DataSource {
@Override @Override
public synchronized boolean updateEmail(PlayerAuth auth) { public synchronized boolean updateEmail(PlayerAuth auth) {
if (source.updateEmail(auth)) { if (source.updateEmail(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get(
cache.get(auth.getNickname()).setEmail(auth.getEmail()); auth.getNickname()).setEmail(auth.getEmail());
return true; return true;
} }
return false; return false;
@ -159,8 +157,8 @@ public class CacheDataSource implements DataSource {
@Override @Override
public synchronized boolean updateSalt(PlayerAuth auth) { public synchronized boolean updateSalt(PlayerAuth auth) {
if (source.updateSalt(auth)) { if (source.updateSalt(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get(
cache.get(auth.getNickname()).setSalt(auth.getSalt()); auth.getNickname()).setSalt(auth.getSalt());
return true; return true;
} }
return false; return false;

View File

@ -4,7 +4,6 @@ import java.util.List;
import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerAuth;
public interface DataSource { public interface DataSource {
public enum DataSourceType { public enum DataSourceType {

View File

@ -17,19 +17,18 @@ import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.settings.PlayersLogs; import fr.xephi.authme.settings.PlayersLogs;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class FlatFileThread extends Thread implements DataSource { public class FlatFileThread extends Thread implements DataSource {
/* file layout: /*
* file layout:
* *
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ:LASTPOSWORLD:EMAIL * PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ:
* LASTPOSWORLD:EMAIL
* *
* Old but compatible: * Old but compatible:
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ:LASTPOSWORLD * PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS * :LASTPOSZ:LASTPOSWORLD PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS
* PLAYERNAME:HASHSUM:IP * PLAYERNAME:HASHSUM:IP PLAYERNAME:HASHSUM
* PLAYERNAME:HASHSUM
*
*/ */
private File source; private File source;
@ -43,8 +42,8 @@ public class FlatFileThread extends Thread implements DataSource {
ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN..."); ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); .getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} }
} }
@ -86,7 +85,11 @@ public class FlatFileThread extends Thread implements DataSource {
BufferedWriter bw = null; BufferedWriter bw = null;
try { try {
bw = new BufferedWriter(new FileWriter(source, true)); bw = new BufferedWriter(new FileWriter(source, true));
bw.write(auth.getNickname() + ":" + auth.getHash() + ":" + auth.getIp() + ":" + auth.getLastLogin() + ":" + auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":" + auth.getQuitLocZ() + ":" + auth.getWorld() + ":" + auth.getEmail() + "\n"); bw.write(auth.getNickname() + ":" + auth.getHash() + ":"
+ auth.getIp() + ":" + auth.getLastLogin() + ":"
+ auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":"
+ auth.getQuitLocZ() + ":" + auth.getWorld() + ":"
+ auth.getEmail() + "\n");
} catch (IOException ex) { } catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
@ -116,23 +119,46 @@ public class FlatFileThread extends Thread implements DataSource {
if (args[0].equals(auth.getNickname())) { if (args[0].equals(auth.getNickname())) {
switch (args.length) { switch (args.length) {
case 4: { case 4: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
case 7: { case 7: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world", "your@email.com", API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), "world",
"your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
case 8: { case 8: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
"your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
case 9: { case 9: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
args[8], API.getPlayerRealName(args[0]));
break; break;
} }
default: { default: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], 0, 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], 0, 0, 0, 0, "world",
"your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
} }
@ -173,23 +199,46 @@ public class FlatFileThread extends Thread implements DataSource {
if (args[0].equals(auth.getNickname())) { if (args[0].equals(auth.getNickname())) {
switch (args.length) { switch (args.length) {
case 4: { case 4: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
case 7: { case 7: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world", "your@email.com", API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), "world",
"your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
case 8: { case 8: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
"your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
case 9: { case 9: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
args[8], API.getPlayerRealName(args[0]));
break; break;
} }
default: { default: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break; break;
} }
} }
@ -228,7 +277,11 @@ public class FlatFileThread extends Thread implements DataSource {
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
String[] args = line.split(":"); String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) { if (args[0].equals(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), auth.getEmail(), API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]), auth.getQuitLocX(),
auth.getQuitLocY(), auth.getQuitLocZ(),
auth.getWorld(), auth.getEmail(),
API.getPlayerRealName(args[0]));
break; break;
} }
} }
@ -428,17 +481,40 @@ public class FlatFileThread extends Thread implements DataSource {
if (args[0].equals(user)) { if (args[0].equals(user)) {
switch (args.length) { switch (args.length) {
case 2: case 2:
return new PlayerAuth(args[0], args[1], "198.18.0.1", 0, "your@email.com", API.getPlayerRealName(args[0])); return new PlayerAuth(args[0], args[1],
"198.18.0.1", 0, "your@email.com",
API.getPlayerRealName(args[0]));
case 3: case 3:
return new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", API.getPlayerRealName(args[0])); return new PlayerAuth(args[0], args[1], args[2], 0,
"your@email.com",
API.getPlayerRealName(args[0]));
case 4: case 4:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", API.getPlayerRealName(args[0])); return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]), "your@email.com",
API.getPlayerRealName(args[0]));
case 7: case 7:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "unavailableworld", "your@email.com", API.getPlayerRealName(args[0])); return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]),
"unavailableworld", "your@email.com",
API.getPlayerRealName(args[0]));
case 8: case 8:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", API.getPlayerRealName(args[0])); return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
"your@email.com",
API.getPlayerRealName(args[0]));
case 9: case 9:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], API.getPlayerRealName(args[0])); return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
args[8], API.getPlayerRealName(args[0]));
} }
} }
} }
@ -480,7 +556,12 @@ public class FlatFileThread extends Thread implements DataSource {
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
String[] args = line.split(":"); String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) { if (args[0].equals(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], auth.getEmail(), API.getPlayerRealName(args[0])); newAuth = new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
auth.getEmail(), API.getPlayerRealName(args[0]));
break; break;
} }
} }
@ -612,8 +693,9 @@ public class FlatFileThread extends Thread implements DataSource {
if (banned.contains(args[0])) { if (banned.contains(args[0])) {
lines.add(line); lines.add(line);
} }
} catch (NullPointerException npe) {} } catch (NullPointerException npe) {
catch (ArrayIndexOutOfBoundsException aioobe) {} } catch (ArrayIndexOutOfBoundsException aioobe) {
}
} }
bw = new BufferedWriter(new FileWriter(source)); bw = new BufferedWriter(new FileWriter(source));
for (String l : lines) { for (String l : lines) {

View File

@ -1,11 +1,13 @@
// Copyright 2007-2013 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland // Copyright 2007-2013 Christian d'Heureuse, Inventec Informatik AG, Zurich,
// Switzerland
// www.source-code.biz, www.inventec.ch/chdh // www.source-code.biz, www.inventec.ch/chdh
// //
// This module is multi-licensed and may be used under the terms // This module is multi-licensed and may be used under the terms
// of any of the following licenses: // of any of the following licenses:
// //
// EPL, Eclipse Public License, http://www.eclipse.org/legal // EPL, Eclipse Public License, http://www.eclipse.org/legal
// LGPL, GNU Lesser General Public License, http://www.gnu.org/licenses/lgpl.html // LGPL, GNU Lesser General Public License,
// http://www.gnu.org/licenses/lgpl.html
// MPL, Mozilla Public License 1.1, http://www.mozilla.org/MPL // MPL, Mozilla Public License 1.1, http://www.mozilla.org/MPL
// //
// Please contact the author if you need another license. // Please contact the author if you need another license.
@ -27,9 +29,13 @@ import javax.sql.PooledConnection;
/** /**
* A lightweight standalone JDBC connection pool manager. * A lightweight standalone JDBC connection pool manager.
* *
* <p>The public methods of this class are thread-safe. * <p>
* The public methods of this class are thread-safe.
* *
* <p>Home page: <a href="http://www.source-code.biz/miniconnectionpoolmanager">www.source-code.biz/miniconnectionpoolmanager</a><br> * <p>
* Home page: <a
* href="http://www.source-code.biz/miniconnectionpoolmanager">www.
* source-code.biz/miniconnectionpoolmanager</a><br>
* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br> * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
* Multi-licensed: EPL / LGPL / MPL. * Multi-licensed: EPL / LGPL / MPL.
*/ */
@ -44,33 +50,49 @@ private PoolConnectionEventListener poolConnectionEventListener;
// The following variables must only be accessed within synchronized blocks. // The following variables must only be accessed within synchronized blocks.
// @GuardedBy("this") could by used in the future. // @GuardedBy("this") could by used in the future.
private LinkedList<PooledConnection> recycledConnections; // list of inactive PooledConnections private LinkedList<PooledConnection> recycledConnections; // list of
private int activeConnections; // number of active (open) connections of this pool // inactive
private boolean isDisposed; // true if this connection pool has been disposed // PooledConnections
private boolean doPurgeConnection; // flag to purge the connection currently beeing closed instead of recycling it private int activeConnections; // number of active (open) connections of
private PooledConnection connectionInTransition; // a PooledConnection which is currently within a PooledConnection.getConnection() call, or null // this pool
private boolean isDisposed; // true if this connection pool has been
// disposed
private boolean doPurgeConnection; // flag to purge the connection currently
// beeing closed instead of recycling it
private PooledConnection connectionInTransition; // a PooledConnection which
// is currently within a
// PooledConnection.getConnection()
// call, or null
/** /**
* Thrown in {@link #getConnection()} or {@link #getValidConnection()} when no free connection becomes * Thrown in {@link #getConnection()} or {@link #getValidConnection()} when
* available within <code>timeout</code> seconds. * no free connection becomes available within <code>timeout</code> seconds.
*/ */
public static class TimeoutException extends RuntimeException { public static class TimeoutException extends RuntimeException {
private static final long serialVersionUID = 1; private static final long serialVersionUID = 1;
public TimeoutException() { public TimeoutException() {
super("Timeout while waiting for a free database connection."); } super("Timeout while waiting for a free database connection.");
}
public TimeoutException(String msg) { public TimeoutException(String msg) {
super(msg); }} super(msg);
}
}
/** /**
* Constructs a MiniConnectionPoolManager object with a timeout of 60 seconds. * Constructs a MiniConnectionPoolManager object with a timeout of 60
* seconds.
* *
* @param dataSource * @param dataSource
* the data source for the connections. * the data source for the connections.
* @param maxConnections * @param maxConnections
* the maximum number of connections. * the maximum number of connections.
*/ */
public MiniConnectionPoolManager (ConnectionPoolDataSource dataSource, int maxConnections) { public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource,
this(dataSource, maxConnections, 60); } int maxConnections) {
this(dataSource, maxConnections, 60);
}
/** /**
* Constructs a MiniConnectionPoolManager object. * Constructs a MiniConnectionPoolManager object.
@ -82,111 +104,146 @@ public MiniConnectionPoolManager (ConnectionPoolDataSource dataSource, int maxCo
* @param timeout * @param timeout
* the maximum time in seconds to wait for a free connection. * the maximum time in seconds to wait for a free connection.
*/ */
public MiniConnectionPoolManager (ConnectionPoolDataSource dataSource, int maxConnections, int timeout) { public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource,
int maxConnections, int timeout) {
this.dataSource = dataSource; this.dataSource = dataSource;
this.maxConnections = maxConnections; this.maxConnections = maxConnections;
this.timeoutMs = timeout * 1000L; this.timeoutMs = timeout * 1000L;
try { try {
logWriter = dataSource.getLogWriter(); } logWriter = dataSource.getLogWriter();
catch (SQLException e) {} } catch (SQLException e) {
}
if (maxConnections < 1) { if (maxConnections < 1) {
throw new IllegalArgumentException("Invalid maxConnections value."); } throw new IllegalArgumentException("Invalid maxConnections value.");
}
semaphore = new Semaphore(maxConnections, true); semaphore = new Semaphore(maxConnections, true);
recycledConnections = new LinkedList<PooledConnection>(); recycledConnections = new LinkedList<PooledConnection>();
poolConnectionEventListener = new PoolConnectionEventListener(); } poolConnectionEventListener = new PoolConnectionEventListener();
}
/** /**
* Closes all unused pooled connections. * Closes all unused pooled connections.
*/ */
public synchronized void dispose() throws SQLException { public synchronized void dispose() throws SQLException {
if (isDisposed) { if (isDisposed) {
return; } return;
}
isDisposed = true; isDisposed = true;
SQLException e = null; SQLException e = null;
while (!recycledConnections.isEmpty()) { while (!recycledConnections.isEmpty()) {
PooledConnection pconn = recycledConnections.remove(); PooledConnection pconn = recycledConnections.remove();
try { try {
pconn.close(); } pconn.close();
catch (SQLException e2) { } catch (SQLException e2) {
if (e == null) { if (e == null) {
e = e2; }}} e = e2;
}
}
}
if (e != null) { if (e != null) {
throw e; }} throw e;
}
}
/** /**
* Retrieves a connection from the connection pool. * Retrieves a connection from the connection pool.
* *
* <p>If <code>maxConnections</code> connections are already in use, the method * <p>
* waits until a connection becomes available or <code>timeout</code> seconds elapsed. * If <code>maxConnections</code> connections are already in use, the method
* When the application is finished using the connection, it must close it * waits until a connection becomes available or <code>timeout</code>
* in order to return it to the pool. * seconds elapsed. When the application is finished using the connection,
* it must close it in order to return it to the pool.
* *
* @return * @return a new <code>Connection</code> object.
* a new <code>Connection</code> object.
* @throws TimeoutException * @throws TimeoutException
* when no connection becomes available within <code>timeout</code> seconds. * when no connection becomes available within
* <code>timeout</code> seconds.
*/ */
public Connection getConnection() throws SQLException { public Connection getConnection() throws SQLException {
return getConnection2(timeoutMs); } return getConnection2(timeoutMs);
}
private Connection getConnection2(long timeoutMs) throws SQLException { private Connection getConnection2(long timeoutMs) throws SQLException {
// This routine is unsynchronized, because semaphore.tryAcquire() may block. // This routine is unsynchronized, because semaphore.tryAcquire() may
// block.
synchronized (this) { synchronized (this) {
if (isDisposed) { if (isDisposed) {
throw new IllegalStateException("Connection pool has been disposed."); }} throw new IllegalStateException(
"Connection pool has been disposed.");
}
}
try { try {
if (!semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) { if (!semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) {
throw new TimeoutException(); }} throw new TimeoutException();
catch (InterruptedException e) { }
throw new RuntimeException("Interrupted while waiting for a database connection.",e); } } catch (InterruptedException e) {
throw new RuntimeException(
"Interrupted while waiting for a database connection.", e);
}
boolean ok = false; boolean ok = false;
try { try {
Connection conn = getConnection3(); Connection conn = getConnection3();
ok = true; ok = true;
return conn; } return conn;
finally { } finally {
if (!ok) { if (!ok) {
semaphore.release(); }}} semaphore.release();
}
}
}
private synchronized Connection getConnection3() throws SQLException { private synchronized Connection getConnection3() throws SQLException {
if (isDisposed) { if (isDisposed) {
throw new IllegalStateException("Connection pool has been disposed."); } throw new IllegalStateException(
"Connection pool has been disposed.");
}
PooledConnection pconn; PooledConnection pconn;
if (!recycledConnections.isEmpty()) { if (!recycledConnections.isEmpty()) {
pconn = recycledConnections.remove(); } pconn = recycledConnections.remove();
else { } else {
pconn = dataSource.getPooledConnection(); pconn = dataSource.getPooledConnection();
pconn.addConnectionEventListener(poolConnectionEventListener); } pconn.addConnectionEventListener(poolConnectionEventListener);
}
Connection conn; Connection conn;
try { try {
// The JDBC driver may call ConnectionEventListener.connectionErrorOccurred() // The JDBC driver may call
// from within PooledConnection.getConnection(). To detect this within // ConnectionEventListener.connectionErrorOccurred()
// from within PooledConnection.getConnection(). To detect this
// within
// disposeConnection(), we temporarily set connectionInTransition. // disposeConnection(), we temporarily set connectionInTransition.
connectionInTransition = pconn; connectionInTransition = pconn;
activeConnections++; activeConnections++;
conn = pconn.getConnection(); } conn = pconn.getConnection();
finally { } finally {
connectionInTransition = null; } connectionInTransition = null;
}
assertInnerState(); assertInnerState();
return conn; } return conn;
}
/** /**
* Retrieves a connection from the connection pool and ensures that it is valid * Retrieves a connection from the connection pool and ensures that it is
* by calling {@link Connection#isValid(int)}. * valid by calling {@link Connection#isValid(int)}.
* *
* <p>If a connection is not valid, the method tries to get another connection * <p>
* If a connection is not valid, the method tries to get another connection
* until one is valid (or a timeout occurs). * until one is valid (or a timeout occurs).
* *
* <p>Pooled connections may become invalid when e.g. the database server is * <p>
* Pooled connections may become invalid when e.g. the database server is
* restarted. * restarted.
* *
* <p>This method is slower than {@link #getConnection()} because the JDBC * <p>
* driver has to send an extra command to the database server to test the connection. * This method is slower than {@link #getConnection()} because the JDBC
* driver has to send an extra command to the database server to test the
* connection.
* *
* <p>This method requires Java 1.6 or newer. * <p>
* This method requires Java 1.6 or newer.
* *
* @throws TimeoutException * @throws TimeoutException
* when no valid connection becomes available within <code>timeout</code> seconds. * when no valid connection becomes available within
* <code>timeout</code> seconds.
*/ */
public Connection getValidConnection() { public Connection getValidConnection() {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
@ -195,132 +252,181 @@ public Connection getValidConnection() {
while (true) { while (true) {
Connection conn = getValidConnection2(time, timeoutTime); Connection conn = getValidConnection2(time, timeoutTime);
if (conn != null) { if (conn != null) {
return conn; } return conn;
}
triesWithoutDelay--; triesWithoutDelay--;
if (triesWithoutDelay <= 0) { if (triesWithoutDelay <= 0) {
triesWithoutDelay = 0; triesWithoutDelay = 0;
try { try {
Thread.sleep(250); } Thread.sleep(250);
catch (InterruptedException e) { } catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for a valid database connection.", e); }} throw new RuntimeException(
"Interrupted while waiting for a valid database connection.",
e);
}
}
time = System.currentTimeMillis(); time = System.currentTimeMillis();
if (time >= timeoutTime) { if (time >= timeoutTime) {
throw new TimeoutException("Timeout while waiting for a valid database connection."); }}} throw new TimeoutException(
"Timeout while waiting for a valid database connection.");
}
}
}
private Connection getValidConnection2(long time, long timeoutTime) { private Connection getValidConnection2(long time, long timeoutTime) {
long rtime = Math.max(1, timeoutTime - time); long rtime = Math.max(1, timeoutTime - time);
Connection conn; Connection conn;
try { try {
conn = getConnection2(rtime); } conn = getConnection2(rtime);
catch (SQLException e) { } catch (SQLException e) {
return null; } return null;
}
rtime = timeoutTime - System.currentTimeMillis(); rtime = timeoutTime - System.currentTimeMillis();
int rtimeSecs = Math.max(1, (int) ((rtime + 999) / 1000)); int rtimeSecs = Math.max(1, (int) ((rtime + 999) / 1000));
try { try {
if (conn.isValid(rtimeSecs)) { if (conn.isValid(rtimeSecs)) {
return conn; }} return conn;
catch (SQLException e) {} }
// This Exception should never occur. If it nevertheless occurs, it's because of an error in the } catch (SQLException e) {
// JDBC driver which we ignore and assume that the connection is not valid. }
// When isValid() returns false, the JDBC driver should have already called connectionErrorOccurred() // This Exception should never occur. If it nevertheless occurs, it's
// and the PooledConnection has been removed from the pool, i.e. the PooledConnection will // because of an error in the
// not be added to recycledConnections when Connection.close() is called. // JDBC driver which we ignore and assume that the connection is not
// But to be sure that this works even with a faulty JDBC driver, we call purgeConnection(). // valid.
// When isValid() returns false, the JDBC driver should have already
// called connectionErrorOccurred()
// and the PooledConnection has been removed from the pool, i.e. the
// PooledConnection will
// not be added to recycledConnections when Connection.close() is
// called.
// But to be sure that this works even with a faulty JDBC driver, we
// call purgeConnection().
purgeConnection(conn); purgeConnection(conn);
return null; } return null;
}
// Purges the PooledConnection associated with the passed Connection from the connection pool. // Purges the PooledConnection associated with the passed Connection from
// the connection pool.
private synchronized void purgeConnection(Connection conn) { private synchronized void purgeConnection(Connection conn) {
try { try {
doPurgeConnection = true; doPurgeConnection = true;
// (A potential problem of this program logic is that setting the doPurgeConnection flag // (A potential problem of this program logic is that setting the
// has an effect only if the JDBC driver calls connectionClosed() synchronously within // doPurgeConnection flag
// has an effect only if the JDBC driver calls connectionClosed()
// synchronously within
// Connection.close().) // Connection.close().)
conn.close(); } conn.close();
catch (SQLException e) {} } catch (SQLException e) {
}
// ignore exception from close() // ignore exception from close()
finally { finally {
doPurgeConnection = false; }} doPurgeConnection = false;
}
}
private synchronized void recycleConnection(PooledConnection pconn) { private synchronized void recycleConnection(PooledConnection pconn) {
if (isDisposed || doPurgeConnection) { if (isDisposed || doPurgeConnection) {
disposeConnection(pconn); disposeConnection(pconn);
return; } return;
}
if (activeConnections <= 0) { if (activeConnections <= 0) {
throw new AssertionError("AuthMeDatabaseError"); } throw new AssertionError("AuthMeDatabaseError");
}
activeConnections--; activeConnections--;
semaphore.release(); semaphore.release();
recycledConnections.add(pconn); recycledConnections.add(pconn);
assertInnerState(); } assertInnerState();
}
private synchronized void disposeConnection(PooledConnection pconn) { private synchronized void disposeConnection(PooledConnection pconn) {
pconn.removeConnectionEventListener(poolConnectionEventListener); pconn.removeConnectionEventListener(poolConnectionEventListener);
if (!recycledConnections.remove(pconn) && pconn != connectionInTransition) { if (!recycledConnections.remove(pconn)
&& pconn != connectionInTransition) {
// If the PooledConnection is not in the recycledConnections list // If the PooledConnection is not in the recycledConnections list
// and is not currently within a PooledConnection.getConnection() call, // and is not currently within a PooledConnection.getConnection()
// call,
// we assume that the connection was active. // we assume that the connection was active.
if (activeConnections <= 0) { if (activeConnections <= 0) {
throw new AssertionError("AuthMeDatabaseError"); } throw new AssertionError("AuthMeDatabaseError");
}
activeConnections--; activeConnections--;
semaphore.release(); } semaphore.release();
}
closeConnectionAndIgnoreException(pconn); closeConnectionAndIgnoreException(pconn);
assertInnerState(); } assertInnerState();
}
private void closeConnectionAndIgnoreException(PooledConnection pconn) { private void closeConnectionAndIgnoreException(PooledConnection pconn) {
try { try {
pconn.close(); } pconn.close();
catch (SQLException e) { } catch (SQLException e) {
log("Error while closing database connection: "+e.toString()); }} log("Error while closing database connection: " + e.toString());
}
}
private void log(String msg) { private void log(String msg) {
String s = "MiniConnectionPoolManager: " + msg; String s = "MiniConnectionPoolManager: " + msg;
try { try {
if (logWriter == null) { if (logWriter == null) {
System.err.println(s); } System.err.println(s);
else { } else {
logWriter.println(s); }} logWriter.println(s);
catch (Exception e) {}} }
} catch (Exception e) {
}
}
private synchronized void assertInnerState() { private synchronized void assertInnerState() {
if (activeConnections < 0) { if (activeConnections < 0) {
throw new AssertionError("AuthMeDatabaseError"); } throw new AssertionError("AuthMeDatabaseError");
}
if (activeConnections + recycledConnections.size() > maxConnections) { if (activeConnections + recycledConnections.size() > maxConnections) {
throw new AssertionError("AuthMeDatabaseError"); } throw new AssertionError("AuthMeDatabaseError");
}
if (activeConnections + semaphore.availablePermits() > maxConnections) { if (activeConnections + semaphore.availablePermits() > maxConnections) {
throw new AssertionError("AuthMeDatabaseError"); }} throw new AssertionError("AuthMeDatabaseError");
}
}
private class PoolConnectionEventListener implements ConnectionEventListener { private class PoolConnectionEventListener implements
ConnectionEventListener {
public void connectionClosed(ConnectionEvent event) { public void connectionClosed(ConnectionEvent event) {
PooledConnection pconn = (PooledConnection) event.getSource(); PooledConnection pconn = (PooledConnection) event.getSource();
recycleConnection(pconn); } recycleConnection(pconn);
}
public void connectionErrorOccurred(ConnectionEvent event) { public void connectionErrorOccurred(ConnectionEvent event) {
PooledConnection pconn = (PooledConnection) event.getSource(); PooledConnection pconn = (PooledConnection) event.getSource();
disposeConnection(pconn); }} disposeConnection(pconn);
}
}
/** /**
* Returns the number of active (open) connections of this pool. * Returns the number of active (open) connections of this pool.
* *
* <p>This is the number of <code>Connection</code> objects that have been * <p>
* issued by {@link #getConnection()}, for which <code>Connection.close()</code> * This is the number of <code>Connection</code> objects that have been
* has not yet been called. * issued by {@link #getConnection()}, for which
* <code>Connection.close()</code> has not yet been called.
* *
* @return * @return the number of active connections.
* the number of active connections.
**/ **/
public synchronized int getActiveConnections() { public synchronized int getActiveConnections() {
return activeConnections; } return activeConnections;
}
/** /**
* Returns the number of inactive (unused) connections in this pool. * Returns the number of inactive (unused) connections in this pool.
* *
* <p>This is the number of internally kept recycled connections, * <p>
* for which <code>Connection.close()</code> has been called and which * This is the number of internally kept recycled connections, for which
* have not yet been reused. * <code>Connection.close()</code> has been called and which have not yet
* been reused.
* *
* @return * @return the number of inactive connections.
* the number of inactive connections.
**/ **/
public synchronized int getInactiveConnections() { public synchronized int getInactiveConnections() {
return recycledConnections.size(); } return recycledConnections.size();
}
} // end class MiniConnectionPoolManager } // end class MiniConnectionPoolManager

View File

@ -70,34 +70,38 @@ public class MySQLThread extends Thread implements DataSource {
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN..."); ConsoleLogger
.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); .getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} catch (SQLException e) { } catch (SQLException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN..."); ConsoleLogger
.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); .getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} catch (TimeoutException e) { } catch (TimeoutException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN..."); ConsoleLogger
.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); .getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} }
} }
private synchronized void connect() throws ClassNotFoundException, SQLException, TimeoutException { private synchronized void connect() throws ClassNotFoundException,
SQLException, TimeoutException {
Class.forName("com.mysql.jdbc.Driver"); Class.forName("com.mysql.jdbc.Driver");
ConsoleLogger.info("MySQL driver loaded"); ConsoleLogger.info("MySQL driver loaded");
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource(); MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
@ -118,19 +122,22 @@ public class MySQLThread extends Thread implements DataSource {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
st = con.createStatement(); st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ columnID + " INTEGER AUTO_INCREMENT," + columnID + " INTEGER AUTO_INCREMENT," + columnName
+ columnName + " VARCHAR(255) NOT NULL UNIQUE," + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword
+ columnPassword + " VARCHAR(255) NOT NULL," + " VARCHAR(255) NOT NULL," + columnIp
+ columnIp + " VARCHAR(40) NOT NULL DEFAULT '127.0.0.1'," + " VARCHAR(40) NOT NULL DEFAULT '127.0.0.1',"
+ columnLastLogin + " BIGINT NOT NULL DEFAULT '" + System.currentTimeMillis() + "'," + columnLastLogin + " BIGINT NOT NULL DEFAULT '"
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + System.currentTimeMillis() + "'," + lastlocX
+ lastlocY + " DOUBLE NOT NULL DEFAULT '0.0'," + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY
+ lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ
+ lastlocWorld + " VARCHAR(255) DEFAULT 'world'," + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld
+ columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + " VARCHAR(255) DEFAULT 'world'," + columnEmail
+ columnLogged + " SMALLINT NOT NULL DEFAULT '0'," + " VARCHAR(255) DEFAULT 'your@email.com'," + columnLogged
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));"); + " SMALLINT NOT NULL DEFAULT '0',"
rs = con.getMetaData().getColumns(null, null, tableName, columnPassword); + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID
+ "));");
rs = con.getMetaData().getColumns(null, null, tableName,
columnPassword);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnPassword + " VARCHAR(255) NOT NULL;"); + columnPassword + " VARCHAR(255) NOT NULL;");
@ -142,7 +149,8 @@ public class MySQLThread extends Thread implements DataSource {
+ columnIp + " VARCHAR(40) NOT NULL;"); + columnIp + " VARCHAR(40) NOT NULL;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin); rs = con.getMetaData().getColumns(null, null, tableName,
columnLastLogin);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnLastLogin + " BIGINT;"); + columnLastLogin + " BIGINT;");
@ -150,28 +158,48 @@ public class MySQLThread extends Thread implements DataSource {
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnLastLogin +" , ADD " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocX + " , ADD " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocY + ";"); + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0' AFTER "
+ columnLastLogin + " , ADD " + lastlocY
+ " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocX
+ " , ADD " + lastlocZ
+ " DOUBLE NOT NULL DEFAULT '0.0' AFTER " + lastlocY
+ ";");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld); rs = con.getMetaData().getColumns(null, null, tableName,
lastlocWorld);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER " + lastlocZ + ";"); st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocWorld
+ " VARCHAR(255) NOT NULL DEFAULT 'world' AFTER "
+ lastlocZ + ";");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnEmail); rs = con.getMetaData().getColumns(null, null, tableName,
columnEmail);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com' AFTER " + lastlocWorld +";"); st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com' AFTER "
+ lastlocWorld + ";");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLogged); rs = con.getMetaData().getColumns(null, null, tableName,
columnLogged);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLogged + " SMALLINT NOT NULL DEFAULT '0' AFTER " + columnEmail +";"); st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnLogged
+ " SMALLINT NOT NULL DEFAULT '0' AFTER " + columnEmail
+ ";");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (rs.next()) { if (rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " MODIFY " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';"); st.executeUpdate("ALTER TABLE " + tableName + " MODIFY "
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY "
+ lastlocY + " DOUBLE NOT NULL DEFAULT '0.0', MODIFY "
+ lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
} }
} finally { } finally {
close(rs); close(rs);
@ -221,20 +249,55 @@ public class MySQLThread extends Thread implements DataSource {
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) { if (rs.getString(columnIp).isEmpty()
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "198.18.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld),rs.getString(columnEmail), API.getPlayerRealName(rs.getString(columnName))); && rs.getString(columnIp) != null) {
pAuth = new PlayerAuth(rs.getString(columnName),
rs.getString(columnPassword), "198.18.0.1",
rs.getLong(columnLastLogin),
rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ), rs.getString(lastlocWorld),
rs.getString(columnEmail), API.getPlayerRealName(rs
.getString(columnName)));
} else { } else {
if (!columnSalt.isEmpty()) { if (!columnSalt.isEmpty()) {
if(!columnGroup.isEmpty()) if (!columnGroup.isEmpty()) pAuth = new PlayerAuth(
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword),rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), API.getPlayerRealName(rs.getString(columnName))); rs.getString(columnName),
else pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword),rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld),rs.getString(columnEmail), API.getPlayerRealName(rs.getString(columnName))); rs.getString(columnPassword),
rs.getString(columnSalt),
rs.getInt(columnGroup), rs.getString(columnIp),
rs.getLong(columnLastLogin),
rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ),
rs.getString(lastlocWorld),
rs.getString(columnEmail),
API.getPlayerRealName(rs.getString(columnName)));
else pAuth = new PlayerAuth(rs.getString(columnName),
rs.getString(columnPassword),
rs.getString(columnSalt),
rs.getString(columnIp),
rs.getLong(columnLastLogin),
rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ),
rs.getString(lastlocWorld),
rs.getString(columnEmail),
API.getPlayerRealName(rs.getString(columnName)));
} else { } else {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), API.getPlayerRealName(rs.getString(columnName))); pAuth = new PlayerAuth(rs.getString(columnName),
rs.getString(columnPassword),
rs.getString(columnIp),
rs.getLong(columnLastLogin),
rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ),
rs.getString(lastlocWorld),
rs.getString(columnEmail),
API.getPlayerRealName(rs.getString(columnName)));
} }
} }
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
rs.close(); rs.close();
pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;"); pst = con
.prepareStatement("SELECT * FROM xf_user_authenticate WHERE "
+ columnID + "=?;");
pst.setInt(1, id); pst.setInt(1, id);
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
@ -266,15 +329,21 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
if ((columnSalt == null || columnSalt.isEmpty()) || (auth.getSalt() == null || auth.getSalt().isEmpty())) { if ((columnSalt == null || columnSalt.isEmpty())
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + ") VALUES (?,?,?,?);"); || (auth.getSalt() == null || auth.getSalt().isEmpty())) {
pst = con.prepareStatement("INSERT INTO " + tableName + "("
+ columnName + "," + columnPassword + "," + columnIp
+ "," + columnLastLogin + ") VALUES (?,?,?,?);");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash()); pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp()); pst.setString(3, auth.getIp());
pst.setLong(4, auth.getLastLogin()); pst.setLong(4, auth.getLastLogin());
pst.executeUpdate(); pst.executeUpdate();
} else { } else {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnSalt + ") VALUES (?,?,?,?,?);"); pst = con.prepareStatement("INSERT INTO " + tableName + "("
+ columnName + "," + columnPassword + "," + columnIp
+ "," + columnLastLogin + "," + columnSalt
+ ") VALUES (?,?,?,?,?);");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash()); pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp()); pst.setString(3, auth.getIp());
@ -284,7 +353,8 @@ public class MySQLThread extends Thread implements DataSource {
} }
if (!columnOthers.isEmpty()) { if (!columnOthers.isEmpty()) {
for (String column : columnOthers) { for (String column : columnOthers) {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + column + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ column + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getRealname()); pst.setString(1, auth.getRealname());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -293,32 +363,42 @@ public class MySQLThread extends Thread implements DataSource {
if (Settings.getPasswordHash == HashAlgorithm.PHPBB) { if (Settings.getPasswordHash == HashAlgorithm.PHPBB) {
int id; int id;
ResultSet rs = null; ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName
+ " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
// Insert player in phpbb_user_group // Insert player in phpbb_user_group
pst = con.prepareStatement("INSERT INTO " + Settings.getPhpbbPrefix + "user_group (group_id, user_id, group_leader, user_pending) VALUES (?,?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getPhpbbPrefix
+ "user_group (group_id, user_id, group_leader, user_pending) VALUES (?,?,?,?);");
pst.setInt(1, Settings.getPhpbbGroup); pst.setInt(1, Settings.getPhpbbGroup);
pst.setInt(2, id); pst.setInt(2, id);
pst.setInt(3, 0); pst.setInt(3, 0);
pst.setInt(4, 0); pst.setInt(4, 0);
pst.executeUpdate(); pst.executeUpdate();
// Update player group in phpbb_users // Update player group in phpbb_users
pst = con.prepareStatement("UPDATE " + tableName + " SET " + tableName + ".group_id=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ tableName + ".group_id=? WHERE " + columnName
+ "=?;");
pst.setInt(1, Settings.getPhpbbGroup); pst.setInt(1, Settings.getPhpbbGroup);
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
// Get current time without ms // Get current time without ms
long time = System.currentTimeMillis() / 1000; long time = System.currentTimeMillis() / 1000;
// Update user_regdate // Update user_regdate
pst = con.prepareStatement("UPDATE " + tableName + " SET " + tableName + ".user_regdate=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ tableName + ".user_regdate=? WHERE " + columnName
+ "=?;");
pst.setLong(1, time); pst.setLong(1, time);
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
// Update user_lastvisit // Update user_lastvisit
pst = con.prepareStatement("UPDATE " + tableName + " SET " + tableName + ".user_lastvisit=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ tableName + ".user_lastvisit=? WHERE "
+ columnName + "=?;");
pst.setLong(1, time); pst.setLong(1, time);
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -327,79 +407,116 @@ public class MySQLThread extends Thread implements DataSource {
if (Settings.getPasswordHash == HashAlgorithm.WORDPRESS) { if (Settings.getPasswordHash == HashAlgorithm.WORDPRESS) {
int id; int id;
ResultSet rs = null; ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName
+ " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
// First Name // First Name
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "first_name"); pst.setString(2, "first_name");
pst.setString(3, ""); pst.setString(3, "");
pst.executeUpdate(); pst.executeUpdate();
// Last Name // Last Name
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "last_name"); pst.setString(2, "last_name");
pst.setString(3, ""); pst.setString(3, "");
pst.executeUpdate(); pst.executeUpdate();
// Nick Name // Nick Name
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "nickname"); pst.setString(2, "nickname");
pst.setString(3, auth.getNickname()); pst.setString(3, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
// Description // Description
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "description"); pst.setString(2, "description");
pst.setString(3, ""); pst.setString(3, "");
pst.executeUpdate(); pst.executeUpdate();
// Rich_Editing // Rich_Editing
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "rich_editing"); pst.setString(2, "rich_editing");
pst.setString(3, "true"); pst.setString(3, "true");
pst.executeUpdate(); pst.executeUpdate();
// Comments_Shortcuts // Comments_Shortcuts
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "comment_shortcuts"); pst.setString(2, "comment_shortcuts");
pst.setString(3, "false"); pst.setString(3, "false");
pst.executeUpdate(); pst.executeUpdate();
// admin_color // admin_color
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "admin_color"); pst.setString(2, "admin_color");
pst.setString(3, "fresh"); pst.setString(3, "fresh");
pst.executeUpdate(); pst.executeUpdate();
// use_ssl // use_ssl
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "use_ssl"); pst.setString(2, "use_ssl");
pst.setString(3, "0"); pst.setString(3, "0");
pst.executeUpdate(); pst.executeUpdate();
// show_admin_bar_front // show_admin_bar_front
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "show_admin_bar_front"); pst.setString(2, "show_admin_bar_front");
pst.setString(3, "true"); pst.setString(3, "true");
pst.executeUpdate(); pst.executeUpdate();
// wp_capabilities // wp_capabilities
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "wp_capabilities"); pst.setString(2, "wp_capabilities");
pst.setString(3, "a:1:{s:10:\"subscriber\";b:1;}"); pst.setString(3, "a:1:{s:10:\"subscriber\";b:1;}");
pst.executeUpdate(); pst.executeUpdate();
// wp_user_level // wp_user_level
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "wp_user_level"); pst.setString(2, "wp_user_level");
pst.setString(3, "0"); pst.setString(3, "0");
pst.executeUpdate(); pst.executeUpdate();
// default_password_nag // default_password_nag
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO "
+ Settings.getWordPressPrefix
+ "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "default_password_nag"); pst.setString(2, "default_password_nag");
pst.setString(3, ""); pst.setString(3, "");
@ -409,13 +526,15 @@ public class MySQLThread extends Thread implements DataSource {
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
int id; int id;
ResultSet rs = null; ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName
+ " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
// Insert password in the correct table // Insert password in the correct table
pst = con.prepareStatement("INSERT INTO xf_user_authenticate (user_id, scheme_class, data) VALUES (?,?,?);"); pst = con
.prepareStatement("INSERT INTO xf_user_authenticate (user_id, scheme_class, data) VALUES (?,?,?);");
pst.setInt(1, id); pst.setInt(1, id);
pst.setString(2, "XenForo_Authentication_Core12"); pst.setString(2, "XenForo_Authentication_Core12");
byte[] bytes = auth.getHash().getBytes(); byte[] bytes = auth.getHash().getBytes();
@ -444,27 +563,33 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnPassword + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getHash()); pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
int id; int id;
ResultSet rs = null; ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName
+ " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
// Insert password in the correct table // Insert password in the correct table
pst = con.prepareStatement("UPDATE xf_user_authenticate SET data=? WHERE " + columnID + "=?;"); pst = con
.prepareStatement("UPDATE xf_user_authenticate SET data=? WHERE "
+ columnID + "=?;");
byte[] bytes = auth.getHash().getBytes(); byte[] bytes = auth.getHash().getBytes();
Blob blob = con.createBlob(); Blob blob = con.createBlob();
blob.setBytes(1, bytes); blob.setBytes(1, bytes);
pst.setBlob(1, blob); pst.setBlob(1, blob);
pst.setInt(2, id); pst.setInt(2, id);
pst.executeUpdate(); pst.executeUpdate();
pst = con.prepareStatement("UPDATE xf_user_authenticate SET scheme_class=? WHERE " + columnID + "=?;"); pst = con
.prepareStatement("UPDATE xf_user_authenticate SET scheme_class=? WHERE "
+ columnID + "=?;");
pst.setString(1, "XenForo_Authentication_Core12"); pst.setString(1, "XenForo_Authentication_Core12");
pst.setInt(2, id); pst.setInt(2, id);
pst.executeUpdate(); pst.executeUpdate();
@ -489,7 +614,9 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnIp + "=?, " + columnLastLogin + "=? WHERE "
+ columnName + "=?;");
pst.setString(1, auth.getIp()); pst.setString(1, auth.getIp());
pst.setLong(2, auth.getLastLogin()); pst.setLong(2, auth.getLastLogin());
pst.setString(3, auth.getNickname()); pst.setString(3, auth.getNickname());
@ -513,7 +640,8 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;"); pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE "
+ columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
return pst.executeUpdate(); return pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
@ -536,13 +664,15 @@ public class MySQLThread extends Thread implements DataSource {
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE "
+ columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
list.add(rs.getString(columnName)); list.add(rs.getString(columnName));
} }
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;"); pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE "
+ columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
pst.executeUpdate(); pst.executeUpdate();
return list; return list;
@ -568,17 +698,21 @@ public class MySQLThread extends Thread implements DataSource {
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
int id; int id;
ResultSet rs = null; ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("SELECT * FROM " + tableName
+ " WHERE " + columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(columnID); id = rs.getInt(columnID);
// Remove data // Remove data
pst = con.prepareStatement("DELETE FROM xf_user_authenticate WHERE " + columnID + "=?;"); pst = con
.prepareStatement("DELETE FROM xf_user_authenticate WHERE "
+ columnID + "=?;");
pst.setInt(1, id); pst.setInt(1, id);
} }
} }
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE "
+ columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
pst.executeUpdate(); pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
@ -600,7 +734,9 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET "+ lastlocX + " =?, "+ lastlocY +"=?, "+ lastlocZ +"=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ lastlocX + " =?, " + lastlocY + "=?, " + lastlocZ
+ "=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;");
pst.setDouble(1, auth.getQuitLocX()); pst.setDouble(1, auth.getQuitLocX());
pst.setDouble(2, auth.getQuitLocY()); pst.setDouble(2, auth.getQuitLocY());
pst.setDouble(3, auth.getQuitLocZ()); pst.setDouble(3, auth.getQuitLocZ());
@ -655,7 +791,8 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET "+ columnEmail + " =? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnEmail + " =? WHERE " + columnName + "=?;");
pst.setString(1, auth.getEmail()); pst.setString(1, auth.getEmail());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -681,7 +818,8 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET "+ columnSalt + " =? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnSalt + " =? WHERE " + columnName + "=?;");
pst.setString(1, auth.getSalt()); pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -714,11 +852,12 @@ public class MySQLThread extends Thread implements DataSource {
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN..."); ConsoleLogger
.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); .getPluginManager().disablePlugin(AuthMe.getInstance());
} }
} }
@ -846,7 +985,8 @@ public class MySQLThread extends Thread implements DataSource {
try { try {
for (String name : banned) { for (String name : banned) {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("DELETE FROM " + tableName
+ " WHERE " + columnName + "=?;");
pst.setString(1, name); pst.setString(1, name);
pst.executeUpdate(); pst.executeUpdate();
} }
@ -869,35 +1009,38 @@ public class MySQLThread extends Thread implements DataSource {
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN..."); ConsoleLogger
.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); .getPluginManager().disablePlugin(AuthMe.getInstance());
} }
} catch (AssertionError ae) { } catch (AssertionError ae) {
// Make sure assertionerror is caused by the connectionpoolmanager, else re-throw it // Make sure assertionerror is caused by the connectionpoolmanager,
if (!ae.getMessage().equalsIgnoreCase("AuthMeDatabaseError")) // else re-throw it
throw new AssertionError(ae.getMessage()); if (!ae.getMessage().equalsIgnoreCase("AuthMeDatabaseError")) throw new AssertionError(
ae.getMessage());
try { try {
con = null; con = null;
reconnect(false); reconnect(false);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) { if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN..."); ConsoleLogger
.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); .getPluginManager().disablePlugin(AuthMe.getInstance());
} }
} }
if (con == null) if (con == null) con = conPool.getValidConnection();
con = conPool.getValidConnection();
return con; return con;
} }
private synchronized void reconnect(boolean reload) throws ClassNotFoundException, SQLException, TimeoutException { private synchronized void reconnect(boolean reload)
throws ClassNotFoundException, SQLException, TimeoutException {
conPool.dispose(); conPool.dispose();
Class.forName("com.mysql.jdbc.Driver"); Class.forName("com.mysql.jdbc.Driver");
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource(); MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
@ -907,8 +1050,8 @@ public class MySQLThread extends Thread implements DataSource {
dataSource.setUser(username); dataSource.setUser(username);
dataSource.setPassword(password); dataSource.setPassword(password);
conPool = new MiniConnectionPoolManager(dataSource, 10); conPool = new MiniConnectionPoolManager(dataSource, 10);
if (!reload) if (!reload) ConsoleLogger
ConsoleLogger.info("ConnectionPool was unavailable... Reconnected!"); .info("ConnectionPool was unavailable... Reconnected!");
} }
@Override @Override
@ -927,8 +1070,7 @@ public class MySQLThread extends Thread implements DataSource {
+ columnName + "=?;"); + columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) if (rs.next()) return (rs.getInt(columnLogged) == 1);
return (rs.getInt(columnLogged) == 1);
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
return false; return false;
@ -949,7 +1091,8 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnLogged + "=? WHERE " + columnName + "=?;");
pst.setInt(1, 1); pst.setInt(1, 1);
pst.setString(2, user); pst.setString(2, user);
pst.executeUpdate(); pst.executeUpdate();
@ -972,7 +1115,8 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnLogged + "=? WHERE " + columnName + "=?;");
pst.setInt(1, 0); pst.setInt(1, 0);
pst.setString(2, user); pst.setString(2, user);
pst.executeUpdate(); pst.executeUpdate();
@ -995,7 +1139,8 @@ public class MySQLThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
con = makeSureConnectionIsReady(); con = makeSureConnectionIsReady();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnLogged + "=? WHERE " + columnLogged + "=?;");
pst.setInt(1, 0); pst.setInt(1, 0);
pst.setInt(2, 1); pst.setInt(2, 1);
pst.executeUpdate(); pst.executeUpdate();

View File

@ -17,7 +17,6 @@ import fr.xephi.authme.datasource.MiniConnectionPoolManager.TimeoutException;
import fr.xephi.authme.settings.PlayersLogs; import fr.xephi.authme.settings.PlayersLogs;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class SQLiteThread extends Thread implements DataSource { public class SQLiteThread extends Thread implements DataSource {
private String database; private String database;
@ -61,8 +60,8 @@ public class SQLiteThread extends Thread implements DataSource {
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN..."); ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); .getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} catch (SQLException e) { } catch (SQLException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
@ -70,16 +69,18 @@ public class SQLiteThread extends Thread implements DataSource {
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN..."); ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown(); AuthMe.getInstance().getServer().shutdown();
} }
if (!Settings.isStopEnabled) if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); .getPluginManager().disablePlugin(AuthMe.getInstance());
return; return;
} }
} }
private synchronized void connect() throws ClassNotFoundException, SQLException { private synchronized void connect() throws ClassNotFoundException,
SQLException {
Class.forName("org.sqlite.JDBC"); Class.forName("org.sqlite.JDBC");
ConsoleLogger.info("SQLite driver loaded"); ConsoleLogger.info("SQLite driver loaded");
this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/"+database+".db"); this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/"
+ database + ".db");
} }
@ -89,18 +90,19 @@ public class SQLiteThread extends Thread implements DataSource {
try { try {
st = con.createStatement(); st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ columnID + " INTEGER AUTO_INCREMENT," + columnID + " INTEGER AUTO_INCREMENT," + columnName
+ columnName + " VARCHAR(255) NOT NULL UNIQUE," + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword
+ columnPassword + " VARCHAR(255) NOT NULL," + " VARCHAR(255) NOT NULL," + columnIp
+ columnIp + " VARCHAR(40) NOT NULL," + " VARCHAR(40) NOT NULL," + columnLastLogin + " BIGINT,"
+ columnLastLogin + " BIGINT," + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ
+ lastlocY + " DOUBLE NOT NULL DEFAULT '0.0'," + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld
+ lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + " VARCHAR(255) DEFAULT 'world'," + columnEmail
+ lastlocWorld + " VARCHAR(255) DEFAULT 'world'," + " VARCHAR(255) DEFAULT 'your@email.com',"
+ columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));"); + "));");
rs = con.getMetaData().getColumns(null, null, tableName, columnPassword); rs = con.getMetaData().getColumns(null, null, tableName,
columnPassword);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnPassword + " VARCHAR(255) NOT NULL;"); + columnPassword + " VARCHAR(255) NOT NULL;");
@ -112,7 +114,8 @@ public class SQLiteThread extends Thread implements DataSource {
+ columnIp + " VARCHAR(40) NOT NULL;"); + columnIp + " VARCHAR(40) NOT NULL;");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin); rs = con.getMetaData().getColumns(null, null, tableName,
columnLastLogin);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnLastLogin + " BIGINT;"); + columnLastLogin + " BIGINT;");
@ -120,19 +123,28 @@ public class SQLiteThread extends Thread implements DataSource {
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0';"); st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0';"); + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';"); st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocY + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld); rs = con.getMetaData().getColumns(null, null, tableName,
lastlocWorld);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world';"); st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocWorld
+ " VARCHAR(255) NOT NULL DEFAULT 'world';");
} }
rs.close(); rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnEmail); rs = con.getMetaData().getColumns(null, null, tableName,
columnEmail);
if (!rs.next()) { if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';"); st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com';");
} }
} finally { } finally {
close(rs); close(rs);
@ -146,7 +158,8 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE "
+ columnName + "=?");
pst.setString(1, user); pst.setString(1, user);
rs = pst.executeQuery(); rs = pst.executeQuery();
return rs.next(); return rs.next();
@ -170,12 +183,35 @@ public class SQLiteThread extends Thread implements DataSource {
rs = pst.executeQuery(); rs = pst.executeQuery();
if (rs.next()) { if (rs.next()) {
if (rs.getString(columnIp).isEmpty()) { if (rs.getString(columnIp).isEmpty()) {
return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "198.18.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld) , rs.getString(columnEmail), API.getPlayerRealName(rs.getString(columnName))); return new PlayerAuth(rs.getString(columnName),
rs.getString(columnPassword), "198.18.0.1",
rs.getLong(columnLastLogin),
rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ), rs.getString(lastlocWorld),
rs.getString(columnEmail), API.getPlayerRealName(rs
.getString(columnName)));
} else { } else {
if (!columnSalt.isEmpty()) { if (!columnSalt.isEmpty()) {
return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword),rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld) , rs.getString(columnEmail), API.getPlayerRealName(rs.getString(columnName))); return new PlayerAuth(rs.getString(columnName),
rs.getString(columnPassword),
rs.getString(columnSalt),
rs.getInt(columnGroup), rs.getString(columnIp),
rs.getLong(columnLastLogin),
rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ),
rs.getString(lastlocWorld),
rs.getString(columnEmail),
API.getPlayerRealName(rs.getString(columnName)));
} else { } else {
return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld) , rs.getString(columnEmail), API.getPlayerRealName(rs.getString(columnName))); return new PlayerAuth(rs.getString(columnName),
rs.getString(columnPassword),
rs.getString(columnIp),
rs.getLong(columnLastLogin),
rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ),
rs.getString(lastlocWorld),
rs.getString(columnEmail),
API.getPlayerRealName(rs.getString(columnName)));
} }
} }
} else { } else {
@ -195,14 +231,19 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) { if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + ") VALUES (?,?,?,?);"); pst = con.prepareStatement("INSERT INTO " + tableName + "("
+ columnName + "," + columnPassword + "," + columnIp
+ "," + columnLastLogin + ") VALUES (?,?,?,?);");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash()); pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp()); pst.setString(3, auth.getIp());
pst.setLong(4, auth.getLastLogin()); pst.setLong(4, auth.getLastLogin());
pst.executeUpdate(); pst.executeUpdate();
} else { } else {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnSalt + ") VALUES (?,?,?,?,?);"); pst = con.prepareStatement("INSERT INTO " + tableName + "("
+ columnName + "," + columnPassword + "," + columnIp
+ "," + columnLastLogin + "," + columnSalt
+ ") VALUES (?,?,?,?,?);");
pst.setString(1, auth.getNickname()); pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash()); pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp()); pst.setString(3, auth.getIp());
@ -223,7 +264,8 @@ public class SQLiteThread extends Thread implements DataSource {
public synchronized boolean updatePassword(PlayerAuth auth) { public synchronized boolean updatePassword(PlayerAuth auth) {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnPassword + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getHash()); pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -240,7 +282,9 @@ public class SQLiteThread extends Thread implements DataSource {
public boolean updateSession(PlayerAuth auth) { public boolean updateSession(PlayerAuth auth) {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnIp + "=?, " + columnLastLogin + "=? WHERE "
+ columnName + "=?;");
pst.setString(1, auth.getIp()); pst.setString(1, auth.getIp());
pst.setLong(2, auth.getLastLogin()); pst.setLong(2, auth.getLastLogin());
pst.setString(3, auth.getNickname()); pst.setString(3, auth.getNickname());
@ -259,7 +303,8 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;"); pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE "
+ columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
return pst.executeUpdate(); return pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
@ -276,7 +321,8 @@ public class SQLiteThread extends Thread implements DataSource {
ResultSet rs = null; ResultSet rs = null;
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
try { try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;"); pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE "
+ columnLastLogin + "<?;");
pst.setLong(1, until); pst.setLong(1, until);
rs = pst.executeQuery(); rs = pst.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -296,7 +342,8 @@ public class SQLiteThread extends Thread implements DataSource {
public synchronized boolean removeAuth(String user) { public synchronized boolean removeAuth(String user) {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE "
+ columnName + "=?;");
pst.setString(1, user); pst.setString(1, user);
pst.executeUpdate(); pst.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
@ -312,7 +359,9 @@ public class SQLiteThread extends Thread implements DataSource {
public boolean updateQuitLoc(PlayerAuth auth) { public boolean updateQuitLoc(PlayerAuth auth) {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + "=?, "+ lastlocY +"=?, "+ lastlocZ +"=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ lastlocX + "=?, " + lastlocY + "=?, " + lastlocZ + "=?, "
+ lastlocWorld + "=? WHERE " + columnName + "=?;");
pst.setDouble(1, auth.getQuitLocX()); pst.setDouble(1, auth.getQuitLocX());
pst.setDouble(2, auth.getQuitLocY()); pst.setDouble(2, auth.getQuitLocY());
pst.setDouble(3, auth.getQuitLocZ()); pst.setDouble(3, auth.getQuitLocZ());
@ -355,7 +404,8 @@ public class SQLiteThread extends Thread implements DataSource {
public boolean updateEmail(PlayerAuth auth) { public boolean updateEmail(PlayerAuth auth) {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnEmail + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getEmail()); pst.setString(1, auth.getEmail());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -375,7 +425,8 @@ public class SQLiteThread extends Thread implements DataSource {
} }
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnSalt + "=? WHERE " + columnName + "=?;"); pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnSalt + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getSalt()); pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname()); pst.setString(2, auth.getNickname());
pst.executeUpdate(); pst.executeUpdate();
@ -510,7 +561,8 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null; PreparedStatement pst = null;
try { try {
for (String name : banned) { for (String name : banned) {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;"); pst = con.prepareStatement("DELETE FROM " + tableName
+ " WHERE " + columnName + "=?;");
pst.setString(1, name); pst.setString(1, name);
pst.executeUpdate(); pst.executeUpdate();
} }

View File

@ -18,15 +18,19 @@ public class AuthMeTeleportEvent extends CustomEvent {
this.from = player.getLocation(); this.from = player.getLocation();
this.to = to; this.to = to;
} }
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
public void setTo(Location to) { public void setTo(Location to) {
this.to = to; this.to = to;
} }
public Location getTo() { public Location getTo() {
return to; return to;
} }
public Location getFrom() { public Location getFrom() {
return from; return from;
} }

View File

@ -15,7 +15,8 @@ public class ProtectInventoryEvent extends CustomEvent {
private ItemStack[] emptyArmor = null; private ItemStack[] emptyArmor = null;
private Player player; private Player player;
public ProtectInventoryEvent(Player player, ItemStack[] storedinventory, ItemStack[] storedarmor) { public ProtectInventoryEvent(Player player, ItemStack[] storedinventory,
ItemStack[] storedarmor) {
this.player = player; this.player = player;
this.storedinventory = storedinventory; this.storedinventory = storedinventory;
this.storedarmor = storedarmor; this.storedarmor = storedarmor;

View File

@ -18,15 +18,19 @@ public class RegisterTeleportEvent extends CustomEvent {
this.from = player.getLocation(); this.from = player.getLocation();
this.to = to; this.to = to;
} }
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
public void setTo(Location to) { public void setTo(Location to) {
this.to = to; this.to = to;
} }
public Location getTo() { public Location getTo() {
return to; return to;
} }
public Location getFrom() { public Location getFrom() {
return from; return from;
} }

View File

@ -13,7 +13,8 @@ public class RestoreInventoryEvent extends CustomEvent {
private ItemStack[] armor; private ItemStack[] armor;
private Player player; private Player player;
public RestoreInventoryEvent(Player player, ItemStack[] inventory, ItemStack[] armor) { public RestoreInventoryEvent(Player player, ItemStack[] inventory,
ItemStack[] armor) {
this.player = player; this.player = player;
this.inventory = inventory; this.inventory = inventory;
this.armor = armor; this.armor = armor;

View File

@ -14,24 +14,30 @@ public class SpawnTeleportEvent extends CustomEvent {
private Location from; private Location from;
private boolean isAuthenticated; private boolean isAuthenticated;
public SpawnTeleportEvent(Player player, Location from, Location to, boolean isAuthenticated) { public SpawnTeleportEvent(Player player, Location from, Location to,
boolean isAuthenticated) {
this.player = player; this.player = player;
this.from = from; this.from = from;
this.to = to; this.to = to;
this.isAuthenticated = isAuthenticated; this.isAuthenticated = isAuthenticated;
} }
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
public void setTo(Location to) { public void setTo(Location to) {
this.to = to; this.to = to;
} }
public Location getTo() { public Location getTo() {
return to; return to;
} }
public Location getFrom() { public Location getFrom() {
return from; return from;
} }
public boolean isAuthenticated() { public boolean isAuthenticated() {
return isAuthenticated; return isAuthenticated;
} }

View File

@ -5,7 +5,6 @@ import org.bukkit.inventory.ItemStack;
import fr.xephi.authme.cache.backup.FileCache; import fr.xephi.authme.cache.backup.FileCache;
/** /**
* *
* @author Xephi59 * @author Xephi59
@ -24,8 +23,10 @@ public class StoreInventoryEvent extends CustomEvent {
public StoreInventoryEvent(Player player, FileCache fileCache) { public StoreInventoryEvent(Player player, FileCache fileCache) {
this.player = player; this.player = player;
this.inventory = fileCache.readCache(player.getName().toLowerCase()).getInventory(); this.inventory = fileCache.readCache(player.getName().toLowerCase())
this.armor = fileCache.readCache(player.getName().toLowerCase()).getArmour(); .getInventory();
this.armor = fileCache.readCache(player.getName().toLowerCase())
.getArmour();
} }
public ItemStack[] getInventory() { public ItemStack[] getInventory() {

View File

@ -3,8 +3,7 @@ package fr.xephi.authme.gui;
import org.getspout.spoutapi.event.screen.ButtonClickEvent; import org.getspout.spoutapi.event.screen.ButtonClickEvent;
import org.getspout.spoutapi.gui.GenericButton; import org.getspout.spoutapi.gui.GenericButton;
public class CustomButton extends GenericButton public class CustomButton extends GenericButton {
{
public Clickable handleRef = null; public Clickable handleRef = null;
public CustomButton(Clickable c) { public CustomButton(Clickable c) {
@ -16,12 +15,8 @@ public class CustomButton extends GenericButton
handleRef.handleClick(event); handleRef.handleClick(event);
} }
public CustomButton setMidPos(int x, int y) public CustomButton setMidPos(int x, int y) {
{ this.setX(x).setY(y).shiftXPos(-(width / 2)).shiftYPos(-(height / 2));
this.setX(x)
.setY(y)
.shiftXPos(-(width / 2))
.shiftYPos(-(height / 2));
return this; return this;
} }

View File

@ -20,7 +20,6 @@ import fr.xephi.authme.gui.Clickable;
import fr.xephi.authme.gui.CustomButton; import fr.xephi.authme.gui.CustomButton;
import fr.xephi.authme.settings.SpoutCfg; import fr.xephi.authme.settings.SpoutCfg;
public class LoginScreen extends GenericPopup implements Clickable { public class LoginScreen extends GenericPopup implements Clickable {
public AuthMe plugin = AuthMe.getInstance(); public AuthMe plugin = AuthMe.getInstance();
@ -37,7 +36,8 @@ public class LoginScreen extends GenericPopup implements Clickable{
String exitMsg = spoutCfg.getString("LoginScreen.exit message"); String exitMsg = spoutCfg.getString("LoginScreen.exit message");
String title = spoutCfg.getString("LoginScreen.title"); String title = spoutCfg.getString("LoginScreen.title");
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<String> textlines = (List<String>) spoutCfg.getList("LoginScreen.text"); List<String> textlines = (List<String>) spoutCfg
.getList("LoginScreen.text");
public SpoutPlayer splayer; public SpoutPlayer splayer;
public LoginScreen(SpoutPlayer player) { public LoginScreen(SpoutPlayer player) {
@ -50,61 +50,37 @@ public class LoginScreen extends GenericPopup implements Clickable{
int part = !(textlines.size() <= 5) ? 195 / objects : 20; int part = !(textlines.size() <= 5) ? 195 / objects : 20;
int h = 3 * part / 4, w = 8 * part; int h = 3 * part / 4, w = 8 * part;
titleLbl = new GenericLabel(); titleLbl = new GenericLabel();
titleLbl titleLbl.setText(title).setTextColor(new Color(1.0F, 0, 0, 1.0F))
.setText(title) .setAlign(WidgetAnchor.TOP_CENTER).setHeight(h).setWidth(w)
.setTextColor(new Color(1.0F, 0, 0, 1.0F)) .setX(maxWidth / 2).setY(25);
.setAlign(WidgetAnchor.TOP_CENTER)
.setHeight(h)
.setWidth(w)
.setX(maxWidth / 2 )
.setY(25);
this.attachWidget(plugin, titleLbl); this.attachWidget(plugin, titleLbl);
int ystart = 25 + h + part / 2; int ystart = 25 + h + part / 2;
for (int x=0; x<textlines.size();x++) for (int x = 0; x < textlines.size(); x++) {
{
textLbl = new GenericLabel(); textLbl = new GenericLabel();
textLbl textLbl.setText(textlines.get(x)).setAlign(WidgetAnchor.TOP_CENTER)
.setText(textlines.get(x)) .setHeight(h).setWidth(w).setX(maxWidth / 2)
.setAlign(WidgetAnchor.TOP_CENTER)
.setHeight(h)
.setWidth(w)
.setX(maxWidth / 2)
.setY(ystart + x * part); .setY(ystart + x * part);
this.attachWidget(plugin, textLbl); this.attachWidget(plugin, textLbl);
} }
passBox = new GenericTextField(); passBox = new GenericTextField();
passBox passBox.setMaximumCharacters(18).setMaximumLines(1).setHeight(h - 2)
.setMaximumCharacters(18) .setWidth(w - 2).setY(220 - h - 2 * part);
.setMaximumLines(1)
.setHeight(h-2)
.setWidth(w-2)
.setY(220-h - 2*part);
passBox.setPasswordField(true); passBox.setPasswordField(true);
setXToMid(passBox); setXToMid(passBox);
this.attachWidget(plugin, passBox); this.attachWidget(plugin, passBox);
errorLbl = new GenericLabel(); errorLbl = new GenericLabel();
errorLbl errorLbl.setText("").setTextColor(new Color(1.0F, 0, 0, 1.0F))
.setText("") .setHeight(h).setWidth(w)
.setTextColor(new Color(1.0F, 0, 0, 1.0F))
.setHeight(h)
.setWidth(w)
.setX(passBox.getX() + passBox.getWidth() + 2) .setX(passBox.getX() + passBox.getWidth() + 2)
.setY(passBox.getY()); .setY(passBox.getY());
this.attachWidget(plugin, errorLbl); this.attachWidget(plugin, errorLbl);
loginBtn = new CustomButton(this); loginBtn = new CustomButton(this);
loginBtn loginBtn.setText(loginTxt).setHeight(h).setWidth(w)
.setText(loginTxt)
.setHeight(h)
.setWidth(w)
.setY(220 - h - part); .setY(220 - h - part);
setXToMid(loginBtn); setXToMid(loginBtn);
this.attachWidget(plugin, loginBtn); this.attachWidget(plugin, loginBtn);
exitBtn = new CustomButton(this); exitBtn = new CustomButton(this);
exitBtn exitBtn.setText(exitTxt).setHeight(h).setWidth(w).setY(220 - h);
.setText(exitTxt)
.setHeight(h)
.setWidth(w)
.setY(220-h);
setXToMid(exitBtn); setXToMid(exitBtn);
this.attachWidget(plugin, exitBtn); this.attachWidget(plugin, exitBtn);
this.setPriority(RenderPriority.Highest); this.setPriority(RenderPriority.Highest);
@ -115,11 +91,9 @@ public class LoginScreen extends GenericPopup implements Clickable{
Button b = event.getButton(); Button b = event.getButton();
SpoutPlayer player = event.getPlayer(); SpoutPlayer player = event.getPlayer();
if (event.isCancelled() || event == null || event.getPlayer() == null) return; if (event.isCancelled() || event == null || event.getPlayer() == null) return;
if (b.equals(loginBtn)) if (b.equals(loginBtn)) {
{
plugin.management.performLogin(player, passBox.getText(), false); plugin.management.performLogin(player, passBox.getText(), false);
}else if(b.equals(exitBtn)) } else if (b.equals(exitBtn)) {
{
event.getPlayer().kickPlayer(exitMsg); event.getPlayer().kickPlayer(exitMsg);
} }
} }

View File

@ -12,7 +12,6 @@ import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class AuthMeBlockListener implements Listener { public class AuthMeBlockListener implements Listener {
private DataSource data; private DataSource data;
@ -61,7 +60,8 @@ public class AuthMeBlockListener implements Listener {
return; return;
} }
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return; return;
} }

View File

@ -14,7 +14,6 @@ import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class AuthMeChestShopListener implements Listener { public class AuthMeChestShopListener implements Listener {
public DataSource database; public DataSource database;

View File

@ -18,7 +18,6 @@ import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.plugin.manager.CombatTagComunicator; import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class AuthMeEntityListener implements Listener { public class AuthMeEntityListener implements Listener {
private DataSource data; private DataSource data;
@ -44,14 +43,12 @@ public class AuthMeEntityListener implements Listener{
return; return;
} }
if(instance.citizens.isNPC(entity, instance)) if (instance.citizens.isNPC(entity, instance)) return;
return;
Player player = (Player) entity; Player player = (Player) entity;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if(CombatTagComunicator.isNPC(player)) if (CombatTagComunicator.isNPC(player)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(name)) { if (PlayerCache.getInstance().isAuthenticated(name)) {
return; return;
@ -77,8 +74,7 @@ public class AuthMeEntityListener implements Listener{
return; return;
} }
if(instance.citizens.isNPC(entity, instance)) if (instance.citizens.isNPC(entity, instance)) return;
return;
Player player = (Player) entity; Player player = (Player) entity;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
@ -107,8 +103,7 @@ public class AuthMeEntityListener implements Listener{
return; return;
} }
if(instance.citizens.isNPC(entity, instance)) if (instance.citizens.isNPC(entity, instance)) return;
return;
Player player = (Player) entity; Player player = (Player) entity;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
@ -138,8 +133,7 @@ public class AuthMeEntityListener implements Listener{
return; return;
} }
if(instance.citizens.isNPC(entity, instance)) if (instance.citizens.isNPC(entity, instance)) return;
return;
Player player = (Player) entity; Player player = (Player) entity;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
@ -170,14 +164,15 @@ public class AuthMeEntityListener implements Listener{
Player player = (Player) event.getEntity(); Player player = (Player) event.getEntity();
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { if (Utils.getInstance().isUnrestricted(player)
|| CombatTagComunicator.isNPC(player)) {
return; return;
} }
if(instance.citizens.isNPC(player, instance)) if (instance.citizens.isNPC(player, instance)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return; return;
} }
@ -202,14 +197,15 @@ public class AuthMeEntityListener implements Listener{
Player player = (Player) event.getEntity(); Player player = (Player) event.getEntity();
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { if (Utils.getInstance().isUnrestricted(player)
|| CombatTagComunicator.isNPC(player)) {
return; return;
} }
if(instance.citizens.isNPC(player, instance)) if (instance.citizens.isNPC(player, instance)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return; return;
} }

View File

@ -61,7 +61,6 @@ import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask; import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask; import fr.xephi.authme.task.TimeoutTask;
public class AuthMePlayerListener implements Listener { public class AuthMePlayerListener implements Listener {
public static GameMode gm = GameMode.SURVIVAL; public static GameMode gm = GameMode.SURVIVAL;
@ -82,34 +81,29 @@ public class AuthMePlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (event.isCancelled() || event.getPlayer() == null) if (event.isCancelled() || event.getPlayer() == null) return;
return;
Player player = event.getPlayer(); Player player = event.getPlayer();
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) if (Utils.getInstance().isUnrestricted(player)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(name)) if (PlayerCache.getInstance().isAuthenticated(name)) return;
return;
if (!data.isAuthAvailable(name)) if (!data.isAuthAvailable(name)) if (!Settings.isForcedRegistrationEnabled) return;
if (!Settings.isForcedRegistrationEnabled)
return;
String msg = event.getMessage(); String msg = event.getMessage();
// WorldEdit GUI Shit // WorldEdit GUI Shit
if (msg.equalsIgnoreCase("/worldedit cui")) if (msg.equalsIgnoreCase("/worldedit cui")) return;
return;
String cmd = msg.split(" ")[0]; String cmd = msg.split(" ")[0];
if (cmd.equalsIgnoreCase("/login") || cmd.equalsIgnoreCase("/register") || cmd.equalsIgnoreCase("/passpartu") || cmd.equalsIgnoreCase("/l") || cmd.equalsIgnoreCase("/reg") || cmd.equalsIgnoreCase("/email") || cmd.equalsIgnoreCase("/captcha")) if (cmd.equalsIgnoreCase("/login") || cmd.equalsIgnoreCase("/register")
return; || cmd.equalsIgnoreCase("/passpartu")
if (Settings.useEssentialsMotd && cmd.equalsIgnoreCase("/motd")) || cmd.equalsIgnoreCase("/l") || cmd.equalsIgnoreCase("/reg")
return; || cmd.equalsIgnoreCase("/email")
if (Settings.allowCommands.contains(cmd)) || cmd.equalsIgnoreCase("/captcha")) return;
return; if (Settings.useEssentialsMotd && cmd.equalsIgnoreCase("/motd")) return;
if (Settings.allowCommands.contains(cmd)) return;
event.setMessage("/notloggedin"); event.setMessage("/notloggedin");
event.setCancelled(true); event.setCancelled(true);
@ -117,17 +111,14 @@ public class AuthMePlayerListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onPlayerNormalChat(AsyncPlayerChatEvent event) { public void onPlayerNormalChat(AsyncPlayerChatEvent event) {
if (event.isCancelled() || event.getPlayer() == null) if (event.isCancelled() || event.getPlayer() == null) return;
return;
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final String name = player.getName().toLowerCase(); final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) if (Utils.getInstance().isUnrestricted(player)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(name)) if (PlayerCache.getInstance().isAuthenticated(name)) return;
return;
String cmd = event.getMessage().split(" ")[0]; String cmd = event.getMessage().split(" ")[0];
@ -154,17 +145,14 @@ public class AuthMePlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
public void onPlayerHighChat(AsyncPlayerChatEvent event) { public void onPlayerHighChat(AsyncPlayerChatEvent event) {
if (event.isCancelled() || event.getPlayer() == null) if (event.isCancelled() || event.getPlayer() == null) return;
return;
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final String name = player.getName().toLowerCase(); final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) if (Utils.getInstance().isUnrestricted(player)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(name)) if (PlayerCache.getInstance().isAuthenticated(name)) return;
return;
String cmd = event.getMessage().split(" ")[0]; String cmd = event.getMessage().split(" ")[0];
@ -191,17 +179,14 @@ public class AuthMePlayerListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerChat(AsyncPlayerChatEvent event) { public void onPlayerChat(AsyncPlayerChatEvent event) {
if (event.isCancelled() || event.getPlayer() == null) if (event.isCancelled() || event.getPlayer() == null) return;
return;
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final String name = player.getName().toLowerCase(); final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) if (Utils.getInstance().isUnrestricted(player)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(name)) if (PlayerCache.getInstance().isAuthenticated(name)) return;
return;
String cmd = event.getMessage().split(" ")[0]; String cmd = event.getMessage().split(" ")[0];
@ -228,17 +213,14 @@ public class AuthMePlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerHighestChat(AsyncPlayerChatEvent event) { public void onPlayerHighestChat(AsyncPlayerChatEvent event) {
if (event.isCancelled() || event.getPlayer() == null) if (event.isCancelled() || event.getPlayer() == null) return;
return;
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final String name = player.getName().toLowerCase(); final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) if (Utils.getInstance().isUnrestricted(player)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(name)) if (PlayerCache.getInstance().isAuthenticated(name)) return;
return;
String cmd = event.getMessage().split(" ")[0]; String cmd = event.getMessage().split(" ")[0];
@ -265,17 +247,14 @@ public class AuthMePlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerEarlyChat(AsyncPlayerChatEvent event) { public void onPlayerEarlyChat(AsyncPlayerChatEvent event) {
if (event.isCancelled() || event.getPlayer() == null) if (event.isCancelled() || event.getPlayer() == null) return;
return;
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final String name = player.getName().toLowerCase(); final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) if (Utils.getInstance().isUnrestricted(player)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(name)) if (PlayerCache.getInstance().isAuthenticated(name)) return;
return;
String cmd = event.getMessage().split(" ")[0]; String cmd = event.getMessage().split(" ")[0];
@ -302,17 +281,14 @@ public class AuthMePlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)
public void onPlayerLowChat(AsyncPlayerChatEvent event) { public void onPlayerLowChat(AsyncPlayerChatEvent event) {
if (event.isCancelled() || event.getPlayer() == null) if (event.isCancelled() || event.getPlayer() == null) return;
return;
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final String name = player.getName().toLowerCase(); final String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player)) if (Utils.getInstance().isUnrestricted(player)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(name)) if (PlayerCache.getInstance().isAuthenticated(name)) return;
return;
String cmd = event.getMessage().split(" ")[0]; String cmd = event.getMessage().split(" ")[0];
@ -344,7 +320,9 @@ public class AuthMePlayerListener implements Listener {
Player player = event.getPlayer(); Player player = event.getPlayer();
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { if (plugin.getCitizensCommunicator().isNPC(player, plugin)
|| Utils.getInstance().isUnrestricted(player)
|| CombatTagComunicator.isNPC(player)) {
return; return;
} }
@ -384,53 +362,74 @@ public class AuthMePlayerListener implements Listener {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final String name = player.getName().toLowerCase(); final String name = player.getName().toLowerCase();
if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { if (plugin.getCitizensCommunicator().isNPC(player, plugin)
|| Utils.getInstance().isUnrestricted(player)
|| CombatTagComunicator.isNPC(player)) {
return; return;
} }
if (!Settings.countriesBlacklist.isEmpty()) { if (!Settings.countriesBlacklist.isEmpty()) {
String code = plugin.getCountryCode(event.getAddress().getHostAddress()); String code = plugin.getCountryCode(event.getAddress()
if (((code == null) || (Settings.countriesBlacklist.contains(code) && !API.isRegistered(name))) && !plugin.authmePermissible(player, "authme.bypassantibot")) { .getHostAddress());
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, m._("country_banned")[0]); if (((code == null) || (Settings.countriesBlacklist.contains(code) && !API
.isRegistered(name)))
&& !plugin
.authmePermissible(player, "authme.bypassantibot")) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
m._("country_banned")[0]);
return; return;
} }
} }
if (Settings.enableProtection && !Settings.countries.isEmpty()) { if (Settings.enableProtection && !Settings.countries.isEmpty()) {
String code = plugin.getCountryCode(event.getAddress().getHostAddress()); String code = plugin.getCountryCode(event.getAddress()
if (((code == null) || (!Settings.countries.contains(code) && !API.isRegistered(name))) && !plugin.authmePermissible(player, "authme.bypassantibot")) { .getHostAddress());
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, m._("country_banned")[0]); if (((code == null) || (!Settings.countries.contains(code) && !API
.isRegistered(name)))
&& !plugin
.authmePermissible(player, "authme.bypassantibot")) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
m._("country_banned")[0]);
return; return;
} }
} }
if (Settings.isKickNonRegisteredEnabled) { if (Settings.isKickNonRegisteredEnabled) {
if (!data.isAuthAvailable(name)) { if (!data.isAuthAvailable(name)) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, m._("reg_only")[0]); event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
m._("reg_only")[0]);
return; return;
} }
} }
if (player.isOnline() && Settings.isForceSingleSessionEnabled) { if (player.isOnline() && Settings.isForceSingleSessionEnabled) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, m._("same_nick")[0]); event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
m._("same_nick")[0]);
return; return;
} }
if(data.isAuthAvailable(name) && !LimboCache.getInstance().hasLimboPlayer(name)) { if (data.isAuthAvailable(name)
&& !LimboCache.getInstance().hasLimboPlayer(name)) {
if (!Settings.isSessionsEnabled) { if (!Settings.isSessionsEnabled) {
} else if (PlayerCache.getInstance().isAuthenticated(name)) { } else if (PlayerCache.getInstance().isAuthenticated(name)) {
if(!Settings.sessionExpireOnIpChange) if (!Settings.sessionExpireOnIpChange) if (LimboCache
if(LimboCache.getInstance().hasLimboPlayer(player.getName().toLowerCase())) { .getInstance().hasLimboPlayer(
player.getName().toLowerCase())) {
LimboCache.getInstance().deleteLimboPlayer(name); LimboCache.getInstance().deleteLimboPlayer(name);
} }
} }
} }
//Check if forceSingleSession is set to true, so kick player that has joined with same nick of online player // Check if forceSingleSession is set to true, so kick player that has
// joined with same nick of online player
if (player.isOnline() && Settings.isForceSingleSessionEnabled) { if (player.isOnline() && Settings.isForceSingleSessionEnabled) {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase()); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, m._("same_nick")[0]); player.getName().toLowerCase());
if(PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
m._("same_nick")[0]);
if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
utils.addNormal(player, limbo.getGroup()); utils.addNormal(player, limbo.getGroup());
LimboCache.getInstance().deleteLimboPlayer(player.getName().toLowerCase()); LimboCache.getInstance().deleteLimboPlayer(
player.getName().toLowerCase());
} }
return; return;
} }
@ -441,27 +440,33 @@ public class AuthMePlayerListener implements Listener {
if (name.length() > max || name.length() < min) { if (name.length() > max || name.length() < min) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, m._("name_len")[0]); event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
m._("name_len")[0]);
return; return;
} }
try { try {
if (!player.getName().matches(regex) || name.equals("Player")) { if (!player.getName().matches(regex) || name.equals("Player")) {
try { try {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, m._("regex")[0].replace("REG_EX", regex)); event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
m._("regex")[0].replace("REG_EX", regex));
} catch (Exception exc) { } catch (Exception exc) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "allowed char : " + regex); event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
"allowed char : " + regex);
} }
return; return;
} }
} catch (PatternSyntaxException pse) { } catch (PatternSyntaxException pse) {
if (regex == null || regex.isEmpty()) { if (regex == null || regex.isEmpty()) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "Your nickname do not match"); event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
"Your nickname do not match");
return; return;
} }
try { try {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, m._("regex")[0].replace("REG_EX", regex)); event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
m._("regex")[0].replace("REG_EX", regex));
} catch (Exception exc) { } catch (Exception exc) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "allowed char : " + regex); event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
"allowed char : " + regex);
} }
return; return;
} }
@ -487,17 +492,20 @@ public class AuthMePlayerListener implements Listener {
return; return;
} }
if (plugin.getServer().getOnlinePlayers().length > plugin.getServer().getMaxPlayers()) { if (plugin.getServer().getOnlinePlayers().length > plugin.getServer()
.getMaxPlayers()) {
event.allow(); event.allow();
return; return;
} else { } else {
final Player pl = plugin.generateKickPlayer(plugin.getServer().getOnlinePlayers()); final Player pl = plugin.generateKickPlayer(plugin.getServer()
.getOnlinePlayers());
if (pl != null) { if (pl != null) {
pl.kickPlayer(m._("kick_forvip")[0]); pl.kickPlayer(m._("kick_forvip")[0]);
event.allow(); event.allow();
return; return;
} else { } else {
ConsoleLogger.info("The player " + player.getName() + " wants to join, but the server is full"); ConsoleLogger.info("The player " + player.getName()
+ " wants to join, but the server is full");
event.disallow(Result.KICK_FULL, m._("kick_fullserver")[0]); event.disallow(Result.KICK_FULL, m._("kick_fullserver")[0]);
return; return;
} }
@ -505,22 +513,22 @@ public class AuthMePlayerListener implements Listener {
} }
private void checkAntiBotMod(final PlayerLoginEvent event) { private void checkAntiBotMod(final PlayerLoginEvent event) {
if (plugin.delayedAntiBot || plugin.antibotMod) if (plugin.delayedAntiBot || plugin.antibotMod) return;
return; if (plugin.authmePermissible(event.getPlayer(), "authme.bypassantibot")) return;
if (plugin.authmePermissible(event.getPlayer(), "authme.bypassantibot"))
return;
if (antibot.keySet().size() > Settings.antiBotSensibility) { if (antibot.keySet().size() > Settings.antiBotSensibility) {
plugin.switchAntiBotMod(true); plugin.switchAntiBotMod(true);
for (String s : m._("antibot_auto_enabled")) for (String s : m._("antibot_auto_enabled"))
Bukkit.broadcastMessage(s); Bukkit.broadcastMessage(s);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable(){ Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override @Override
public void run() { public void run() {
if (plugin.antibotMod) { if (plugin.antibotMod) {
plugin.switchAntiBotMod(false); plugin.switchAntiBotMod(false);
antibot.clear(); antibot.clear();
for (String s : m._("antibot_auto_disabled")) for (String s : m._("antibot_auto_disabled"))
Bukkit.broadcastMessage(s.replace("%m", "" + Settings.antiBotDuration)); Bukkit.broadcastMessage(s.replace("%m", ""
+ Settings.antiBotDuration));
} }
} }
}, Settings.antiBotDuration * 1200); }, Settings.antiBotDuration * 1200);
@ -547,14 +555,17 @@ public class AuthMePlayerListener implements Listener {
gameMode.put(name, gm); gameMode.put(name, gm);
BukkitScheduler sched = plugin.getServer().getScheduler(); BukkitScheduler sched = plugin.getServer().getScheduler();
if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { if (plugin.getCitizensCommunicator().isNPC(player, plugin)
|| Utils.getInstance().isUnrestricted(player)
|| CombatTagComunicator.isNPC(player)) {
return; return;
} }
if (plugin.ess != null && Settings.disableSocialSpy) { if (plugin.ess != null && Settings.disableSocialSpy) {
try { try {
plugin.ess.getUser(player.getName()).setSocialSpyEnabled(false); plugin.ess.getUser(player.getName()).setSocialSpyEnabled(false);
} catch (Exception e) {} } catch (Exception e) {
}
} }
String ip = plugin.getIP(player); String ip = plugin.getIP(player);
@ -564,11 +575,13 @@ public class AuthMePlayerListener implements Listener {
player.setGameMode(gM); player.setGameMode(gM);
this.causeByAuthMe = false; this.causeByAuthMe = false;
player.kickPlayer("You are not the Owner of this account, please try another name!"); player.kickPlayer("You are not the Owner of this account, please try another name!");
if (Settings.banUnsafeIp) if (Settings.banUnsafeIp) plugin.getServer().banIP(ip);
plugin.getServer().banIP(ip);
return; return;
} }
if(Settings.getMaxJoinPerIp > 0 && !plugin.authmePermissible(player, "authme.allow2accounts") && !ip.equalsIgnoreCase("127.0.0.1") && !ip.equalsIgnoreCase("localhost")) { if (Settings.getMaxJoinPerIp > 0
&& !plugin.authmePermissible(player, "authme.allow2accounts")
&& !ip.equalsIgnoreCase("127.0.0.1")
&& !ip.equalsIgnoreCase("localhost")) {
if (plugin.hasJoinedIp(player.getName(), ip)) { if (plugin.hasJoinedIp(player.getName(), ip)) {
player.kickPlayer("A player with the same IP is already in game!"); player.kickPlayer("A player with the same IP is already in game!");
return; return;
@ -580,8 +593,10 @@ public class AuthMePlayerListener implements Listener {
long timeout = Settings.getSessionTimeout * 60000; long timeout = Settings.getSessionTimeout * 60000;
long lastLogin = auth.getLastLogin(); long lastLogin = auth.getLastLogin();
long cur = new Date().getTime(); long cur = new Date().getTime();
if((cur - lastLogin < timeout || timeout == 0) && !auth.getIp().equals("198.18.0.1") ) { if ((cur - lastLogin < timeout || timeout == 0)
if (auth.getNickname().equalsIgnoreCase(name) && auth.getIp().equals(ip) ) { && !auth.getIp().equals("198.18.0.1")) {
if (auth.getNickname().equalsIgnoreCase(name)
&& auth.getIp().equals(ip)) {
if (PlayerCache.getInstance().getAuth(name) != null) { if (PlayerCache.getInstance().getAuth(name) != null) {
PlayerCache.getInstance().updatePlayer(auth); PlayerCache.getInstance().updatePlayer(auth);
} else { } else {
@ -591,7 +606,8 @@ public class AuthMePlayerListener implements Listener {
m._(player, "valid_session"); m._(player, "valid_session");
// Restore Permission Group // Restore Permission Group
utils.setGroup(player, Utils.groupType.LOGGEDIN); utils.setGroup(player, Utils.groupType.LOGGEDIN);
plugin.getServer().getPluginManager().callEvent(new SessionEvent(auth, true)); plugin.getServer().getPluginManager()
.callEvent(new SessionEvent(auth, true));
return; return;
} else if (!Settings.sessionExpireOnIpChange) { } else if (!Settings.sessionExpireOnIpChange) {
GameMode gM = gameMode.get(name); GameMode gM = gameMode.get(name);
@ -601,7 +617,8 @@ public class AuthMePlayerListener implements Listener {
player.kickPlayer(m._("unvalid_session")[0]); player.kickPlayer(m._("unvalid_session")[0]);
return; return;
} else if (auth.getNickname().equalsIgnoreCase(name)) { } else if (auth.getNickname().equalsIgnoreCase(name)) {
if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) { if (Settings.isForceSurvivalModeEnabled
&& !Settings.forceOnlyAfterLogin) {
this.causeByAuthMe = true; this.causeByAuthMe = true;
Utils.forceGM(player); Utils.forceGM(player);
this.causeByAuthMe = false; this.causeByAuthMe = false;
@ -624,27 +641,38 @@ public class AuthMePlayerListener implements Listener {
} }
} }
// isent in session or session was ended correctly // isent in session or session was ended correctly
if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) { if (Settings.isForceSurvivalModeEnabled
&& !Settings.forceOnlyAfterLogin) {
this.causeByAuthMe = true; this.causeByAuthMe = true;
Utils.forceGM(player); Utils.forceGM(player);
this.causeByAuthMe = false; this.causeByAuthMe = false;
} }
if (!Settings.noTeleport) if (!Settings.noTeleport) if (Settings.isTeleportToSpawnEnabled
if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) { || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name)); .contains(player.getWorld().getName()))) {
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player,
player.getLocation(), spawnLoc, PlayerCache
.getInstance().isAuthenticated(name));
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (player != null && player.isOnline() && tpEvent.getTo() != null) { if (player != null && player.isOnline()
&& tpEvent.getTo() != null) {
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }
} }
} }
placePlayerSafely(player, spawnLoc); placePlayerSafely(player, spawnLoc);
LimboCache.getInstance().updateLimboPlayer(player); LimboCache.getInstance().updateLimboPlayer(player);
DataFileCache dataFile = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(),LimboCache.getInstance().getLimboPlayer(name).getArmour()); DataFileCache dataFile = new DataFileCache(LimboCache.getInstance()
playerBackup.createCache(name, dataFile, LimboCache.getInstance().getLimboPlayer(name).getGroup(),LimboCache.getInstance().getLimboPlayer(name).getOperator(),LimboCache.getInstance().getLimboPlayer(name).isFlying()); .getLimboPlayer(name).getInventory(), LimboCache
.getInstance().getLimboPlayer(name).getArmour());
playerBackup.createCache(name, dataFile, LimboCache.getInstance()
.getLimboPlayer(name).getGroup(), LimboCache.getInstance()
.getLimboPlayer(name).getOperator(), LimboCache
.getInstance().getLimboPlayer(name).isFlying());
} else { } else {
if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) { if (Settings.isForceSurvivalModeEnabled
&& !Settings.forceOnlyAfterLogin) {
this.causeByAuthMe = true; this.causeByAuthMe = true;
Utils.forceGM(player); Utils.forceGM(player);
this.causeByAuthMe = false; this.causeByAuthMe = false;
@ -652,12 +680,16 @@ public class AuthMePlayerListener implements Listener {
if (!Settings.unRegisteredGroup.isEmpty()) { if (!Settings.unRegisteredGroup.isEmpty()) {
utils.setGroup(player, Utils.groupType.UNREGISTERED); utils.setGroup(player, Utils.groupType.UNREGISTERED);
} }
if (!Settings.noTeleport) if (!Settings.noTeleport) if (Settings.isTeleportToSpawnEnabled
if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) { || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name)); .contains(player.getWorld().getName()))) {
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player,
player.getLocation(), spawnLoc, PlayerCache
.getInstance().isAuthenticated(name));
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (player != null && player.isOnline() && tpEvent.getTo() != null) { if (player != null && player.isOnline()
&& tpEvent.getTo() != null) {
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }
} }
@ -669,52 +701,59 @@ public class AuthMePlayerListener implements Listener {
} }
if (Settings.protectInventoryBeforeLogInEnabled) { if (Settings.protectInventoryBeforeLogInEnabled) {
try { try {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase()); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(
ProtectInventoryEvent ev = new ProtectInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); player.getName().toLowerCase());
ProtectInventoryEvent ev = new ProtectInventoryEvent(player,
limbo.getInventory(), limbo.getArmour());
plugin.getServer().getPluginManager().callEvent(ev); plugin.getServer().getPluginManager().callEvent(ev);
if (ev.isCancelled()) { if (ev.isCancelled()) {
if (!Settings.noConsoleSpam) if (!Settings.noConsoleSpam) ConsoleLogger
ConsoleLogger.info("ProtectInventoryEvent has been cancelled for " + player.getName() + " ..."); .info("ProtectInventoryEvent has been cancelled for "
+ player.getName() + " ...");
} else { } else {
API.setPlayerInventory(player, ev.getEmptyInventory(), ev.getEmptyArmor()); API.setPlayerInventory(player, ev.getEmptyInventory(),
ev.getEmptyArmor());
} }
} catch (NullPointerException ex) { } catch (NullPointerException ex) {
} }
} }
String[] msg; String[] msg;
if (Settings.emailRegistration) { if (Settings.emailRegistration) {
msg = data.isAuthAvailable(name) ? m._("login_msg") : m._("reg_email_msg"); msg = data.isAuthAvailable(name) ? m._("login_msg") : m
._("reg_email_msg");
} else { } else {
msg = data.isAuthAvailable(name) ? m._("login_msg") : m._("reg_msg"); msg = data.isAuthAvailable(name) ? m._("login_msg") : m
._("reg_msg");
} }
int time = Settings.getRegistrationTimeout * 20; int time = Settings.getRegistrationTimeout * 20;
int msgInterval = Settings.getWarnMessageInterval; int msgInterval = Settings.getWarnMessageInterval;
if (time != 0) { if (time != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), time); int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(
if(!LimboCache.getInstance().hasLimboPlayer(name)) plugin, name), time);
LimboCache.getInstance().addLimboPlayer(player); if (!LimboCache.getInstance().hasLimboPlayer(name)) LimboCache
.getInstance().addLimboPlayer(player);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
} }
if(!LimboCache.getInstance().hasLimboPlayer(name)) if (!LimboCache.getInstance().hasLimboPlayer(name)) LimboCache
LimboCache.getInstance().addLimboPlayer(player); .getInstance().addLimboPlayer(player);
if (data.isAuthAvailable(name)) { if (data.isAuthAvailable(name)) {
utils.setGroup(player, groupType.NOTLOGGEDIN); utils.setGroup(player, groupType.NOTLOGGEDIN);
} else { } else {
utils.setGroup(player, groupType.UNREGISTERED); utils.setGroup(player, groupType.UNREGISTERED);
} }
if(player.isOp()) if (player.isOp()) player.setOp(false);
player.setOp(false);
if (!Settings.isMovementAllowed) { if (!Settings.isMovementAllowed) {
player.setAllowFlight(true); player.setAllowFlight(true);
player.setFlying(true); player.setFlying(true);
} }
int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, msg, msgInterval)); int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask(
plugin, name, msg, msgInterval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
player.setNoDamageTicks(Settings.getRegistrationTimeout * 20); player.setNoDamageTicks(Settings.getRegistrationTimeout * 20);
if (Settings.useEssentialsMotd) if (Settings.useEssentialsMotd) player.performCommand("motd");
player.performCommand("motd"); if (Settings.applyBlindEffect) player.addPotionEffect(new PotionEffect(
if (Settings.applyBlindEffect) PotionEffectType.BLINDNESS,
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); Settings.getRegistrationTimeout * 20, 2));
// Remove the join message while the player isn't logging in // Remove the join message while the player isn't logging in
if (Settings.enableProtection || Settings.delayJoinMessage) { if (Settings.enableProtection || Settings.delayJoinMessage) {
@ -725,16 +764,23 @@ public class AuthMePlayerListener implements Listener {
private void placePlayerSafely(Player player, Location spawnLoc) { private void placePlayerSafely(Player player, Location spawnLoc) {
if (!Settings.noTeleport) return; if (!Settings.noTeleport) return;
if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) if (Settings.isTeleportToSpawnEnabled
return; || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds
.contains(player.getWorld().getName()))) return;
Block b = player.getLocation().getBlock(); Block b = player.getLocation().getBlock();
if (b.getType() == Material.PORTAL || b.getType() == Material.ENDER_PORTAL || b.getType() == Material.LAVA || b.getType() == Material.STATIONARY_LAVA) { if (b.getType() == Material.PORTAL
|| b.getType() == Material.ENDER_PORTAL
|| b.getType() == Material.LAVA
|| b.getType() == Material.STATIONARY_LAVA) {
m._(player, "unsafe_spawn"); m._(player, "unsafe_spawn");
player.teleport(spawnLoc); player.teleport(spawnLoc);
return; return;
} }
Block c = player.getLocation().add(0D, 1D, 0D).getBlock(); Block c = player.getLocation().add(0D, 1D, 0D).getBlock();
if (c.getType() == Material.PORTAL || c.getType() == Material.ENDER_PORTAL || c.getType() == Material.LAVA || c.getType() == Material.STATIONARY_LAVA) { if (c.getType() == Material.PORTAL
|| c.getType() == Material.ENDER_PORTAL
|| c.getType() == Material.LAVA
|| c.getType() == Material.STATIONARY_LAVA) {
m._(player, "unsafe_spawn"); m._(player, "unsafe_spawn");
player.teleport(spawnLoc); player.teleport(spawnLoc);
return; return;
@ -751,43 +797,56 @@ public class AuthMePlayerListener implements Listener {
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
Location loc = player.getLocation(); Location loc = player.getLocation();
if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { if (plugin.getCitizensCommunicator().isNPC(player, plugin)
|| Utils.getInstance().isUnrestricted(player)
|| CombatTagComunicator.isNPC(player)) {
return; return;
} }
String ip = plugin.getIP(player); String ip = plugin.getIP(player);
if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead()) { if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead()) {
if(Settings.isSaveQuitLocationEnabled && data.isAuthAvailable(name)) { if (Settings.isSaveQuitLocationEnabled
final PlayerAuth auth = new PlayerAuth(name,loc.getX(),loc.getY(),loc.getZ(),loc.getWorld().getName()); && data.isAuthAvailable(name)) {
final PlayerAuth auth = new PlayerAuth(name, loc.getX(),
loc.getY(), loc.getZ(), loc.getWorld().getName());
try { try {
data.updateQuitLoc(auth); data.updateQuitLoc(auth);
} catch (NullPointerException npe) { } } catch (NullPointerException npe) {
} }
PlayerAuth auth = new PlayerAuth(name, ip, System.currentTimeMillis()); }
PlayerAuth auth = new PlayerAuth(name, ip,
System.currentTimeMillis());
data.updateSession(auth); data.updateSession(auth);
} }
if (data.getAuth(name) != null && !PlayerCache.getInstance().isAuthenticated(name) && Settings.enableProtection) if (data.getAuth(name) != null
event.setQuitMessage(null); && !PlayerCache.getInstance().isAuthenticated(name)
&& Settings.enableProtection) event.setQuitMessage(null);
if (LimboCache.getInstance().hasLimboPlayer(name)) { if (LimboCache.getInstance().hasLimboPlayer(name)) {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if(Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) { if (Settings.protectInventoryBeforeLogInEnabled
RestoreInventoryEvent ev = new RestoreInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); && player.hasPlayedBefore()) {
RestoreInventoryEvent ev = new RestoreInventoryEvent(player,
limbo.getInventory(), limbo.getArmour());
plugin.getServer().getPluginManager().callEvent(ev); plugin.getServer().getPluginManager().callEvent(ev);
if (!ev.isCancelled()) { if (!ev.isCancelled()) {
API.setPlayerInventory(player, ev.getInventory(), ev.getArmor()); API.setPlayerInventory(player, ev.getInventory(),
ev.getArmor());
} }
} }
utils.addNormal(player, limbo.getGroup()); utils.addNormal(player, limbo.getGroup());
player.setOp(limbo.getOperator()); player.setOp(limbo.getOperator());
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { if (player.getGameMode() != GameMode.CREATIVE
&& !Settings.isMovementAllowed) {
player.setAllowFlight(limbo.isFlying()); player.setAllowFlight(limbo.isFlying());
player.setFlying(limbo.isFlying()); player.setFlying(limbo.isFlying());
} }
this.plugin.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId()); this.plugin.getServer().getScheduler()
this.plugin.getServer().getScheduler().cancelTask(limbo.getMessageTaskId()); .cancelTask(limbo.getTimeoutTaskId());
this.plugin.getServer().getScheduler()
.cancelTask(limbo.getMessageTaskId());
LimboCache.getInstance().deleteLimboPlayer(name); LimboCache.getInstance().deleteLimboPlayer(name);
if (playerBackup.doesCacheExist(name)) { if (playerBackup.doesCacheExist(name)) {
playerBackup.removeCache(name); playerBackup.removeCache(name);
@ -815,12 +874,15 @@ public class AuthMePlayerListener implements Listener {
Player player = event.getPlayer(); Player player = event.getPlayer();
Location loc = player.getLocation(); Location loc = player.getLocation();
if ((plugin.getCitizensCommunicator().isNPC(player, plugin)) || (Utils.getInstance().isUnrestricted(player)) || (CombatTagComunicator.isNPC(player))) { if ((plugin.getCitizensCommunicator().isNPC(player, plugin))
|| (Utils.getInstance().isUnrestricted(player))
|| (CombatTagComunicator.isNPC(player))) {
return; return;
} }
if ((Settings.isForceSingleSessionEnabled) && if ((Settings.isForceSingleSessionEnabled)
(event.getReason().contains("You logged in from another location"))) { && (event.getReason()
.contains("You logged in from another location"))) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
@ -828,40 +890,49 @@ public class AuthMePlayerListener implements Listener {
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
String ip = plugin.getIP(player); String ip = plugin.getIP(player);
if ((PlayerCache.getInstance().isAuthenticated(name)) && (!player.isDead())) { if ((PlayerCache.getInstance().isAuthenticated(name))
if ((Settings.isSaveQuitLocationEnabled) && data.isAuthAvailable(name)){ && (!player.isDead())) {
final PlayerAuth auth = new PlayerAuth(name, loc.getX(), loc.getY(), loc.getZ(),loc.getWorld().getName()); if ((Settings.isSaveQuitLocationEnabled)
&& data.isAuthAvailable(name)) {
final PlayerAuth auth = new PlayerAuth(name, loc.getX(),
loc.getY(), loc.getZ(), loc.getWorld().getName());
try { try {
data.updateQuitLoc(auth); data.updateQuitLoc(auth);
} catch (NullPointerException npe) { } } catch (NullPointerException npe) {
} }
PlayerAuth auth = new PlayerAuth(name, ip, System.currentTimeMillis()); }
PlayerAuth auth = new PlayerAuth(name, ip,
System.currentTimeMillis());
data.updateSession(auth); data.updateSession(auth);
} }
if (data.getAuth(name) != null && !PlayerCache.getInstance().isAuthenticated(name) && Settings.enableProtection) if (data.getAuth(name) != null
event.setLeaveMessage(null); && !PlayerCache.getInstance().isAuthenticated(name)
&& Settings.enableProtection) event.setLeaveMessage(null);
if (LimboCache.getInstance().hasLimboPlayer(name)) if (LimboCache.getInstance().hasLimboPlayer(name)) {
{
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (Settings.protectInventoryBeforeLogInEnabled) { if (Settings.protectInventoryBeforeLogInEnabled) {
try { try {
RestoreInventoryEvent ev = new RestoreInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); RestoreInventoryEvent ev = new RestoreInventoryEvent(
player, limbo.getInventory(), limbo.getArmour());
plugin.getServer().getPluginManager().callEvent(ev); plugin.getServer().getPluginManager().callEvent(ev);
if (!ev.isCancelled()) { if (!ev.isCancelled()) {
API.setPlayerInventory(player, ev.getInventory(), ev.getArmor()); API.setPlayerInventory(player, ev.getInventory(),
ev.getArmor());
} }
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
ConsoleLogger.showError("Problem while restore " + name + " inventory after a kick"); ConsoleLogger.showError("Problem while restore " + name
+ " inventory after a kick");
} }
} }
if (!Settings.noTeleport) if (!Settings.noTeleport) try {
try { AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player,
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, limbo.getLoc()); limbo.getLoc());
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (player != null && player.isOnline() && tpEvent.getTo() != null) { if (player != null && player.isOnline()
&& tpEvent.getTo() != null) {
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }
} }
@ -869,12 +940,15 @@ public class AuthMePlayerListener implements Listener {
} }
this.utils.addNormal(player, limbo.getGroup()); this.utils.addNormal(player, limbo.getGroup());
player.setOp(limbo.getOperator()); player.setOp(limbo.getOperator());
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { if (player.getGameMode() != GameMode.CREATIVE
&& !Settings.isMovementAllowed) {
player.setAllowFlight(limbo.isFlying()); player.setAllowFlight(limbo.isFlying());
player.setFlying(limbo.isFlying()); player.setFlying(limbo.isFlying());
} }
this.plugin.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId()); this.plugin.getServer().getScheduler()
this.plugin.getServer().getScheduler().cancelTask(limbo.getMessageTaskId()); .cancelTask(limbo.getTimeoutTaskId());
this.plugin.getServer().getScheduler()
.cancelTask(limbo.getMessageTaskId());
LimboCache.getInstance().deleteLimboPlayer(name); LimboCache.getInstance().deleteLimboPlayer(name);
if (this.playerBackup.doesCacheExist(name)) { if (this.playerBackup.doesCacheExist(name)) {
this.playerBackup.removeCache(name); this.playerBackup.removeCache(name);
@ -885,7 +959,8 @@ public class AuthMePlayerListener implements Listener {
if (gameMode.containsKey(name)) gameMode.remove(name); if (gameMode.containsKey(name)) gameMode.remove(name);
try { try {
player.getVehicle().eject(); player.getVehicle().eject();
} catch (NullPointerException ex) {} } catch (NullPointerException ex) {
}
player.saveData(); player.saveData();
} }
@ -902,10 +977,10 @@ public class AuthMePlayerListener implements Listener {
return; return;
} }
if(plugin.getCitizensCommunicator().isNPC(player, plugin)) if (plugin.getCitizensCommunicator().isNPC(player, plugin)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return; return;
} }
@ -929,10 +1004,10 @@ public class AuthMePlayerListener implements Listener {
return; return;
} }
if(plugin.getCitizensCommunicator().isNPC(player, plugin)) if (plugin.getCitizensCommunicator().isNPC(player, plugin)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return; return;
} }
@ -941,8 +1016,9 @@ public class AuthMePlayerListener implements Listener {
return; return;
} }
} }
if (event.getClickedBlock() != null && event.getClickedBlock().getType() != Material.AIR) if (event.getClickedBlock() != null
event.setUseInteractedBlock(org.bukkit.event.Event.Result.DENY); && event.getClickedBlock().getType() != Material.AIR) event
.setUseInteractedBlock(org.bukkit.event.Event.Result.DENY);
event.setUseItemInHand(org.bukkit.event.Event.Result.DENY); event.setUseItemInHand(org.bukkit.event.Event.Result.DENY);
event.setCancelled(true); event.setCancelled(true);
} }
@ -957,10 +1033,10 @@ public class AuthMePlayerListener implements Listener {
return; return;
} }
if(plugin.getCitizensCommunicator().isNPC(player, plugin)) if (plugin.getCitizensCommunicator().isNPC(player, plugin)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return; return;
} }
@ -984,10 +1060,10 @@ public class AuthMePlayerListener implements Listener {
return; return;
} }
if(plugin.getCitizensCommunicator().isNPC(player, plugin)) if (plugin.getCitizensCommunicator().isNPC(player, plugin)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return; return;
} }
@ -1009,11 +1085,14 @@ public class AuthMePlayerListener implements Listener {
Player player = event.getPlayer(); Player player = event.getPlayer();
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (plugin.getCitizensCommunicator().isNPC(player, plugin) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { if (plugin.getCitizensCommunicator().isNPC(player, plugin)
|| Utils.getInstance().isUnrestricted(player)
|| CombatTagComunicator.isNPC(player)) {
return; return;
} }
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return; return;
} }
@ -1033,14 +1112,15 @@ public class AuthMePlayerListener implements Listener {
Player player = event.getPlayer(); Player player = event.getPlayer();
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) { if (Utils.getInstance().isUnrestricted(player)
|| CombatTagComunicator.isNPC(player)) {
return; return;
} }
if(plugin.getCitizensCommunicator().isNPC(player, plugin)) if (plugin.getCitizensCommunicator().isNPC(player, plugin)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return; return;
} }
@ -1064,7 +1144,8 @@ public class AuthMePlayerListener implements Listener {
return; return;
} }
if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { if (PlayerCache.getInstance().isAuthenticated(
player.getName().toLowerCase())) {
return; return;
} }
@ -1106,60 +1187,49 @@ public class AuthMePlayerListener implements Listener {
Player player = event.getPlayer(); Player player = event.getPlayer();
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) if (Utils.getInstance().isUnrestricted(player)
return; || CombatTagComunicator.isNPC(player)) return;
if(plugin.getCitizensCommunicator().isNPC(player, plugin)) if (plugin.getCitizensCommunicator().isNPC(player, plugin)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(name)) if (PlayerCache.getInstance().isAuthenticated(name)) return;
return;
if (!data.isAuthAvailable(name)) if (!data.isAuthAvailable(name)) if (!Settings.isForcedRegistrationEnabled) return;
if (!Settings.isForcedRegistrationEnabled)
return;
Location spawn = plugin.getSpawnLocation(player); Location spawn = plugin.getSpawnLocation(player);
if (Settings.isSaveQuitLocationEnabled && data.isAuthAvailable(name)) { if (Settings.isSaveQuitLocationEnabled && data.isAuthAvailable(name)) {
final PlayerAuth auth = new PlayerAuth(name,spawn.getX(),spawn.getY(),spawn.getZ(),spawn.getWorld().getName()); final PlayerAuth auth = new PlayerAuth(name, spawn.getX(),
spawn.getY(), spawn.getZ(), spawn.getWorld().getName());
try { try {
data.updateQuitLoc(auth); data.updateQuitLoc(auth);
} catch (NullPointerException npe) { } } catch (NullPointerException npe) {
}
} }
event.setRespawnLocation(spawn); event.setRespawnLocation(spawn);
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) { public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) {
if (event.isCancelled()) if (event.isCancelled()) return;
return; if (event.getPlayer() == null || event == null) return;
if (event.getPlayer() == null || event == null) if (!Settings.isForceSurvivalModeEnabled) return;
return;
if (!Settings.isForceSurvivalModeEnabled)
return;
Player player = event.getPlayer(); Player player = event.getPlayer();
if (plugin.authmePermissible(player, "authme.bypassforcesurvival")) if (plugin.authmePermissible(player, "authme.bypassforcesurvival")) return;
return;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) if (Utils.getInstance().isUnrestricted(player)
return; || CombatTagComunicator.isNPC(player)) return;
if(plugin.getCitizensCommunicator().isNPC(player, plugin)) if (plugin.getCitizensCommunicator().isNPC(player, plugin)) return;
return;
if (PlayerCache.getInstance().isAuthenticated(name)) if (PlayerCache.getInstance().isAuthenticated(name)) return;
return;
if (!data.isAuthAvailable(name)) if (!data.isAuthAvailable(name)) if (!Settings.isForcedRegistrationEnabled) return;
if (!Settings.isForcedRegistrationEnabled)
return;
if (this.causeByAuthMe) if (this.causeByAuthMe) return;
return;
event.setCancelled(true); event.setCancelled(true);
} }
} }

View File

@ -26,10 +26,12 @@ public class AuthMeServerListener implements Listener {
if (!Settings.enableProtection) return; if (!Settings.enableProtection) return;
if (Settings.countries.isEmpty()) return; if (Settings.countries.isEmpty()) return;
if (!Settings.countriesBlacklist.isEmpty()) { if (!Settings.countriesBlacklist.isEmpty()) {
if(Settings.countriesBlacklist.contains(plugin.getCountryCode(event.getAddress().getHostAddress()))) if (Settings.countriesBlacklist.contains(plugin
event.setMotd(m._("country_banned")[0]); .getCountryCode(event.getAddress().getHostAddress()))) event
.setMotd(m._("country_banned")[0]);
} }
if(Settings.countries.contains(plugin.getCountryCode(event.getAddress().getHostAddress()))) { if (Settings.countries.contains(plugin.getCountryCode(event
.getAddress().getHostAddress()))) {
event.setMotd(plugin.getServer().getMotd()); event.setMotd(plugin.getServer().getMotd());
} else { } else {
event.setMotd(m._("country_banned")[0]); event.setMotd(m._("country_banned")[0]);
@ -72,26 +74,24 @@ public class AuthMeServerListener implements Listener {
} }
if (pluginName.equalsIgnoreCase("Vault")) { if (pluginName.equalsIgnoreCase("Vault")) {
plugin.permission = null; plugin.permission = null;
ConsoleLogger.showError("Vault has been disabled, unhook permissions!"); ConsoleLogger
.showError("Vault has been disabled, unhook permissions!");
} }
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPluginEnable(PluginEnableEvent event) { public void onPluginEnable(PluginEnableEvent event) {
String pluginName = event.getPlugin().getName(); String pluginName = event.getPlugin().getName();
if(pluginName.equalsIgnoreCase("Essentials") || pluginName.equalsIgnoreCase("EssentialsSpawn")) if (pluginName.equalsIgnoreCase("Essentials")
plugin.checkEssentials(); || pluginName.equalsIgnoreCase("EssentialsSpawn")) plugin
if(pluginName.equalsIgnoreCase("Multiverse-Core")) .checkEssentials();
plugin.checkMultiverse(); if (pluginName.equalsIgnoreCase("Multiverse-Core")) plugin
if(pluginName.equalsIgnoreCase("Notifications")) .checkMultiverse();
plugin.checkNotifications(); if (pluginName.equalsIgnoreCase("Notifications")) plugin
if(pluginName.equalsIgnoreCase("ChestShop")) .checkNotifications();
plugin.checkChestShop(); if (pluginName.equalsIgnoreCase("ChestShop")) plugin.checkChestShop();
if(pluginName.equalsIgnoreCase("CombatTag")) if (pluginName.equalsIgnoreCase("CombatTag")) plugin.combatTag();
plugin.combatTag(); if (pluginName.equalsIgnoreCase("Citizens")) plugin.citizensVersion();
if(pluginName.equalsIgnoreCase("Citizens")) if (pluginName.equalsIgnoreCase("Vault")) plugin.checkVault();
plugin.citizensVersion();
if(pluginName.equalsIgnoreCase("Vault"))
plugin.checkVault();
} }
} }

View File

@ -19,8 +19,11 @@ public class AuthMeSpoutListener implements Listener {
@EventHandler @EventHandler
public void onSpoutCraftEnable(final SpoutCraftEnableEvent event) { public void onSpoutCraftEnable(final SpoutCraftEnableEvent event) {
if (SpoutCfg.getInstance().getBoolean("LoginScreen.enabled")) { if (SpoutCfg.getInstance().getBoolean("LoginScreen.enabled")) {
if (data.isAuthAvailable(event.getPlayer().getName().toLowerCase()) && !PlayerCache.getInstance().isAuthenticated(event.getPlayer().getName().toLowerCase()) ) { if (data.isAuthAvailable(event.getPlayer().getName().toLowerCase())
event.getPlayer().getMainScreen().attachPopupScreen(new LoginScreen(event.getPlayer())); && !PlayerCache.getInstance().isAuthenticated(
event.getPlayer().getName().toLowerCase())) {
event.getPlayer().getMainScreen()
.attachPopupScreen(new LoginScreen(event.getPlayer()));
} }
} }
} }

View File

@ -13,22 +13,24 @@ public class BungeeCordMessage implements PluginMessageListener {
public AuthMe plugin; public AuthMe plugin;
public BungeeCordMessage(AuthMe plugin) public BungeeCordMessage(AuthMe plugin) {
{
this.plugin = plugin; this.plugin = plugin;
} }
@Override @Override
public void onPluginMessageReceived(String channel, Player player, byte[] message) { public void onPluginMessageReceived(String channel, Player player,
byte[] message) {
if (!channel.equals("BungeeCord")) { if (!channel.equals("BungeeCord")) {
return; return;
} }
try { try {
final DataInputStream in = new DataInputStream(new ByteArrayInputStream(message)); final DataInputStream in = new DataInputStream(
new ByteArrayInputStream(message));
String subchannel = in.readUTF(); String subchannel = in.readUTF();
if (subchannel.equals("IP")) { // We need only the IP channel if (subchannel.equals("IP")) { // We need only the IP channel
String ip = in.readUTF(); String ip = in.readUTF();
plugin.realIp.put(player.getName().toLowerCase(), ip); //Put the IP (only the ip not the port) in the hashmap plugin.realIp.put(player.getName().toLowerCase(), ip);
// Put the IP (only the ip not the port) in the hashmap
} }
} catch (IOException ex) { } catch (IOException ex) {
} }

View File

@ -12,13 +12,15 @@ public abstract class CombatTagComunicator {
/** /**
* Returns if the entity is an NPC * Returns if the entity is an NPC
*
* @param player * @param player
* @return true if the player is an NPC * @return true if the player is an NPC
*/ */
public static boolean isNPC(Entity player) { public static boolean isNPC(Entity player) {
try { try {
if (Bukkit.getServer().getPluginManager().getPlugin("CombatTag") != null) { if (Bukkit.getServer().getPluginManager().getPlugin("CombatTag") != null) {
combatApi = new CombatTagApi((CombatTag) Bukkit.getServer().getPluginManager().getPlugin("CombatTag")); combatApi = new CombatTagApi((CombatTag) Bukkit.getServer()
.getPluginManager().getPlugin("CombatTag"));
try { try {
combatApi.getClass().getMethod("isNPC"); combatApi.getClass().getMethod("isNPC");
} catch (Exception e) { } catch (Exception e) {

View File

@ -27,8 +27,15 @@ public class EssSpawn extends CustomConfiguration {
public Location getLocation() { public Location getLocation() {
try { try {
if (!this.contains("spawns.default.world")) return null; if (!this.contains("spawns.default.world")) return null;
if (this.getString("spawns.default.world").isEmpty() || this.getString("spawns.default.world") == "") return null; if (this.getString("spawns.default.world").isEmpty()
Location location = new Location(Bukkit.getWorld(this.getString("spawns.default.world")), this.getDouble("spawns.default.x"), this.getDouble("spawns.default.y"), this.getDouble("spawns.default.z"), Float.parseFloat(this.getString("spawns.default.yaw")), Float.parseFloat(this.getString("spawns.default.pitch"))); || this.getString("spawns.default.world") == "") return null;
Location location = new Location(Bukkit.getWorld(this
.getString("spawns.default.world")),
this.getDouble("spawns.default.x"),
this.getDouble("spawns.default.y"),
this.getDouble("spawns.default.z"), Float.parseFloat(this
.getString("spawns.default.yaw")),
Float.parseFloat(this.getString("spawns.default.pitch")));
return location; return location;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return null; return null;

View File

@ -12,7 +12,8 @@ import fr.xephi.authme.settings.Settings;
/** /**
* *
* @authors Xephi59, <a href="http://dev.bukkit.org/profiles/Possible/">Possible</a> * @authors Xephi59, <a
* href="http://dev.bukkit.org/profiles/Possible/">Possible</a>
* *
*/ */
public class Management extends Thread { public class Management extends Thread {
@ -30,11 +31,15 @@ public class Management extends Thread {
public void run() { public void run() {
} }
public void performLogin(final Player player, final String password, final boolean forceLogin) { public void performLogin(final Player player, final String password,
new AsyncronousLogin(player, password, forceLogin, plugin, database).process(); final boolean forceLogin) {
new AsyncronousLogin(player, password, forceLogin, plugin, database)
.process();
} }
public void performRegister(final Player player, final String password, final String email) { public void performRegister(final Player player, final String password,
new AsyncronousRegister(player, password, email, plugin, database).process(); final String email) {
new AsyncronousRegister(player, password, email, plugin, database)
.process();
} }
} }

View File

@ -32,7 +32,8 @@ public class AsyncronousLogin {
private static RandomString rdm = new RandomString(Settings.captchaLength); private static RandomString rdm = new RandomString(Settings.captchaLength);
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
public AsyncronousLogin(Player player, String password, boolean forceLogin, AuthMe plugin, DataSource data) { public AsyncronousLogin(Player player, String password, boolean forceLogin,
AuthMe plugin, DataSource data) {
this.player = player; this.player = player;
this.password = password; this.password = password;
name = player.getName().toLowerCase(); name = player.getName().toLowerCase();
@ -45,6 +46,7 @@ public class AsyncronousLogin {
protected String getIP() { protected String getIP() {
return plugin.getIP(player); return plugin.getIP(player);
} }
protected boolean needsCaptcha() { protected boolean needsCaptcha() {
if (Settings.useCaptcha) { if (Settings.useCaptcha) {
if (!plugin.captcha.containsKey(name)) { if (!plugin.captcha.containsKey(name)) {
@ -54,13 +56,17 @@ public class AsyncronousLogin {
plugin.captcha.remove(name); plugin.captcha.remove(name);
plugin.captcha.put(name, i); plugin.captcha.put(name, i);
} }
if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) { if (plugin.captcha.containsKey(name)
&& plugin.captcha.get(name) >= Settings.maxLoginTry) {
plugin.cap.put(name, rdm.nextString()); plugin.cap.put(name, rdm.nextString());
for (String s : m._("usage_captcha")) { for (String s : m._("usage_captcha")) {
player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name)).replace("<theCaptcha>", plugin.cap.get(name))); player.sendMessage(s.replace("THE_CAPTCHA",
plugin.cap.get(name)).replace("<theCaptcha>",
plugin.cap.get(name)));
} }
return true; return true;
} else if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) { } else if (plugin.captcha.containsKey(name)
&& plugin.captcha.get(name) >= Settings.maxLoginTry) {
try { try {
plugin.captcha.remove(name); plugin.captcha.remove(name);
plugin.cap.remove(name); plugin.cap.remove(name);
@ -72,7 +78,8 @@ public class AsyncronousLogin {
} }
/** /**
* Checks the precondition for authentication (like user known) and returns the playerAuth-State * Checks the precondition for authentication (like user known) and returns
* the playerAuth-State
*/ */
protected PlayerAuth preAuth() { protected PlayerAuth preAuth() {
if (PlayerCache.getInstance().isAuthenticated(name)) { if (PlayerCache.getInstance().isAuthenticated(name)) {
@ -82,19 +89,28 @@ public class AsyncronousLogin {
if (!database.isAuthAvailable(name)) { if (!database.isAuthAvailable(name)) {
m._(player, "user_unknown"); m._(player, "user_unknown");
if (LimboCache.getInstance().hasLimboPlayer(name)) { if (LimboCache.getInstance().hasLimboPlayer(name)) {
Bukkit.getScheduler().cancelTask(LimboCache.getInstance().getLimboPlayer(name).getMessageTaskId()); Bukkit.getScheduler().cancelTask(
LimboCache.getInstance().getLimboPlayer(name)
.getMessageTaskId());
String[] msg; String[] msg;
if (Settings.emailRegistration) { if (Settings.emailRegistration) {
msg = m._("reg_email_msg"); msg = m._("reg_email_msg");
} else { } else {
msg = m._("reg_msg"); msg = m._("reg_msg");
} }
int msgT = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, msg, Settings.getWarnMessageInterval)); int msgT = Bukkit.getScheduler().scheduleSyncDelayedTask(
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); plugin,
new MessageTask(plugin, name, msg,
Settings.getWarnMessageInterval));
LimboCache.getInstance().getLimboPlayer(name)
.setMessageTaskId(msgT);
} }
return null; return null;
} }
if (Settings.getMaxLoginPerIp > 0 && !plugin.authmePermissible(player, "authme.allow2accounts") && !getIP().equalsIgnoreCase("127.0.0.1") && !getIP().equalsIgnoreCase("localhost")) { if (Settings.getMaxLoginPerIp > 0
&& !plugin.authmePermissible(player, "authme.allow2accounts")
&& !getIP().equalsIgnoreCase("127.0.0.1")
&& !getIP().equalsIgnoreCase("localhost")) {
if (plugin.isLoggedIp(realName, getIP())) { if (plugin.isLoggedIp(realName, getIP())) {
m._(player, "logged_in"); m._(player, "logged_in");
return null; return null;
@ -105,7 +121,8 @@ public class AsyncronousLogin {
m._(player, "user_unknown"); m._(player, "user_unknown");
return null; return null;
} }
if (!Settings.getMySQLColumnGroup.isEmpty() && pAuth.getGroupId() == Settings.getNonActivatedGroup) { if (!Settings.getMySQLColumnGroup.isEmpty()
&& pAuth.getGroupId() == Settings.getNonActivatedGroup) {
m._(player, "vb_nonActiv"); m._(player, "vb_nonActiv");
return null; return null;
} }
@ -114,22 +131,22 @@ public class AsyncronousLogin {
public void process() { public void process() {
PlayerAuth pAuth = preAuth(); PlayerAuth pAuth = preAuth();
if (pAuth == null || needsCaptcha()) if (pAuth == null || needsCaptcha()) return;
return;
String hash = pAuth.getHash(); String hash = pAuth.getHash();
String email = pAuth.getEmail(); String email = pAuth.getEmail();
boolean passwordVerified = true; boolean passwordVerified = true;
if (!forceLogin) if (!forceLogin) try {
try { passwordVerified = PasswordSecurity.comparePasswordWithHash(
passwordVerified = PasswordSecurity.comparePasswordWithHash(password, hash, realName); password, hash, realName);
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage()); ConsoleLogger.showError(ex.getMessage());
m._(player, "error"); m._(player, "error");
return; return;
} }
if (passwordVerified && player.isOnline()) { if (passwordVerified && player.isOnline()) {
PlayerAuth auth = new PlayerAuth(name, hash, getIP(), new Date().getTime(), email, realName); PlayerAuth auth = new PlayerAuth(name, hash, getIP(),
new Date().getTime(), email, realName);
database.updateSession(auth); database.updateSession(auth);
if (Settings.useCaptcha) { if (Settings.useCaptcha) {
@ -146,11 +163,12 @@ public class AsyncronousLogin {
displayOtherAccounts(auth, player); displayOtherAccounts(auth, player);
if (!Settings.noConsoleSpam) if (!Settings.noConsoleSpam) ConsoleLogger.info(player.getName()
ConsoleLogger.info(player.getName() + " logged in!"); + " logged in!");
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " logged in!")); plugin.notifications.showNotification(new Notification(
"[AuthMe] " + player.getName() + " logged in!"));
} }
// makes player isLoggedin via API // makes player isLoggedin via API
@ -158,23 +176,39 @@ public class AsyncronousLogin {
database.setLogged(name); database.setLogged(name);
plugin.otherAccounts.addPlayer(player.getUniqueId()); plugin.otherAccounts.addPlayer(player.getUniqueId());
// As the scheduling executes the Task most likely after the current task, we schedule it in the end // As the scheduling executes the Task most likely after the current
// so that we can be sure, and have not to care if it might be processed in other order. // task, we schedule it in the end
ProcessSyncronousPlayerLogin syncronousPlayerLogin = new ProcessSyncronousPlayerLogin(player, plugin, database); // so that we can be sure, and have not to care if it might be
// processed in other order.
ProcessSyncronousPlayerLogin syncronousPlayerLogin = new ProcessSyncronousPlayerLogin(
player, plugin, database);
if (syncronousPlayerLogin.getLimbo() != null) { if (syncronousPlayerLogin.getLimbo() != null) {
player.getServer().getScheduler().cancelTask(syncronousPlayerLogin.getLimbo().getTimeoutTaskId()); player.getServer()
player.getServer().getScheduler().cancelTask(syncronousPlayerLogin.getLimbo().getMessageTaskId()); .getScheduler()
.cancelTask(
syncronousPlayerLogin.getLimbo()
.getTimeoutTaskId());
player.getServer()
.getScheduler()
.cancelTask(
syncronousPlayerLogin.getLimbo()
.getMessageTaskId());
} }
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, syncronousPlayerLogin); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
syncronousPlayerLogin);
} else if (player.isOnline()) { } else if (player.isOnline()) {
if (!Settings.noConsoleSpam) if (!Settings.noConsoleSpam) ConsoleLogger.info(player.getName()
ConsoleLogger.info(player.getName() + " used the wrong password"); + " used the wrong password");
if (Settings.isKickOnWrongPasswordEnabled) { if (Settings.isKickOnWrongPasswordEnabled) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override @Override
public void run() { public void run() {
if (AuthMePlayerListener.gameMode != null && AuthMePlayerListener.gameMode.containsKey(name)) { if (AuthMePlayerListener.gameMode != null
player.setGameMode(AuthMePlayerListener.gameMode.get(name)); && AuthMePlayerListener.gameMode
.containsKey(name)) {
player.setGameMode(AuthMePlayerListener.gameMode
.get(name));
} }
player.kickPlayer(m._("wrong_pwd")[0]); player.kickPlayer(m._("wrong_pwd")[0]);
} }
@ -184,7 +218,8 @@ public class AsyncronousLogin {
return; return;
} }
} else { } else {
ConsoleLogger.showError("Player " + name + " wasn't online during login process, aborted... "); ConsoleLogger.showError("Player " + name
+ " wasn't online during login process, aborted... ");
} }
} }
@ -196,7 +231,8 @@ public class AsyncronousLogin {
return; return;
} }
List<String> auths = this.database.getAllAuthsByName(auth); List<String> auths = this.database.getAllAuthsByName(auth);
//List<String> uuidlist = plugin.otherAccounts.getAllPlayersByUUID(player.getUniqueId()); // List<String> uuidlist =
// plugin.otherAccounts.getAllPlayersByUUID(player.getUniqueId());
if (auths.isEmpty() || auths == null) { if (auths.isEmpty() || auths == null) {
return; return;
} }
@ -204,7 +240,8 @@ public class AsyncronousLogin {
return; return;
} }
String message = "[AuthMe] "; String message = "[AuthMe] ";
//String uuidaccounts = "[AuthMe] PlayerNames has %size% links to this UUID : "; // String uuidaccounts =
// "[AuthMe] PlayerNames has %size% links to this UUID : ";
int i = 0; int i = 0;
for (String account : auths) { for (String account : auths) {
i++; i++;
@ -215,23 +252,19 @@ public class AsyncronousLogin {
message = message + "."; message = message + ".";
} }
} }
/*TODO: Active uuid system /*
i = 0; * TODO: Active uuid system i = 0; for (String account : uuidlist) {
for (String account : uuidlist) { * i++; uuidaccounts = uuidaccounts + account; if (i != auths.size()) {
i++; * uuidaccounts = uuidaccounts + ", "; } else { uuidaccounts =
uuidaccounts = uuidaccounts + account; * uuidaccounts + "."; } }
if (i != auths.size()) { */
uuidaccounts = uuidaccounts + ", ";
} else {
uuidaccounts = uuidaccounts + ".";
}
}*/
for (Player player : plugin.getServer().getOnlinePlayers()) { for (Player player : plugin.getServer().getOnlinePlayers()) {
if (plugin.authmePermissible(player, "authme.seeOtherAccounts")) { if (plugin.authmePermissible(player, "authme.seeOtherAccounts")) {
player.sendMessage("[AuthMe] The player " + auth.getNickname() + " has " player.sendMessage("[AuthMe] The player " + auth.getNickname()
+ auths.size() + " accounts"); + " has " + auths.size() + " accounts");
player.sendMessage(message); player.sendMessage(message);
//player.sendMessage(uuidaccounts.replace("%size%", ""+uuidlist.size())); // player.sendMessage(uuidaccounts.replace("%size%",
// ""+uuidlist.size()));
} }
} }
} }

View File

@ -33,7 +33,8 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
private PluginManager pm; private PluginManager pm;
private FileCache playerCache = new FileCache(); private FileCache playerCache = new FileCache();
public ProcessSyncronousPlayerLogin(Player player, AuthMe plugin, DataSource data) { public ProcessSyncronousPlayerLogin(Player player, AuthMe plugin,
DataSource data) {
this.plugin = plugin; this.plugin = plugin;
this.database = data; this.database = data;
this.pm = plugin.getServer().getPluginManager(); this.pm = plugin.getServer().getPluginManager();
@ -49,18 +50,21 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
protected void restoreOpState() { protected void restoreOpState() {
player.setOp(limbo.getOperator()); player.setOp(limbo.getOperator());
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { if (player.getGameMode() != GameMode.CREATIVE
&& !Settings.isMovementAllowed) {
player.setAllowFlight(limbo.isFlying()); player.setAllowFlight(limbo.isFlying());
player.setFlying(limbo.isFlying()); player.setFlying(limbo.isFlying());
} }
} }
protected void packQuitLocation() { protected void packQuitLocation() {
Utils.getInstance().packCoords(auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), player); Utils.getInstance().packCoords(auth.getQuitLocX(), auth.getQuitLocY(),
auth.getQuitLocZ(), auth.getWorld(), player);
} }
protected void teleportBackFromSpawn() { protected void teleportBackFromSpawn() {
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, limbo.getLoc()); AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player,
limbo.getLoc());
pm.callEvent(tpEvent); pm.callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
Location fLoc = tpEvent.getTo(); Location fLoc = tpEvent.getTo();
@ -73,7 +77,8 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
protected void teleportToSpawn() { protected void teleportToSpawn() {
Location spawnL = plugin.getSpawnLocation(player); Location spawnL = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnL, true); SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player,
player.getLocation(), spawnL, true);
pm.callEvent(tpEvent); pm.callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
Location fLoc = tpEvent.getTo(); Location fLoc = tpEvent.getTo();
@ -85,10 +90,12 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
} }
protected void restoreInventory() { protected void restoreInventory() {
RestoreInventoryEvent event = new RestoreInventoryEvent(player, limbo.getInventory(), limbo.getArmour()); RestoreInventoryEvent event = new RestoreInventoryEvent(player,
limbo.getInventory(), limbo.getArmour());
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {
API.setPlayerInventory(player, event.getInventory(), event.getArmor()); API.setPlayerInventory(player, event.getInventory(),
event.getArmor());
} }
} }
@ -96,10 +103,13 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
for (String command : Settings.forceCommands) { for (String command : Settings.forceCommands) {
try { try {
player.performCommand(command.replace("%p", player.getName())); player.performCommand(command.replace("%p", player.getName()));
} catch (Exception e) {} } catch (Exception e) {
}
} }
for (String command : Settings.forceCommandsAsConsole) { for (String command : Settings.forceCommandsAsConsole) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), command.replace("%p", player.getName())); Bukkit.getServer().dispatchCommand(
Bukkit.getServer().getConsoleSender(),
command.replace("%p", player.getName()));
} }
} }
@ -111,23 +121,26 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
restoreOpState(); restoreOpState();
/* /*
* Restore Inventories and GameMode * Restore Inventories and GameMode We need to restore them before
* We need to restore them before teleport the player * teleport the player Cause in AuthMePlayerListener, we call
* Cause in AuthMePlayerListener, we call ProtectInventoryEvent after Teleporting * ProtectInventoryEvent after Teleporting Also it's the current
* Also it's the current world inventory ! * world inventory !
*/ */
if (!Settings.forceOnlyAfterLogin) { if (!Settings.forceOnlyAfterLogin) {
player.setGameMode(limbo.getGameMode()); player.setGameMode(limbo.getGameMode());
// Inventory - Make it after restore GameMode , cause we need to restore the // Inventory - Make it after restore GameMode , cause we need to
// restore the
// right inventory in the right gamemode // right inventory in the right gamemode
if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) { if (Settings.protectInventoryBeforeLogInEnabled
&& player.hasPlayedBefore()) {
restoreInventory(); restoreInventory();
} }
} } else {
else { // Inventory - Make it before force the survival GameMode to
// Inventory - Make it before force the survival GameMode to cancel all // cancel all
// inventory problem // inventory problem
if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) { if (Settings.protectInventoryBeforeLogInEnabled
&& player.hasPlayedBefore()) {
restoreInventory(); restoreInventory();
} }
player.setGameMode(GameMode.SURVIVAL); player.setGameMode(GameMode.SURVIVAL);
@ -135,24 +148,31 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
if (!Settings.noTeleport) { if (!Settings.noTeleport) {
// Teleport // Teleport
if (Settings.isTeleportToSpawnEnabled && !Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())) { if (Settings.isTeleportToSpawnEnabled
if (Settings.isSaveQuitLocationEnabled && auth.getQuitLocY() != 0) { && !Settings.isForceSpawnLocOnJoinEnabled
&& Settings.getForcedWorlds.contains(player.getWorld()
.getName())) {
if (Settings.isSaveQuitLocationEnabled
&& auth.getQuitLocY() != 0) {
packQuitLocation(); packQuitLocation();
} else { } else {
teleportBackFromSpawn(); teleportBackFromSpawn();
} }
} else if (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())) { } else if (Settings.isForceSpawnLocOnJoinEnabled
&& Settings.getForcedWorlds.contains(player.getWorld()
.getName())) {
teleportToSpawn(); teleportToSpawn();
} else if (Settings.isSaveQuitLocationEnabled && auth.getQuitLocY() != 0) { } else if (Settings.isSaveQuitLocationEnabled
&& auth.getQuitLocY() != 0) {
packQuitLocation(); packQuitLocation();
} else { } else {
teleportBackFromSpawn(); teleportBackFromSpawn();
} }
} }
// Re-Force Survival GameMode if we need due to world change specification // Re-Force Survival GameMode if we need due to world change
if (Settings.isForceSurvivalModeEnabled) // specification
Utils.forceGM(player); if (Settings.isForceSurvivalModeEnabled) Utils.forceGM(player);
// Restore Permission Group // Restore Permission Group
Utils.getInstance().setGroup(player, groupType.LOGGEDIN); Utils.getInstance().setGroup(player, groupType.LOGGEDIN);
@ -165,26 +185,29 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
} }
// We can now display the join message // We can now display the join message
if (AuthMePlayerListener.joinMessage.containsKey(name) && AuthMePlayerListener.joinMessage.get(name) != null && !AuthMePlayerListener.joinMessage.get(name).isEmpty()) { if (AuthMePlayerListener.joinMessage.containsKey(name)
&& AuthMePlayerListener.joinMessage.get(name) != null
&& !AuthMePlayerListener.joinMessage.get(name).isEmpty()) {
for (Player p : Bukkit.getServer().getOnlinePlayers()) { for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (p.isOnline()) if (p.isOnline()) p
p.sendMessage(AuthMePlayerListener.joinMessage.get(name)); .sendMessage(AuthMePlayerListener.joinMessage.get(name));
} }
AuthMePlayerListener.joinMessage.remove(name); AuthMePlayerListener.joinMessage.remove(name);
} }
if (Settings.applyBlindEffect) if (Settings.applyBlindEffect) player
player.removePotionEffect(PotionEffectType.BLINDNESS); .removePotionEffect(PotionEffectType.BLINDNESS);
// The Loginevent now fires (as intended) after everything is processed // The Loginevent now fires (as intended) after everything is processed
Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true)); Bukkit.getServer().getPluginManager()
.callEvent(new LoginEvent(player, true));
player.saveData(); player.saveData();
// Login is finish, display welcome message // Login is finish, display welcome message
if(Settings.useWelcomeMessage) if (Settings.useWelcomeMessage) if (Settings.broadcastWelcomeMessage) {
if(Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) { for (String s : Settings.welcomeMsg) {
Bukkit.getServer().broadcastMessage(plugin.replaceAllInfos(s, player)); Bukkit.getServer().broadcastMessage(
plugin.replaceAllInfos(s, player));
} }
} else { } else {
for (String s : Settings.welcomeMsg) { for (String s : Settings.welcomeMsg) {

View File

@ -26,7 +26,8 @@ public class AsyncronousRegister {
private DataSource database; private DataSource database;
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
public AsyncronousRegister(Player player, String password, String email, AuthMe plugin, DataSource data) { public AsyncronousRegister(Player player, String password, String email,
AuthMe plugin, DataSource data) {
this.player = player; this.player = player;
this.password = password; this.password = password;
name = player.getName().toLowerCase(); name = player.getName().toLowerCase();
@ -54,8 +55,9 @@ public class AsyncronousRegister {
String lowpass = password.toLowerCase(); String lowpass = password.toLowerCase();
if ((lowpass.contains("delete") || lowpass.contains("where") if ((lowpass.contains("delete") || lowpass.contains("where")
|| lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("insert") || lowpass.contains("modify")
|| lowpass.contains("select") || lowpass.contains(";") || lowpass.contains("null")) || lowpass.contains("from") || lowpass.contains("select")
|| lowpass.contains(";") || lowpass.contains("null"))
|| !lowpass.matches(Settings.getPassRegex)) { || !lowpass.matches(Settings.getPassRegex)) {
m._(player, "password_error"); m._(player, "password_error");
allowRegister = false; allowRegister = false;
@ -63,14 +65,18 @@ public class AsyncronousRegister {
if (database.isAuthAvailable(player.getName().toLowerCase())) { if (database.isAuthAvailable(player.getName().toLowerCase())) {
m._(player, "user_regged"); m._(player, "user_regged");
if (plugin.pllog.getStringList("players").contains(player.getName())) { if (plugin.pllog.getStringList("players")
.contains(player.getName())) {
plugin.pllog.getStringList("players").remove(player.getName()); plugin.pllog.getStringList("players").remove(player.getName());
} }
allowRegister = false; allowRegister = false;
} }
if (Settings.getmaxRegPerIp > 0) { if (Settings.getmaxRegPerIp > 0) {
if(!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByIp(getIp()).size() >= Settings.getmaxRegPerIp && !getIp().equalsIgnoreCase("127.0.0.1") && !getIp().equalsIgnoreCase("localhost")) { if (!plugin.authmePermissible(player, "authme.allow2accounts")
&& database.getAllAuthsByIp(getIp()).size() >= Settings.getmaxRegPerIp
&& !getIp().equalsIgnoreCase("127.0.0.1")
&& !getIp().equalsIgnoreCase("localhost")) {
m._(player, "max_reg"); m._(player, "max_reg");
allowRegister = false; allowRegister = false;
} }
@ -83,7 +89,8 @@ public class AsyncronousRegister {
if (!allowRegister) return; if (!allowRegister) return;
if (!email.isEmpty() && email != "") { if (!email.isEmpty() && email != "") {
if (Settings.getmaxRegPerEmail > 0) { if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) { if (!plugin.authmePermissible(player, "authme.allow2accounts")
&& database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg"); m._(player, "max_reg");
return; return;
} }
@ -96,15 +103,21 @@ public class AsyncronousRegister {
protected void emailRegister() { protected void emailRegister() {
if (Settings.getmaxRegPerEmail > 0) { if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) { if (!plugin.authmePermissible(player, "authme.allow2accounts")
&& database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
m._(player, "max_reg"); m._(player, "max_reg");
return; return;
} }
} }
PlayerAuth auth = null; PlayerAuth auth = null;
try { try {
final String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); final String hashnew = PasswordSecurity.getHash(
auth = new PlayerAuth(name, hashnew, getIp(), new Date().getTime(), (int) player.getLocation().getX() , (int) player.getLocation().getY(), (int) player.getLocation().getZ(), player.getLocation().getWorld().getName(), email, realName); Settings.getPasswordHash, password, name);
auth = new PlayerAuth(name, hashnew, getIp(), new Date().getTime(),
(int) player.getLocation().getX(), (int) player
.getLocation().getY(), (int) player.getLocation()
.getZ(), player.getLocation().getWorld().getName(),
email, realName);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
m._(player, "error"); m._(player, "error");
@ -117,13 +130,16 @@ public class AsyncronousRegister {
database.updateEmail(auth); database.updateEmail(auth);
database.updateSession(auth); database.updateSession(auth);
plugin.mail.main(auth, password); plugin.mail.main(auth, password);
ProcessSyncronousEmailRegister syncronous = new ProcessSyncronousEmailRegister(player, plugin); ProcessSyncronousEmailRegister syncronous = new ProcessSyncronousEmailRegister(
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous); player, plugin);
plugin.getServer().getScheduler()
.scheduleSyncDelayedTask(plugin, syncronous);
return; return;
} }
protected void passwordRegister() { protected void passwordRegister() {
if(password.length() < Settings.getPasswordMinLen || password.length() > Settings.passwordMaxLength) { if (password.length() < Settings.getPasswordMinLen
|| password.length() > Settings.passwordMaxLength) {
m._(player, "pass_len"); m._(player, "pass_len");
return; return;
} }
@ -136,17 +152,21 @@ public class AsyncronousRegister {
PlayerAuth auth = null; PlayerAuth auth = null;
String hash = ""; String hash = "";
try { try {
hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); hash = PasswordSecurity.getHash(Settings.getPasswordHash, password,
name);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage()); ConsoleLogger.showError(e.getMessage());
m._(player, "error"); m._(player, "error");
return; return;
} }
if (Settings.getMySQLColumnSalt.isEmpty() && !PasswordSecurity.userSalt.containsKey(name)) if (Settings.getMySQLColumnSalt.isEmpty()
{ && !PasswordSecurity.userSalt.containsKey(name)) {
auth = new PlayerAuth(name, hash, getIp(), new Date().getTime(), "your@email.com", player.getName()); auth = new PlayerAuth(name, hash, getIp(), new Date().getTime(),
"your@email.com", player.getName());
} else { } else {
auth = new PlayerAuth(name, hash, PasswordSecurity.userSalt.get(name), getIp(), new Date().getTime(), player.getName()); auth = new PlayerAuth(name, hash,
PasswordSecurity.userSalt.get(name), getIp(),
new Date().getTime(), player.getName());
} }
if (!database.saveAuth(auth)) { if (!database.saveAuth(auth)) {
m._(player, "error"); m._(player, "error");
@ -157,8 +177,10 @@ public class AsyncronousRegister {
database.setLogged(name); database.setLogged(name);
} }
plugin.otherAccounts.addPlayer(player.getUniqueId()); plugin.otherAccounts.addPlayer(player.getUniqueId());
ProcessSyncronousPasswordRegister syncronous = new ProcessSyncronousPasswordRegister(player, plugin); ProcessSyncronousPasswordRegister syncronous = new ProcessSyncronousPasswordRegister(
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous); player, plugin);
plugin.getServer().getScheduler()
.scheduleSyncDelayedTask(plugin, syncronous);
return; return;
} }
} }

View File

@ -24,11 +24,13 @@ public class ProcessSyncronousEmailRegister implements Runnable {
protected String name; protected String name;
private AuthMe plugin; private AuthMe plugin;
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
public ProcessSyncronousEmailRegister(Player player, AuthMe plugin) { public ProcessSyncronousEmailRegister(Player player, AuthMe plugin) {
this.player = player; this.player = player;
this.name = player.getName().toLowerCase(); this.name = player.getName().toLowerCase();
this.plugin = plugin; this.plugin = plugin;
} }
@Override @Override
public void run() { public void run() {
if (!Settings.getRegisteredGroup.isEmpty()) { if (!Settings.getRegisteredGroup.isEmpty()) {
@ -38,37 +40,48 @@ public class ProcessSyncronousEmailRegister implements Runnable {
int time = Settings.getRegistrationTimeout * 20; int time = Settings.getRegistrationTimeout * 20;
int msgInterval = Settings.getWarnMessageInterval; int msgInterval = Settings.getWarnMessageInterval;
if (time != 0) { if (time != 0) {
Bukkit.getScheduler().cancelTask(LimboCache.getInstance().getLimboPlayer(name).getTimeoutTaskId()); Bukkit.getScheduler().cancelTask(
int id = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), time); LimboCache.getInstance().getLimboPlayer(name)
.getTimeoutTaskId());
int id = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new TimeoutTask(plugin, name), time);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
} }
Bukkit.getScheduler().cancelTask(LimboCache.getInstance().getLimboPlayer(name).getMessageTaskId()); Bukkit.getScheduler().cancelTask(
int nwMsg = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("login_msg"), msgInterval)); LimboCache.getInstance().getLimboPlayer(name)
.getMessageTaskId());
int nwMsg = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new MessageTask(plugin, name, m._("login_msg"), msgInterval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(nwMsg); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(nwMsg);
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location loca = plugin.getSpawnLocation(player); Location loca = plugin.getSpawnLocation(player);
RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(player, loca); RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(player,
loca);
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo())
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); .isLoaded()) {
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo())
.load();
} }
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }
} }
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { if (player.getGameMode() != GameMode.CREATIVE
&& !Settings.isMovementAllowed) {
player.setAllowFlight(false); player.setAllowFlight(false);
player.setFlying(false); player.setFlying(false);
} }
if (Settings.applyBlindEffect) if (Settings.applyBlindEffect) player
player.removePotionEffect(PotionEffectType.BLINDNESS); .removePotionEffect(PotionEffectType.BLINDNESS);
player.saveData(); player.saveData();
if (!Settings.noConsoleSpam) if (!Settings.noConsoleSpam) ConsoleLogger.info(player.getName()
ConsoleLogger.info(player.getName() + " registered "+plugin.getIP(player)); + " registered " + plugin.getIP(player));
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " has registered by email!")); plugin.notifications.showNotification(new Notification("[AuthMe] "
+ player.getName() + " has registered by email!"));
} }
} }

View File

@ -28,6 +28,7 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
protected String name; protected String name;
private AuthMe plugin; private AuthMe plugin;
private Messages m = Messages.getInstance(); private Messages m = Messages.getInstance();
public ProcessSyncronousPasswordRegister(Player player, AuthMe plugin) { public ProcessSyncronousPasswordRegister(Player player, AuthMe plugin) {
this.player = player; this.player = player;
this.name = player.getName().toLowerCase(); this.name = player.getName().toLowerCase();
@ -38,38 +39,43 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
for (String command : Settings.forceCommands) { for (String command : Settings.forceCommands) {
try { try {
player.performCommand(command.replace("%p", player.getName())); player.performCommand(command.replace("%p", player.getName()));
} catch (Exception e) {} } catch (Exception e) {
}
} }
} }
protected void forceLogin(Player player) { protected void forceLogin(Player player) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawnLoc = plugin.getSpawnLocation(player); Location spawnLoc = plugin.getSpawnLocation(player);
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, spawnLoc); AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player,
spawnLoc);
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo())
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); .isLoaded()) {
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo())
.load();
} }
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }
} }
if (LimboCache.getInstance().hasLimboPlayer(name)) if (LimboCache.getInstance().hasLimboPlayer(name)) LimboCache
LimboCache.getInstance().deleteLimboPlayer(name); .getInstance().deleteLimboPlayer(name);
LimboCache.getInstance().addLimboPlayer(player); LimboCache.getInstance().addLimboPlayer(player);
int delay = Settings.getRegistrationTimeout * 20; int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval; int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = plugin.getServer().getScheduler(); BukkitScheduler sched = plugin.getServer().getScheduler();
if (delay != 0) { if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay); int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(
plugin, name), delay);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
} }
int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask(plugin, name, m._("login_msg"), interval)); int msgT = sched.scheduleSyncDelayedTask(plugin, new MessageTask(
plugin, name, m._("login_msg"), interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
try { try {
plugin.pllog.removePlayer(name); plugin.pllog.removePlayer(name);
if (player.isInsideVehicle()) if (player.isInsideVehicle()) player.getVehicle().eject();
player.getVehicle().eject();
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
} }
} }
@ -81,17 +87,22 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
player.setGameMode(limbo.getGameMode()); player.setGameMode(limbo.getGameMode());
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location loca = plugin.getSpawnLocation(player); Location loca = plugin.getSpawnLocation(player);
RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(player, loca); RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(
player, loca);
plugin.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo())
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); .isLoaded()) {
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo())
.load();
} }
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }
} }
plugin.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId()); plugin.getServer().getScheduler()
plugin.getServer().getScheduler().cancelTask(limbo.getMessageTaskId()); .cancelTask(limbo.getTimeoutTaskId());
plugin.getServer().getScheduler()
.cancelTask(limbo.getMessageTaskId());
LimboCache.getInstance().deleteLimboPlayer(name); LimboCache.getInstance().deleteLimboPlayer(name);
} }
@ -99,22 +110,24 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED); Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED);
} }
m._(player, "registered"); m._(player, "registered");
if (!Settings.getmailAccount.isEmpty()) if (!Settings.getmailAccount.isEmpty()) m._(player, "add_email");
m._(player, "add_email"); if (player.getGameMode() != GameMode.CREATIVE
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { && !Settings.isMovementAllowed) {
player.setAllowFlight(false); player.setAllowFlight(false);
player.setFlying(false); player.setFlying(false);
} }
if (Settings.applyBlindEffect) if (Settings.applyBlindEffect) player
player.removePotionEffect(PotionEffectType.BLINDNESS); .removePotionEffect(PotionEffectType.BLINDNESS);
// The Loginevent now fires (as intended) after everything is processed // The Loginevent now fires (as intended) after everything is processed
Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true)); Bukkit.getServer().getPluginManager()
.callEvent(new LoginEvent(player, true));
player.saveData(); player.saveData();
if (!Settings.noConsoleSpam) if (!Settings.noConsoleSpam) ConsoleLogger.info(player.getName()
ConsoleLogger.info(player.getName() + " registered "+plugin.getIP(player)); + " registered " + plugin.getIP(player));
if (plugin.notifications != null) { if (plugin.notifications != null) {
plugin.notifications.showNotification(new Notification("[AuthMe] " + player.getName() + " has registered!")); plugin.notifications.showNotification(new Notification("[AuthMe] "
+ player.getName() + " has registered!"));
} }
// Kick Player after Registration is enabled, kick the player // Kick Player after Registration is enabled, kick the player
@ -130,10 +143,10 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
} }
// Register is finish and player is logged, display welcome message // Register is finish and player is logged, display welcome message
if(Settings.useWelcomeMessage) if (Settings.useWelcomeMessage) if (Settings.broadcastWelcomeMessage) {
if(Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) { for (String s : Settings.welcomeMsg) {
Bukkit.getServer().broadcastMessage(plugin.replaceAllInfos(s, player)); Bukkit.getServer().broadcastMessage(
plugin.replaceAllInfos(s, player));
} }
} else { } else {
for (String s : Settings.welcomeMsg) { for (String s : Settings.welcomeMsg) {

View File

@ -15,7 +15,6 @@ import fr.xephi.authme.security.crypts.BCRYPT;
import fr.xephi.authme.security.crypts.EncryptionMethod; import fr.xephi.authme.security.crypts.EncryptionMethod;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
public class PasswordSecurity { public class PasswordSecurity {
private static SecureRandom rnd = new SecureRandom(); private static SecureRandom rnd = new SecureRandom();
@ -27,19 +26,23 @@ public class PasswordSecurity {
MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset(); sha1.reset();
byte[] digest = sha1.digest(msg); byte[] digest = sha1.digest(msg);
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)).substring(0, length); return String.format("%0" + (digest.length << 1) + "x",
new BigInteger(1, digest)).substring(0, length);
} }
public static String getHash(HashAlgorithm alg, String password, String playerName) throws NoSuchAlgorithmException { public static String getHash(HashAlgorithm alg, String password,
String playerName) throws NoSuchAlgorithmException {
EncryptionMethod method; EncryptionMethod method;
try { try {
if (alg != HashAlgorithm.CUSTOM) if (alg != HashAlgorithm.CUSTOM) method = (EncryptionMethod) alg
method = (EncryptionMethod) alg.getclass().newInstance(); .getclass().newInstance();
else method = null; else method = null;
} catch (InstantiationException e) { } catch (InstantiationException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm"); throw new NoSuchAlgorithmException(
"Problem with this hash algorithm");
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm"); throw new NoSuchAlgorithmException(
"Problem with this hash algorithm");
} }
String salt = ""; String salt = "";
switch (alg) { switch (alg) {
@ -109,62 +112,70 @@ public class PasswordSecurity {
default: default:
throw new NoSuchAlgorithmException("Unknown hash algorithm"); throw new NoSuchAlgorithmException("Unknown hash algorithm");
} }
PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName); PasswordEncryptionEvent event = new PasswordEncryptionEvent(method,
playerName);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
method = event.getMethod(); method = event.getMethod();
if (method == null) if (method == null) throw new NoSuchAlgorithmException(
throw new NoSuchAlgorithmException("Unknown hash algorithm"); "Unknown hash algorithm");
return method.getHash(password, salt, playerName); return method.getHash(password, salt, playerName);
} }
public static boolean comparePasswordWithHash(String password, String hash, String playerName) throws NoSuchAlgorithmException { public static boolean comparePasswordWithHash(String password, String hash,
String playerName) throws NoSuchAlgorithmException {
HashAlgorithm algo = Settings.getPasswordHash; HashAlgorithm algo = Settings.getPasswordHash;
EncryptionMethod method; EncryptionMethod method;
try { try {
if (algo != HashAlgorithm.CUSTOM) if (algo != HashAlgorithm.CUSTOM) method = (EncryptionMethod) algo
method = (EncryptionMethod) algo.getclass().newInstance(); .getclass().newInstance();
else method = null; else method = null;
} catch (InstantiationException e) { } catch (InstantiationException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm"); throw new NoSuchAlgorithmException(
"Problem with this hash algorithm");
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm"); throw new NoSuchAlgorithmException(
"Problem with this hash algorithm");
} }
PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName); PasswordEncryptionEvent event = new PasswordEncryptionEvent(method,
playerName);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
method = event.getMethod(); method = event.getMethod();
if (method == null) if (method == null) throw new NoSuchAlgorithmException(
throw new NoSuchAlgorithmException("Unknown hash algorithm"); "Unknown hash algorithm");
try { try {
if (method.comparePassword(hash, password, playerName)) if (method.comparePassword(hash, password, playerName)) return true;
return true;
} catch (Exception e) { } catch (Exception e) {
} }
if (Settings.supportOldPassword) { if (Settings.supportOldPassword) {
try { try {
if (compareWithAllEncryptionMethod(password, hash, playerName)) if (compareWithAllEncryptionMethod(password, hash, playerName)) return true;
return true; } catch (Exception e) {
} catch (Exception e) {} }
} }
return false; return false;
} }
private static boolean compareWithAllEncryptionMethod(String password, String hash, String playerName) throws NoSuchAlgorithmException { private static boolean compareWithAllEncryptionMethod(String password,
String hash, String playerName) throws NoSuchAlgorithmException {
for (HashAlgorithm algo : HashAlgorithm.values()) { for (HashAlgorithm algo : HashAlgorithm.values()) {
if (algo != HashAlgorithm.CUSTOM) if (algo != HashAlgorithm.CUSTOM) try {
try { EncryptionMethod method = (EncryptionMethod) algo.getclass()
EncryptionMethod method = (EncryptionMethod) algo.getclass().newInstance(); .newInstance();
if (method.comparePassword(hash, password, playerName)) { if (method.comparePassword(hash, password, playerName)) {
PlayerAuth nAuth = AuthMe.getInstance().database.getAuth(playerName); PlayerAuth nAuth = AuthMe.getInstance().database
.getAuth(playerName);
if (nAuth != null) { if (nAuth != null) {
nAuth.setHash(getHash(Settings.getPasswordHash, password, playerName)); nAuth.setHash(getHash(Settings.getPasswordHash,
password, playerName));
nAuth.setSalt(userSalt.get(playerName)); nAuth.setSalt(userSalt.get(playerName));
AuthMe.getInstance().database.updatePassword(nAuth); AuthMe.getInstance().database.updatePassword(nAuth);
AuthMe.getInstance().database.updateSalt(nAuth); AuthMe.getInstance().database.updateSalt(nAuth);
} }
return true; return true;
} }
} catch (Exception e) {} } catch (Exception e) {
}
} }
return false; return false;
} }

View File

@ -6,8 +6,7 @@ import java.util.Random;
* *
* @author Xephi59 * @author Xephi59
*/ */
public class RandomString public class RandomString {
{
private static final char[] chars = new char[36]; private static final char[] chars = new char[36];
@ -22,15 +21,13 @@ public class RandomString
private final char[] buf; private final char[] buf;
public RandomString(int length) public RandomString(int length) {
{ if (length < 1) throw new IllegalArgumentException("length < 1: "
if (length < 1) + length);
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length]; buf = new char[length];
} }
public String nextString() public String nextString() {
{
for (int idx = 0; idx < buf.length; ++idx) for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = chars[random.nextInt(chars.length)]; buf[idx] = chars[random.nextInt(chars.length)];
return new String(buf); return new String(buf);

View File

@ -19,25 +19,24 @@ import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom; import java.security.SecureRandom;
/** /**
* BCrypt implements OpenBSD-style Blowfish password hashing using * BCrypt implements OpenBSD-style Blowfish password hashing using the scheme
* the scheme described in "A Future-Adaptable Password Scheme" by * described in "A Future-Adaptable Password Scheme" by Niels Provos and David
* Niels Provos and David Mazieres. * Mazieres.
* <p> * <p>
* This password hashing system tries to thwart off-line password * This password hashing system tries to thwart off-line password cracking using
* cracking using a computationally-intensive hashing algorithm, * a computationally-intensive hashing algorithm, based on Bruce Schneier's
* based on Bruce Schneier's Blowfish cipher. The work factor of * Blowfish cipher. The work factor of the algorithm is parameterised, so it can
* the algorithm is parameterised, so it can be increased as * be increased as computers get faster.
* computers get faster.
* <p> * <p>
* Usage is really simple. To hash a password for the first time, * Usage is really simple. To hash a password for the first time, call the
* call the hashpw method with a random salt, like this: * hashpw method with a random salt, like this:
* <p> * <p>
* <code> * <code>
* String pw_hash = BCrypt.hashpw(plain_password, BCrypt.gensalt()); <br /> * String pw_hash = BCrypt.hashpw(plain_password, BCrypt.gensalt()); <br />
* </code> * </code>
* <p> * <p>
* To check whether a plaintext password matches one that has been * To check whether a plaintext password matches one that has been hashed
* hashed previously, use the checkpw method: * previously, use the checkpw method:
* <p> * <p>
* <code> * <code>
* if (BCrypt.checkpw(candidate_password, stored_hash))<br /> * if (BCrypt.checkpw(candidate_password, stored_hash))<br />
@ -46,17 +45,17 @@ import java.security.SecureRandom;
* &nbsp;&nbsp;&nbsp;&nbsp;System.out.println("It does not match");<br /> * &nbsp;&nbsp;&nbsp;&nbsp;System.out.println("It does not match");<br />
* </code> * </code>
* <p> * <p>
* The gensalt() method takes an optional parameter (log_rounds) * The gensalt() method takes an optional parameter (log_rounds) that determines
* that determines the computational complexity of the hashing: * the computational complexity of the hashing:
* <p> * <p>
* <code> * <code>
* String strong_salt = BCrypt.gensalt(10)<br /> * String strong_salt = BCrypt.gensalt(10)<br />
* String stronger_salt = BCrypt.gensalt(12)<br /> * String stronger_salt = BCrypt.gensalt(12)<br />
* </code> * </code>
* <p> * <p>
* The amount of work increases exponentially (2**log_rounds), so * The amount of work increases exponentially (2**log_rounds), so each increment
* each increment is twice as much work. The default log_rounds is * is twice as much work. The default log_rounds is 10, and the valid range is 4
* 10, and the valid range is 4 to 31. * to 31.
* *
* @author Damien Miller * @author Damien Miller
* @version 0.2 * @version 0.2
@ -70,318 +69,255 @@ public class BCRYPT implements EncryptionMethod {
private static final int BLOWFISH_NUM_ROUNDS = 16; private static final int BLOWFISH_NUM_ROUNDS = 16;
// Initial contents of key schedule // Initial contents of key schedule
private static final int P_orig[] = { private static final int P_orig[] = { 0x243f6a88, 0x85a308d3, 0x13198a2e,
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7,
0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b };
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, private static final int S_orig[] = { 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db,
0x9216d5d9, 0x8979fb1b 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
}; 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8,
private static final int S_orig[] = { 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af,
0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482,
0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72,
0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857,
0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d,
0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01,
0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb,
0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a,
0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d,
0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, 0x4b7a70e9, 0xb5b32944,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6,
0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146,
0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17,
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c,
0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6,
0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78,
0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775,
0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5,
0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829,
0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263,
0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6,
0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a,
0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1,
0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484,
0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68,
0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7,
0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c,
0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9,
0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a,
0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c,
0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1,
0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e,
0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510,
0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7,
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8,
0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0,
0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b,
0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63,
0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578,
0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be,
0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3,
0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e,
0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671,
0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a,
0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120,
0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60,
0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x3ac372e6 };
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
};
// bcrypt IV: "OrpheanBeholderScryDoubt" // bcrypt IV: "OrpheanBeholderScryDoubt"
static private final int bf_crypt_ciphertext[] = { static private final int bf_crypt_ciphertext[] = { 0x4f727068, 0x65616e42,
0x4f727068, 0x65616e42, 0x65686f6c, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274 };
0x64657253, 0x63727944, 0x6f756274
};
// Table for Base64 encoding // Table for Base64 encoding
static private final char base64_code[] = { static private final char base64_code[] = { '.', '/', 'A', 'B', 'C', 'D',
'.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '4', '5', '6', '7', '8', '9' };
'6', '7', '8', '9'
};
// Table for Base64 decoding // Table for Base64 decoding
static private final byte index_64[] = { static private final byte index_64[] = { -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
-1, -1, -1, -1, -1, -1, 0, 1, 54, 55, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1,
56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
-1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1 };
7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
-1, -1, -1, -1, -1, -1, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 53, -1, -1, -1, -1, -1
};
// Expanded Blowfish key // Expanded Blowfish key
private int P[]; private int P[];
private int S[]; private int S[];
/** /**
* Encode a byte array using bcrypt's slightly-modified base64 * Encode a byte array using bcrypt's slightly-modified base64 encoding
* encoding scheme. Note that this is *not* compatible with * scheme. Note that this is *not* compatible with the standard MIME-base64
* the standard MIME-base64 encoding. * encoding.
* *
* @param d the byte array to encode * @param d
* @param len the number of bytes to encode * the byte array to encode
* @param len
* the number of bytes to encode
* @return base64-encoded string * @return base64-encoded string
* @exception IllegalArgumentException if the length is invalid * @exception IllegalArgumentException
* if the length is invalid
*/ */
private static String encode_base64(byte d[], int len) private static String encode_base64(byte d[], int len)
throws IllegalArgumentException { throws IllegalArgumentException {
@ -389,8 +325,8 @@ public class BCRYPT implements EncryptionMethod {
StringBuffer rs = new StringBuffer(); StringBuffer rs = new StringBuffer();
int c1, c2; int c1, c2;
if (len <= 0 || len > d.length) if (len <= 0 || len > d.length) throw new IllegalArgumentException(
throw new IllegalArgumentException ("Invalid len"); "Invalid len");
while (off < len) { while (off < len) {
c1 = d[off++] & 0xff; c1 = d[off++] & 0xff;
@ -419,23 +355,28 @@ public class BCRYPT implements EncryptionMethod {
/** /**
* Look up the 3 bits base64-encoded by the specified character, * Look up the 3 bits base64-encoded by the specified character,
* range-checking againt conversion table * range-checking againt conversion table
* @param x the base64-encoded value *
* @param x
* the base64-encoded value
* @return the decoded value of x * @return the decoded value of x
*/ */
private static byte char64(char x) { private static byte char64(char x) {
if ((int)x < 0 || (int)x > index_64.length) if ((int) x < 0 || (int) x > index_64.length) return -1;
return -1;
return index_64[(int) x]; return index_64[(int) x];
} }
/** /**
* Decode a string encoded using bcrypt's base64 scheme to a * Decode a string encoded using bcrypt's base64 scheme to a byte array.
* byte array. Note that this is *not* compatible with * Note that this is *not* compatible with the standard MIME-base64
* the standard MIME-base64 encoding. * encoding.
* @param s the string to decode *
* @param maxolen the maximum number of bytes to decode * @param s
* the string to decode
* @param maxolen
* the maximum number of bytes to decode
* @return an array containing the decoded bytes * @return an array containing the decoded bytes
* @throws IllegalArgumentException if maxolen is invalid * @throws IllegalArgumentException
* if maxolen is invalid
*/ */
private static byte[] decode_base64(String s, int maxolen) private static byte[] decode_base64(String s, int maxolen)
throws IllegalArgumentException { throws IllegalArgumentException {
@ -444,27 +385,22 @@ public class BCRYPT implements EncryptionMethod {
byte ret[]; byte ret[];
byte c1, c2, c3, c4, o; byte c1, c2, c3, c4, o;
if (maxolen <= 0) if (maxolen <= 0) throw new IllegalArgumentException("Invalid maxolen");
throw new IllegalArgumentException ("Invalid maxolen");
while (off < slen - 1 && olen < maxolen) { while (off < slen - 1 && olen < maxolen) {
c1 = char64(s.charAt(off++)); c1 = char64(s.charAt(off++));
c2 = char64(s.charAt(off++)); c2 = char64(s.charAt(off++));
if (c1 == -1 || c2 == -1) if (c1 == -1 || c2 == -1) break;
break;
o = (byte) (c1 << 2); o = (byte) (c1 << 2);
o |= (c2 & 0x30) >> 4; o |= (c2 & 0x30) >> 4;
rs.append((char) o); rs.append((char) o);
if (++olen >= maxolen || off >= slen) if (++olen >= maxolen || off >= slen) break;
break;
c3 = char64(s.charAt(off++)); c3 = char64(s.charAt(off++));
if (c3 == -1) if (c3 == -1) break;
break;
o = (byte) ((c2 & 0x0f) << 4); o = (byte) ((c2 & 0x0f) << 4);
o |= (c3 & 0x3c) >> 2; o |= (c3 & 0x3c) >> 2;
rs.append((char) o); rs.append((char) o);
if (++olen >= maxolen || off >= slen) if (++olen >= maxolen || off >= slen) break;
break;
c4 = char64(s.charAt(off++)); c4 = char64(s.charAt(off++));
o = (byte) ((c3 & 0x03) << 6); o = (byte) ((c3 & 0x03) << 6);
o |= c4; o |= c4;
@ -479,10 +415,12 @@ public class BCRYPT implements EncryptionMethod {
} }
/** /**
* Blowfish encipher a single 64-bit block encoded as * Blowfish encipher a single 64-bit block encoded as two 32-bit halves
* two 32-bit halves *
* @param lr an array containing the two 32-bit half blocks * @param lr
* @param off the position in the array of the blocks * an array containing the two 32-bit half blocks
* @param off
* the position in the array of the blocks
*/ */
private final void encipher(int lr[], int off) { private final void encipher(int lr[], int off) {
int i, n, l = lr[off], r = lr[off + 1]; int i, n, l = lr[off], r = lr[off + 1];
@ -509,9 +447,12 @@ public class BCRYPT implements EncryptionMethod {
/** /**
* Cycically extract a word of key material * Cycically extract a word of key material
* @param data the string to extract the data from *
* @param offp a "pointer" (as a one-entry array) to the * @param data
* current offset into data * the string to extract the data from
* @param offp
* a "pointer" (as a one-entry array) to the current offset into
* data
* @return the next word of material from data * @return the next word of material from data
*/ */
private static int streamtoword(byte data[], int offp[]) { private static int streamtoword(byte data[], int offp[]) {
@ -538,7 +479,9 @@ public class BCRYPT implements EncryptionMethod {
/** /**
* Key the Blowfish cipher * Key the Blowfish cipher
* @param key an array containing the key *
* @param key
* an array containing the key
*/ */
private void key(byte key[]) { private void key(byte key[]) {
int i; int i;
@ -563,11 +506,14 @@ public class BCRYPT implements EncryptionMethod {
} }
/** /**
* Perform the "enhanced key schedule" step described by * Perform the "enhanced key schedule" step described by Provos and Mazieres
* Provos and Mazieres in "A Future-Adaptable Password Scheme" * in "A Future-Adaptable Password Scheme"
* http://www.openbsd.org/papers/bcrypt-paper.ps * http://www.openbsd.org/papers/bcrypt-paper.ps
* @param data salt information *
* @param key password information * @param data
* salt information
* @param key
* password information
*/ */
private void ekskey(byte data[], byte key[]) { private void ekskey(byte data[], byte key[]) {
int i; int i;
@ -596,12 +542,15 @@ public class BCRYPT implements EncryptionMethod {
} }
/** /**
* Perform the central password hashing step in the * Perform the central password hashing step in the bcrypt scheme
* bcrypt scheme *
* @param password the password to hash * @param password
* @param salt the binary salt to hash with the password * the password to hash
* @param log_rounds the binary logarithm of the number * @param salt
* of rounds of hashing to apply * the binary salt to hash with the password
* @param log_rounds
* the binary logarithm of the number of rounds of hashing to
* apply
* @return an array containing the binary hashed password * @return an array containing the binary hashed password
*/ */
private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) { private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) {
@ -610,11 +559,11 @@ public class BCRYPT implements EncryptionMethod {
int clen = cdata.length; int clen = cdata.length;
byte ret[]; byte ret[];
if (log_rounds < 4 || log_rounds > 31) if (log_rounds < 4 || log_rounds > 31) throw new IllegalArgumentException(
throw new IllegalArgumentException ("Bad number of rounds"); "Bad number of rounds");
rounds = 1 << log_rounds; rounds = 1 << log_rounds;
if (salt.length != BCRYPT_SALT_LEN) if (salt.length != BCRYPT_SALT_LEN) throw new IllegalArgumentException(
throw new IllegalArgumentException ("Bad salt length"); "Bad salt length");
init_key(); init_key();
ekskey(salt, password); ekskey(salt, password);
@ -640,9 +589,11 @@ public class BCRYPT implements EncryptionMethod {
/** /**
* Hash a password using the OpenBSD bcrypt scheme * Hash a password using the OpenBSD bcrypt scheme
* @param password the password to hash *
* @param salt the salt to hash with (perhaps generated * @param password
* using BCrypt.gensalt) * the password to hash
* @param salt
* the salt to hash with (perhaps generated using BCrypt.gensalt)
* @return the hashed password * @return the hashed password
*/ */
public static String hashpw(String password, String salt) { public static String hashpw(String password, String salt) {
@ -653,25 +604,25 @@ public class BCRYPT implements EncryptionMethod {
int rounds, off = 0; int rounds, off = 0;
StringBuffer rs = new StringBuffer(); StringBuffer rs = new StringBuffer();
if (salt.charAt(0) != '$' || salt.charAt(1) != '2') if (salt.charAt(0) != '$' || salt.charAt(1) != '2') throw new IllegalArgumentException(
throw new IllegalArgumentException ("Invalid salt version"); "Invalid salt version");
if (salt.charAt(2) == '$') if (salt.charAt(2) == '$') off = 3;
off = 3;
else { else {
minor = salt.charAt(2); minor = salt.charAt(2);
if (minor != 'a' || salt.charAt(3) != '$') if (minor != 'a' || salt.charAt(3) != '$') throw new IllegalArgumentException(
throw new IllegalArgumentException ("Invalid salt revision"); "Invalid salt revision");
off = 4; off = 4;
} }
// Extract number of rounds // Extract number of rounds
if (salt.charAt(off + 2) > '$') if (salt.charAt(off + 2) > '$') throw new IllegalArgumentException(
throw new IllegalArgumentException ("Missing salt rounds"); "Missing salt rounds");
rounds = Integer.parseInt(salt.substring(off, off + 2)); rounds = Integer.parseInt(salt.substring(off, off + 2));
real_salt = salt.substring(off + 3, off + 25); real_salt = salt.substring(off + 3, off + 25);
try { try {
passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8"); passwordb = (password + (minor >= 'a' ? "\000" : ""))
.getBytes("UTF-8");
} catch (UnsupportedEncodingException uee) { } catch (UnsupportedEncodingException uee) {
throw new AssertionError("UTF-8 is not supported"); throw new AssertionError("UTF-8 is not supported");
} }
@ -682,25 +633,24 @@ public class BCRYPT implements EncryptionMethod {
hashed = B.crypt_raw(passwordb, saltb, rounds); hashed = B.crypt_raw(passwordb, saltb, rounds);
rs.append("$2"); rs.append("$2");
if (minor >= 'a') if (minor >= 'a') rs.append(minor);
rs.append(minor);
rs.append("$"); rs.append("$");
if (rounds < 10) if (rounds < 10) rs.append("0");
rs.append("0");
rs.append(Integer.toString(rounds)); rs.append(Integer.toString(rounds));
rs.append("$"); rs.append("$");
rs.append(encode_base64(saltb, saltb.length)); rs.append(encode_base64(saltb, saltb.length));
rs.append(encode_base64(hashed, rs.append(encode_base64(hashed, bf_crypt_ciphertext.length * 4 - 1));
bf_crypt_ciphertext.length * 4 - 1));
return rs.toString(); return rs.toString();
} }
/** /**
* Generate a salt for use with the BCrypt.hashpw() method * Generate a salt for use with the BCrypt.hashpw() method
* @param log_rounds the log2 of the number of rounds of *
* hashing to apply - the work factor therefore increases as * @param log_rounds
* 2**log_rounds. * the log2 of the number of rounds of hashing to apply - the
* @param random an instance of SecureRandom to use * work factor therefore increases as 2**log_rounds.
* @param random
* an instance of SecureRandom to use
* @return an encoded salt value * @return an encoded salt value
*/ */
public static String gensalt(int log_rounds, SecureRandom random) { public static String gensalt(int log_rounds, SecureRandom random) {
@ -710,8 +660,7 @@ public class BCRYPT implements EncryptionMethod {
random.nextBytes(rnd); random.nextBytes(rnd);
rs.append("$2a$"); rs.append("$2a$");
if (log_rounds < 10) if (log_rounds < 10) rs.append("0");
rs.append("0");
rs.append(Integer.toString(log_rounds)); rs.append(Integer.toString(log_rounds));
rs.append("$"); rs.append("$");
rs.append(encode_base64(rnd, rnd.length)); rs.append(encode_base64(rnd, rnd.length));
@ -720,9 +669,10 @@ public class BCRYPT implements EncryptionMethod {
/** /**
* Generate a salt for use with the BCrypt.hashpw() method * Generate a salt for use with the BCrypt.hashpw() method
* @param log_rounds the log2 of the number of rounds of *
* hashing to apply - the work factor therefore increases as * @param log_rounds
* 2**log_rounds. * the log2 of the number of rounds of hashing to apply - the
* work factor therefore increases as 2**log_rounds.
* @return an encoded salt value * @return an encoded salt value
*/ */
public static String gensalt(int log_rounds) { public static String gensalt(int log_rounds) {
@ -730,9 +680,9 @@ public class BCRYPT implements EncryptionMethod {
} }
/** /**
* Generate a salt for use with the BCrypt.hashpw() method, * Generate a salt for use with the BCrypt.hashpw() method, selecting a
* selecting a reasonable default for the number of hashing * reasonable default for the number of hashing rounds to apply
* rounds to apply *
* @return an encoded salt value * @return an encoded salt value
*/ */
public static String gensalt() { public static String gensalt() {
@ -740,10 +690,12 @@ public class BCRYPT implements EncryptionMethod {
} }
/** /**
* Check that a plaintext password matches a previously hashed * Check that a plaintext password matches a previously hashed one
* one *
* @param plaintext the plaintext password to verify * @param plaintext
* @param hashed the previously-hashed password * the plaintext password to verify
* @param hashed
* the previously-hashed password
* @return true if the passwords match, false otherwise * @return true if the passwords match, false otherwise
*/ */
public static boolean checkpw(String plaintext, String hashed) { public static boolean checkpw(String plaintext, String hashed) {
@ -751,12 +703,15 @@ public class BCRYPT implements EncryptionMethod {
} }
/** /**
* Check that a text password matches a previously hashed * Check that a text password matches a previously hashed one with the
* one with the specified number of rounds using recursion * specified number of rounds using recursion
* *
* @param text plaintext or hashed text * @param text
* @param hashed the previously-hashed password * plaintext or hashed text
* @param rounds number of rounds to hash the password * @param hashed
* the previously-hashed password
* @param rounds
* number of rounds to hash the password
* @return * @return
*/ */
public static boolean checkpw(String text, String hashed, int rounds) { public static boolean checkpw(String text, String hashed, int rounds) {

View File

@ -7,12 +7,14 @@ import java.security.NoSuchAlgorithmException;
public class CRAZYCRYPT1 implements EncryptionMethod { public class CRAZYCRYPT1 implements EncryptionMethod {
protected final Charset charset = Charset.forName("UTF-8"); protected final Charset charset = Charset.forName("UTF-8");
private static final char[] CRYPTCHARS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private static final char[] CRYPTCHARS = new char[] { '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
@Override @Override
public String getHash(String password, String salt, String name) public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException { throws NoSuchAlgorithmException {
final String text = "ÜÄaeut//&/=I " + password + "7421€547" + name + "__+IÄIH§%NK " + password; final String text = "ÜÄaeut//&/=I " + password + "7421€547" + name
+ "__+IÄIH§%NK " + password;
try { try {
final MessageDigest md = MessageDigest.getInstance("SHA-512"); final MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(text.getBytes(charset), 0, text.length()); md.update(text.getBytes(charset), 0, text.length());

View File

@ -5,14 +5,14 @@ import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.security.pbkdf2.PBKDF2Engine; import fr.xephi.authme.security.pbkdf2.PBKDF2Engine;
import fr.xephi.authme.security.pbkdf2.PBKDF2Parameters; import fr.xephi.authme.security.pbkdf2.PBKDF2Parameters;
public class CryptPBKDF2 implements EncryptionMethod { public class CryptPBKDF2 implements EncryptionMethod {
@Override @Override
public String getHash(String password, String salt, String name) public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException { throws NoSuchAlgorithmException {
String result = "pbkdf2_sha256$10000$" + salt + "$"; String result = "pbkdf2_sha256$10000$" + salt + "$";
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 10000); PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII",
salt.getBytes(), 10000);
PBKDF2Engine engine = new PBKDF2Engine(params); PBKDF2Engine engine = new PBKDF2Engine(params);
return result + engine.deriveKey(password, 64).toString(); return result + engine.deriveKey(password, 64).toString();
@ -24,7 +24,8 @@ public class CryptPBKDF2 implements EncryptionMethod {
String[] line = hash.split("\\$"); String[] line = hash.split("\\$");
String salt = line[2]; String salt = line[2];
String derivedKey = line[3]; String derivedKey = line[3];
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 10000, derivedKey.getBytes()); PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII",
salt.getBytes(), 10000, derivedKey.getBytes());
PBKDF2Engine engine = new PBKDF2Engine(params); PBKDF2Engine engine = new PBKDF2Engine(params);
return engine.verifyKey(password); return engine.verifyKey(password);
} }

View File

@ -18,12 +18,14 @@ public class DOUBLEMD5 implements EncryptionMethod {
return hash.equals(getHash(password, "", "")); return hash.equals(getHash(password, "", ""));
} }
private static String getMD5(String message) throws NoSuchAlgorithmException { private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -3,20 +3,29 @@ package fr.xephi.authme.security.crypts;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
/** /**
* <p>Public interface for Custom Password encryption method</p> * <p>
* <p>The getHash function is called when we need to crypt the password (/register usually)</p> * Public interface for Custom Password encryption method
* <p>The comparePassword is called when we need to match password (/login usually)</p> * </p>
* <p>
* The getHash function is called when we need to crypt the password (/register
* usually)
* </p>
* <p>
* The comparePassword is called when we need to match password (/login usually)
* </p>
*/ */
public interface EncryptionMethod { public interface EncryptionMethod {
/** /**
* @param password * @param password
* @param salt (can be an other data like playerName;salt , playerName, etc... * @param salt
* for customs methods) * (can be an other data like playerName;salt , playerName,
* etc... for customs methods)
* @return Hashing password * @return Hashing password
* @throws NoSuchAlgorithmException * @throws NoSuchAlgorithmException
*/ */
String getHash(String password, String salt, String name) throws NoSuchAlgorithmException; String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException;
/** /**
* @param hash * @param hash
@ -25,6 +34,7 @@ public interface EncryptionMethod {
* @return true if password match, false else * @return true if password match, false else
* @throws NoSuchAlgorithmException * @throws NoSuchAlgorithmException
*/ */
boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException; boolean comparePassword(String hash, String password, String playerName)
throws NoSuchAlgorithmException;
} }

View File

@ -6,7 +6,6 @@ import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
public class IPB3 implements EncryptionMethod { public class IPB3 implements EncryptionMethod {
@Override @Override
@ -18,15 +17,18 @@ public class IPB3 implements EncryptionMethod {
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); String salt = AuthMe.getInstance().database.getAuth(playerName)
.getSalt();
return hash.equals(getHash(password, salt, playerName)); return hash.equals(getHash(password, salt, playerName));
} }
private static String getMD5(String message) throws NoSuchAlgorithmException { private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -19,11 +19,13 @@ public class JOOMLA implements EncryptionMethod {
return hash.equals(getMD5(password + salt) + ":" + salt); return hash.equals(getMD5(password + salt) + ":" + salt);
} }
private static String getMD5(String message) throws NoSuchAlgorithmException { private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -7,20 +7,24 @@ import java.security.NoSuchAlgorithmException;
public class MD5 implements EncryptionMethod { public class MD5 implements EncryptionMethod {
@Override @Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getMD5(password); return getMD5(password);
} }
@Override @Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", "")); return hash.equals(getHash(password, "", ""));
} }
private static String getMD5(String message) throws NoSuchAlgorithmException { private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -19,12 +19,14 @@ public class MD5VB implements EncryptionMethod {
return hash.equals(getHash(password, line[2], "")); return hash.equals(getHash(password, line[2], ""));
} }
private static String getMD5(String message) throws NoSuchAlgorithmException { private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -6,7 +6,6 @@ import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
public class MYBB implements EncryptionMethod { public class MYBB implements EncryptionMethod {
@Override @Override
@ -18,15 +17,18 @@ public class MYBB implements EncryptionMethod {
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); String salt = AuthMe.getInstance().database.getAuth(playerName)
.getSalt();
return hash.equals(getHash(password, salt, playerName)); return hash.equals(getHash(password, salt, playerName));
} }
private static String getMD5(String message) throws NoSuchAlgorithmException { private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -1,6 +1,6 @@
/* /*
* To change this template, choose Tools | Templates * To change this template, choose Tools | Templates and open the template in
* and open the template in the editor. * the editor.
*/ */
package fr.xephi.authme.security.crypts; package fr.xephi.authme.security.crypts;
@ -15,8 +15,7 @@ import java.security.NoSuchAlgorithmException;
*/ */
public class PHPBB implements EncryptionMethod { public class PHPBB implements EncryptionMethod {
private static final int PHP_VERSION = 4; private static final int PHP_VERSION = 4;
private String itoa64 = private String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public String phpbb_hash(String password, String salt) { public String phpbb_hash(String password, String salt) {
String random_state = salt; String random_state = salt;
@ -30,10 +29,9 @@ public class PHPBB implements EncryptionMethod {
} }
random = random.substring(0, count); random = random.substring(0, count);
} }
String hash = _hash_crypt_private( String hash = _hash_crypt_private(password,
password, _hash_gensalt_private(random, itoa64)); _hash_gensalt_private(random, itoa64));
if (hash.length() == 34) if (hash.length() == 34) return hash;
return hash;
return md5(password); return md5(password);
} }
@ -42,15 +40,14 @@ public class PHPBB implements EncryptionMethod {
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
private String _hash_gensalt_private( private String _hash_gensalt_private(String input, String itoa64,
String input, String itoa64, int iteration_count_log2) { int iteration_count_log2) {
if (iteration_count_log2 < 4 || iteration_count_log2 > 31) { if (iteration_count_log2 < 4 || iteration_count_log2 > 31) {
iteration_count_log2 = 8; iteration_count_log2 = 8;
} }
String output = "$H$"; String output = "$H$";
output += itoa64.charAt( output += itoa64.charAt(Math.min(iteration_count_log2
Math.min(iteration_count_log2 + + ((PHP_VERSION >= 5) ? 5 : 3), 30));
((PHP_VERSION >= 5) ? 5 : 3), 30));
output += _hash_encode64(input, 6); output += _hash_encode64(input, 6);
return output; return output;
} }
@ -64,31 +61,25 @@ private String _hash_gensalt_private(
do { do {
int value = input.charAt(i++); int value = input.charAt(i++);
output += itoa64.charAt(value & 0x3f); output += itoa64.charAt(value & 0x3f);
if (i < count) if (i < count) value |= input.charAt(i) << 8;
value |= input.charAt(i) << 8;
output += itoa64.charAt((value >> 6) & 0x3f); output += itoa64.charAt((value >> 6) & 0x3f);
if (i++ >= count) if (i++ >= count) break;
break; if (i < count) value |= input.charAt(i) << 16;
if (i < count)
value |= input.charAt(i) << 16;
output += itoa64.charAt((value >> 12) & 0x3f); output += itoa64.charAt((value >> 12) & 0x3f);
if (i++ >= count) if (i++ >= count) break;
break;
output += itoa64.charAt((value >> 18) & 0x3f); output += itoa64.charAt((value >> 18) & 0x3f);
} while (i < count); } while (i < count);
return output; return output;
} }
String _hash_crypt_private(String password, String setting) { String _hash_crypt_private(String password, String setting) {
String output = "*"; String output = "*";
if (!setting.substring(0, 3).equals("$H$")) if (!setting.substring(0, 3).equals("$H$")) return output;
return output;
int count_log2 = itoa64.indexOf(setting.charAt(3)); int count_log2 = itoa64.indexOf(setting.charAt(3));
if (count_log2 < 7 || count_log2 > 30) if (count_log2 < 7 || count_log2 > 30) return output;
return output;
int count = 1 << count_log2; int count = 1 << count_log2;
String salt = setting.substring(4, 12); String salt = setting.substring(4, 12);
if (salt.length() != 8) if (salt.length() != 8) return output;
return output;
String m1 = md5(salt + password); String m1 = md5(salt + password);
String hash = pack(m1); String hash = pack(m1);
do { do {
@ -100,10 +91,9 @@ private String _hash_gensalt_private(
} }
public boolean phpbb_check_hash(String password, String hash) { public boolean phpbb_check_hash(String password, String hash) {
if (hash.length() == 34) if (hash.length() == 34) return _hash_crypt_private(password, hash)
return _hash_crypt_private(password, hash).equals(hash); .equals(hash);
else else return md5(password).equals(hash);
return md5(password).equals(hash);
} }
public static String md5(String data) { public static String md5(String data) {
@ -120,11 +110,9 @@ private String _hash_gensalt_private(
} }
static int hexToInt(char ch) { static int hexToInt(char ch) {
if(ch >= '0' && ch <= '9') if (ch >= '0' && ch <= '9') return ch - '0';
return ch - '0';
ch = Character.toUpperCase(ch); ch = Character.toUpperCase(ch);
if(ch >= 'A' && ch <= 'F') if (ch >= 'A' && ch <= 'F') return ch - 'A' + 0xA;
return ch - 'A' + 0xA;
throw new IllegalArgumentException("Not a hex character: " + ch); throw new IllegalArgumentException("Not a hex character: " + ch);
} }
@ -132,8 +120,7 @@ private String _hash_gensalt_private(
StringBuffer r = new StringBuffer(32); StringBuffer r = new StringBuffer(32);
for (int i = 0; i < bytes.length; i++) { for (int i = 0; i < bytes.length; i++) {
String x = Integer.toHexString(bytes[i] & 0xff); String x = Integer.toHexString(bytes[i] & 0xff);
if (x.length() < 2) if (x.length() < 2) r.append("0");
r.append("0");
r.append(x); r.append(x);
} }
return r.toString(); return r.toString();
@ -157,8 +144,8 @@ public String getHash(String password, String salt, String name)
} }
@Override @Override
public boolean comparePassword(String hash, String password, String playerName) public boolean comparePassword(String hash, String password,
throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
return phpbb_check_hash(password, hash); return phpbb_check_hash(password, hash);
} }
} }

View File

@ -11,7 +11,6 @@ import javax.crypto.spec.SecretKeySpec;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
public class PHPFUSION implements EncryptionMethod { public class PHPFUSION implements EncryptionMethod {
@Override @Override
@ -21,7 +20,8 @@ public class PHPFUSION implements EncryptionMethod {
String algo = "HmacSHA256"; String algo = "HmacSHA256";
String keyString = getSHA1(salt); String keyString = getSHA1(salt);
try { try {
SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo); SecretKeySpec key = new SecretKeySpec(
(keyString).getBytes("UTF-8"), algo);
Mac mac = Mac.getInstance(algo); Mac mac = Mac.getInstance(algo);
mac.init(key); mac.init(key);
byte[] bytes = mac.doFinal(password.getBytes("ASCII")); byte[] bytes = mac.doFinal(password.getBytes("ASCII"));
@ -44,16 +44,19 @@ public class PHPFUSION implements EncryptionMethod {
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); String salt = AuthMe.getInstance().database.getAuth(playerName)
.getSalt();
return hash.equals(getHash(password, salt, "")); return hash.equals(getHash(password, salt, ""));
} }
private static String getSHA1(String message) throws NoSuchAlgorithmException { private static String getSHA1(String message)
throws NoSuchAlgorithmException {
MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset(); sha1.reset();
sha1.update(message.getBytes()); sha1.update(message.getBytes());
byte[] digest = sha1.digest(); byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -6,24 +6,28 @@ import java.security.NoSuchAlgorithmException;
public class ROYALAUTH implements EncryptionMethod { public class ROYALAUTH implements EncryptionMethod {
@Override @Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
for (int i = 0; i < 25; i++) for (int i = 0; i < 25; i++)
password = hash(password, salt); password = hash(password, salt);
return password; return password;
} }
public String hash(String password, String salt) throws NoSuchAlgorithmException { public String hash(String password, String salt)
throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512"); MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(password.getBytes()); md.update(password.getBytes());
byte byteData[] = md.digest(); byte byteData[] = md.digest();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (byte aByteData : byteData) for (byte aByteData : byteData)
sb.append(Integer.toString((aByteData & 0xff) + 0x100, 16).substring(1)); sb.append(Integer.toString((aByteData & 0xff) + 0x100, 16)
.substring(1));
return sb.toString(); return sb.toString();
} }
@Override @Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException {
return hash.equalsIgnoreCase(getHash(password, "", "")); return hash.equalsIgnoreCase(getHash(password, "", ""));
} }

View File

@ -6,7 +6,6 @@ import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
public class SALTED2MD5 implements EncryptionMethod { public class SALTED2MD5 implements EncryptionMethod {
@Override @Override
@ -18,15 +17,18 @@ public class SALTED2MD5 implements EncryptionMethod {
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); String salt = AuthMe.getInstance().database.getAuth(playerName)
.getSalt();
return hash.equals(getMD5(getMD5(password) + salt)); return hash.equals(getMD5(getMD5(password) + salt));
} }
private static String getMD5(String message) throws NoSuchAlgorithmException { private static String getMD5(String message)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset(); md5.reset();
md5.update(message.getBytes()); md5.update(message.getBytes());
byte[] digest = md5.digest(); byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -7,22 +7,25 @@ import java.security.NoSuchAlgorithmException;
public class SHA1 implements EncryptionMethod { public class SHA1 implements EncryptionMethod {
@Override @Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return getSHA1(password); return getSHA1(password);
} }
@Override @Override
public boolean comparePassword(String hash, String password, String playerName) public boolean comparePassword(String hash, String password,
throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", "")); return hash.equals(getHash(password, "", ""));
} }
private static String getSHA1(String message) throws NoSuchAlgorithmException { private static String getSHA1(String message)
throws NoSuchAlgorithmException {
MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset(); sha1.reset();
sha1.update(message.getBytes()); sha1.update(message.getBytes());
byte[] digest = sha1.digest(); byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -7,23 +7,26 @@ import java.security.NoSuchAlgorithmException;
public class SHA256 implements EncryptionMethod { public class SHA256 implements EncryptionMethod {
@Override @Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
return "$SHA$" + salt + "$" + getSHA256(getSHA256(password) + salt); return "$SHA$" + salt + "$" + getSHA256(getSHA256(password) + salt);
} }
@Override @Override
public boolean comparePassword(String hash, String password, String playerName) public boolean comparePassword(String hash, String password,
throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String[] line = hash.split("\\$"); String[] line = hash.split("\\$");
return hash.equals(getHash(password, line[2], "")); return hash.equals(getHash(password, line[2], ""));
} }
private static String getSHA256(String message) throws NoSuchAlgorithmException { private static String getSHA256(String message)
throws NoSuchAlgorithmException {
MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
sha256.reset(); sha256.reset();
sha256.update(message.getBytes()); sha256.update(message.getBytes());
byte[] digest = sha256.digest(); byte[] digest = sha256.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -18,11 +18,13 @@ public class SHA512 implements EncryptionMethod {
return hash.equals(getHash(password, "", "")); return hash.equals(getHash(password, "", ""));
} }
private static String getSHA512(String message) throws NoSuchAlgorithmException { private static String getSHA512(String message)
throws NoSuchAlgorithmException {
MessageDigest sha512 = MessageDigest.getInstance("SHA-512"); MessageDigest sha512 = MessageDigest.getInstance("SHA-512");
sha512.reset(); sha512.reset();
sha512.update(message.getBytes()); sha512.update(message.getBytes());
byte[] digest = sha512.digest(); byte[] digest = sha512.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -18,11 +18,13 @@ public class SMF implements EncryptionMethod {
return hash.equals(getHash(password, null, playerName)); return hash.equals(getHash(password, null, playerName));
} }
private static String getSHA1(String message) throws NoSuchAlgorithmException { private static String getSHA1(String message)
throws NoSuchAlgorithmException {
MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset(); sha1.reset();
sha1.update(message.getBytes()); sha1.update(message.getBytes());
byte[] digest = sha1.digest(); byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -6,7 +6,6 @@ import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
public class WBB3 implements EncryptionMethod { public class WBB3 implements EncryptionMethod {
@Override @Override
@ -18,15 +17,18 @@ public class WBB3 implements EncryptionMethod {
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); String salt = AuthMe.getInstance().database.getAuth(playerName)
.getSalt();
return hash.equals(getHash(password, salt, "")); return hash.equals(getHash(password, salt, ""));
} }
private static String getSHA1(String message) throws NoSuchAlgorithmException { private static String getSHA1(String message)
throws NoSuchAlgorithmException {
MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset(); sha1.reset();
sha1.update(message.getBytes()); sha1.update(message.getBytes());
byte[] digest = sha1.digest(); byte[] digest = sha1.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,digest)); return String.format("%0" + (digest.length << 1) + "x", new BigInteger(
1, digest));
} }
} }

View File

@ -7,41 +7,45 @@ package fr.xephi.authme.security.crypts;
* <b>References</b> * <b>References</b>
* *
* <P> * <P>
* The Whirlpool algorithm was developed by * The Whirlpool algorithm was developed by <a
* <a href="mailto:pbarreto@scopus.com.br">Paulo S. L. M. Barreto</a> and * href="mailto:pbarreto@scopus.com.br">Paulo S. L. M. Barreto</a> and <a
* <a href="mailto:vincent.rijmen@cryptomathic.com">Vincent Rijmen</a>. * href="mailto:vincent.rijmen@cryptomathic.com">Vincent Rijmen</a>.
* *
* See * See P.S.L.M. Barreto, V. Rijmen, ``The Whirlpool hashing function,'' First
* P.S.L.M. Barreto, V. Rijmen, * NESSIE workshop, 2000 (tweaked version, 2003),
* ``The Whirlpool hashing function,'' * <https://www.cosic.esat.kuleuven
* First NESSIE workshop, 2000 (tweaked version, 2003), * .ac.be/nessie/workshop/submissions/whirlpool.zip>
* <https://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/whirlpool.zip>
* *
* @author Paulo S.L.M. Barreto * @author Paulo S.L.M. Barreto
* @author Vincent Rijmen. * @author Vincent Rijmen.
* *
* @version 3.0 (2003.03.12) * @version 3.0 (2003.03.12)
* *
* ============================================================================= * ====================================================================
* =========
* *
* Differences from version 2.1: * Differences from version 2.1:
* *
* - Suboptimal diffusion matrix replaced by cir(1, 1, 4, 1, 8, 5, 2, 9). * - Suboptimal diffusion matrix replaced by cir(1, 1, 4, 1, 8, 5, 2,
* 9).
* *
* ============================================================================= * ====================================================================
* =========
* *
* Differences from version 2.0: * Differences from version 2.0:
* *
* - Generation of ISO/IEC 10118-3 test vectors. * - Generation of ISO/IEC 10118-3 test vectors. - Bug fix: nonzero
* - Bug fix: nonzero carry was ignored when tallying the data length * carry was ignored when tallying the data length (this bug apparently
* (this bug apparently only manifested itself when feeding data * only manifested itself when feeding data in pieces rather than in a
* in pieces rather than in a single chunk at once). * single chunk at once).
* *
* Differences from version 1.0: * Differences from version 1.0:
* *
* - Original S-box replaced by the tweaked, hardware-efficient version. * - Original S-box replaced by the tweaked, hardware-efficient
* version.
* *
* ============================================================================= * ====================================================================
* =========
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -50,10 +54,10 @@ package fr.xephi.authme.security.crypts;
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
@ -80,23 +84,22 @@ public class WHIRLPOOL implements EncryptionMethod {
/** /**
* The substitution box. * The substitution box.
*/ */
private static final String sbox = private static final String sbox = "\u1823\uc6E8\u87B8\u014F\u36A6\ud2F5\u796F\u9152"
"\u1823\uc6E8\u87B8\u014F\u36A6\ud2F5\u796F\u9152" + + "\u60Bc\u9B8E\uA30c\u7B35\u1dE0\ud7c2\u2E4B\uFE57"
"\u60Bc\u9B8E\uA30c\u7B35\u1dE0\ud7c2\u2E4B\uFE57" + + "\u1577\u37E5\u9FF0\u4AdA\u58c9\u290A\uB1A0\u6B85"
"\u1577\u37E5\u9FF0\u4AdA\u58c9\u290A\uB1A0\u6B85" + + "\uBd5d\u10F4\ucB3E\u0567\uE427\u418B\uA77d\u95d8"
"\uBd5d\u10F4\ucB3E\u0567\uE427\u418B\uA77d\u95d8" + + "\uFBEE\u7c66\udd17\u479E\ucA2d\uBF07\uAd5A\u8333"
"\uFBEE\u7c66\udd17\u479E\ucA2d\uBF07\uAd5A\u8333" + + "\u6302\uAA71\uc819\u49d9\uF2E3\u5B88\u9A26\u32B0"
"\u6302\uAA71\uc819\u49d9\uF2E3\u5B88\u9A26\u32B0" + + "\uE90F\ud580\uBEcd\u3448\uFF7A\u905F\u2068\u1AAE"
"\uE90F\ud580\uBEcd\u3448\uFF7A\u905F\u2068\u1AAE" + + "\uB454\u9322\u64F1\u7312\u4008\uc3Ec\udBA1\u8d3d"
"\uB454\u9322\u64F1\u7312\u4008\uc3Ec\udBA1\u8d3d" + + "\u9700\ucF2B\u7682\ud61B\uB5AF\u6A50\u45F3\u30EF"
"\u9700\ucF2B\u7682\ud61B\uB5AF\u6A50\u45F3\u30EF" + + "\u3F55\uA2EA\u65BA\u2Fc0\udE1c\uFd4d\u9275\u068A"
"\u3F55\uA2EA\u65BA\u2Fc0\udE1c\uFd4d\u9275\u068A" + + "\uB2E6\u0E1F\u62d4\uA896\uF9c5\u2559\u8472\u394c"
"\uB2E6\u0E1F\u62d4\uA896\uF9c5\u2559\u8472\u394c" + + "\u5E78\u388c\ud1A5\uE261\uB321\u9c1E\u43c7\uFc04"
"\u5E78\u388c\ud1A5\uE261\uB321\u9c1E\u43c7\uFc04" + + "\u5199\u6d0d\uFAdF\u7E24\u3BAB\ucE11\u8F4E\uB7EB"
"\u5199\u6d0d\uFAdF\u7E24\u3BAB\ucE11\u8F4E\uB7EB" + + "\u3c81\u94F7\uB913\u2cd3\uE76E\uc403\u5644\u7FA9"
"\u3c81\u94F7\uB913\u2cd3\uE76E\uc403\u5644\u7FA9" + + "\u2ABB\uc153\udc0B\u9d6c\u3174\uF646\uAc89\u14E1"
"\u2ABB\uc153\udc0B\u9d6c\u3174\uF646\uAc89\u14E1" + + "\u163A\u6909\u70B6\ud0Ed\ucc42\u98A4\u285c\uF886";
"\u163A\u6909\u70B6\ud0Ed\ucc42\u98A4\u285c\uF886";
private static long[][] C = new long[8][256]; private static long[][] C = new long[8][256];
private static long[] rc = new long[R + 1]; private static long[] rc = new long[R + 1];
@ -120,11 +123,11 @@ public class WHIRLPOOL implements EncryptionMethod {
} }
long v9 = v8 ^ v1; long v9 = v8 ^ v1;
/* /*
* build the circulant table C[0][x] = S[x].[1, 1, 4, 1, 8, 5, 2, 9]: * build the circulant table C[0][x] = S[x].[1, 1, 4, 1, 8, 5, 2,
* 9]:
*/ */
C[0][x] = C[0][x] = (v1 << 56) | (v1 << 48) | (v4 << 40) | (v1 << 32)
(v1 << 56) | (v1 << 48) | (v4 << 40) | (v1 << 32) | | (v8 << 24) | (v5 << 16) | (v2 << 8) | (v9);
(v8 << 24) | (v5 << 16) | (v2 << 8) | (v9 );
/* /*
* build the remaining circulant tables C[t][x] = C[0][x] rotr t * build the remaining circulant tables C[t][x] = C[0][x] rotr t
*/ */
@ -135,18 +138,20 @@ public class WHIRLPOOL implements EncryptionMethod {
/* /*
* build the round constants: * build the round constants:
*/ */
rc[0] = 0L; /* not used (assigment kept only to properly initialize all variables) */ rc[0] = 0L; /*
* not used (assigment kept only to properly initialize all
* variables)
*/
for (int r = 1; r <= R; r++) { for (int r = 1; r <= R; r++) {
int i = 8 * (r - 1); int i = 8 * (r - 1);
rc[r] = rc[r] = (C[0][i] & 0xff00000000000000L)
(C[0][i ] & 0xff00000000000000L) ^ ^ (C[1][i + 1] & 0x00ff000000000000L)
(C[1][i + 1] & 0x00ff000000000000L) ^ ^ (C[2][i + 2] & 0x0000ff0000000000L)
(C[2][i + 2] & 0x0000ff0000000000L) ^ ^ (C[3][i + 3] & 0x000000ff00000000L)
(C[3][i + 3] & 0x000000ff00000000L) ^ ^ (C[4][i + 4] & 0x00000000ff000000L)
(C[4][i + 4] & 0x00000000ff000000L) ^ ^ (C[5][i + 5] & 0x0000000000ff0000L)
(C[5][i + 5] & 0x0000000000ff0000L) ^ ^ (C[6][i + 6] & 0x000000000000ff00L)
(C[6][i + 6] & 0x000000000000ff00L) ^ ^ (C[7][i + 7] & 0x00000000000000ffL);
(C[7][i + 7] & 0x00000000000000ffL);
} }
} }
@ -190,15 +195,14 @@ public class WHIRLPOOL implements EncryptionMethod {
* map the buffer to a block: * map the buffer to a block:
*/ */
for (int i = 0, j = 0; i < 8; i++, j += 8) { for (int i = 0, j = 0; i < 8; i++, j += 8) {
block[i] = block[i] = (((long) buffer[j]) << 56)
(((long)buffer[j ] ) << 56) ^ ^ (((long) buffer[j + 1] & 0xffL) << 48)
(((long)buffer[j + 1] & 0xffL) << 48) ^ ^ (((long) buffer[j + 2] & 0xffL) << 40)
(((long)buffer[j + 2] & 0xffL) << 40) ^ ^ (((long) buffer[j + 3] & 0xffL) << 32)
(((long)buffer[j + 3] & 0xffL) << 32) ^ ^ (((long) buffer[j + 4] & 0xffL) << 24)
(((long)buffer[j + 4] & 0xffL) << 24) ^ ^ (((long) buffer[j + 5] & 0xffL) << 16)
(((long)buffer[j + 5] & 0xffL) << 16) ^ ^ (((long) buffer[j + 6] & 0xffL) << 8)
(((long)buffer[j + 6] & 0xffL) << 8) ^ ^ (((long) buffer[j + 7] & 0xffL));
(((long)buffer[j + 7] & 0xffL) );
} }
/* /*
* compute and apply K^0 to the cipher state: * compute and apply K^0 to the cipher state:
@ -257,26 +261,25 @@ public class WHIRLPOOL implements EncryptionMethod {
/** /**
* Delivers input data to the hashing algorithm. * Delivers input data to the hashing algorithm.
* *
* @param source plaintext data to hash. * @param source
* @param sourceBits how many bits of plaintext to process. * plaintext data to hash.
* @param sourceBits
* how many bits of plaintext to process.
* *
* This method maintains the invariant: bufferBits < 512 * This method maintains the invariant: bufferBits < 512
*/ */
public void NESSIEadd(byte[] source, long sourceBits) { public void NESSIEadd(byte[] source, long sourceBits) {
/* /*
sourcePos * sourcePos | +-------+-------+------- ||||||||||||||||||||| source
| * +-------+-------+-------
+-------+-------+------- * +-------+-------+-------+-------+-------+-------
||||||||||||||||||||| source * |||||||||||||||||||||| buffer
+-------+-------+------- * +-------+-------+-------+-------+-------+------- | bufferPos
+-------+-------+-------+-------+-------+-------
|||||||||||||||||||||| buffer
+-------+-------+-------+-------+-------+-------
|
bufferPos
*/ */
int sourcePos = 0; // index of leftmost source byte containing data (1 to 8 bits). int sourcePos = 0; // index of leftmost source byte containing data (1
int sourceGap = (8 - ((int)sourceBits & 7)) & 7; // space on source[sourcePos]. // to 8 bits).
int sourceGap = (8 - ((int) sourceBits & 7)) & 7; // space on
// source[sourcePos].
int bufferRem = bufferBits & 7; // occupied bits on buffer[bufferPos]. int bufferRem = bufferBits & 7; // occupied bits on buffer[bufferPos].
int b; int b;
// tally the length of the added data: // tally the length of the added data:
@ -288,10 +291,11 @@ public class WHIRLPOOL implements EncryptionMethod {
value >>>= 8; value >>>= 8;
} }
// process data in chunks of 8 bits: // process data in chunks of 8 bits:
while (sourceBits > 8) { // at least source[sourcePos] and source[sourcePos+1] contain data. while (sourceBits > 8) { // at least source[sourcePos] and
// source[sourcePos+1] contain data.
// take a byte from the source: // take a byte from the source:
b = ((source[sourcePos] << sourceGap) & 0xff) | b = ((source[sourcePos] << sourceGap) & 0xff)
((source[sourcePos + 1] & 0xff) >>> (8 - sourceGap)); | ((source[sourcePos + 1] & 0xff) >>> (8 - sourceGap));
if (b < 0 || b >= 256) { if (b < 0 || b >= 256) {
throw new RuntimeException("LOGIC ERROR"); throw new RuntimeException("LOGIC ERROR");
} }
@ -313,21 +317,24 @@ public class WHIRLPOOL implements EncryptionMethod {
// now 0 <= sourceBits <= 8; // now 0 <= sourceBits <= 8;
// furthermore, all data (if any is left) is in source[sourcePos]. // furthermore, all data (if any is left) is in source[sourcePos].
if (sourceBits > 0) { if (sourceBits > 0) {
b = (source[sourcePos] << sourceGap) & 0xff; // bits are left-justified on b. b = (source[sourcePos] << sourceGap) & 0xff; // bits are
// left-justified on b.
// process the remaining bits: // process the remaining bits:
buffer[bufferPos] |= b >>> bufferRem; buffer[bufferPos] |= b >>> bufferRem;
} else { } else {
b = 0; b = 0;
} }
if (bufferRem + sourceBits < 8) { if (bufferRem + sourceBits < 8) {
// all remaining data fits on buffer[bufferPos], and there still remains some space. // all remaining data fits on buffer[bufferPos], and there still
// remains some space.
bufferBits += sourceBits; bufferBits += sourceBits;
} else { } else {
// buffer[bufferPos] is full: // buffer[bufferPos] is full:
bufferPos++; bufferPos++;
bufferBits += 8 - bufferRem; // bufferBits = 8*bufferPos; bufferBits += 8 - bufferRem; // bufferBits = 8*bufferPos;
sourceBits -= 8 - bufferRem; sourceBits -= 8 - bufferRem;
// now 0 <= sourceBits < 8; furthermore, all data is in source[sourcePos]. // now 0 <= sourceBits < 8; furthermore, all data is in
// source[sourcePos].
if (bufferBits == 512) { if (bufferBits == 512) {
// process data block: // process data block:
processBuffer(); processBuffer();
@ -382,7 +389,8 @@ public class WHIRLPOOL implements EncryptionMethod {
/** /**
* Delivers string input data to the hashing algorithm. * Delivers string input data to the hashing algorithm.
* *
* @param source plaintext data to hash (ASCII text string). * @param source
* plaintext data to hash (ASCII text string).
* *
* This method maintains the invariant: bufferBits < 512 * This method maintains the invariant: bufferBits < 512
*/ */

View File

@ -47,7 +47,8 @@ public class WORDPRESS implements EncryptionMethod {
private String crypt(String password, String setting) { private String crypt(String password, String setting) {
String output = "*0"; String output = "*0";
if (((setting.length() < 2) ? setting : setting.substring(0, 2)).equalsIgnoreCase(output)) { if (((setting.length() < 2) ? setting : setting.substring(0, 2))
.equalsIgnoreCase(output)) {
output = "*1"; output = "*1";
} }
String id = (setting.length() < 3) ? setting : setting.substring(0, 3); String id = (setting.length() < 3) ? setting : setting.substring(0, 3);
@ -94,12 +95,14 @@ public class WORDPRESS implements EncryptionMethod {
try { try {
return string.getBytes("UTF-8"); return string.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException("This system doesn't support UTF-8!", e); throw new UnsupportedOperationException(
"This system doesn't support UTF-8!", e);
} }
} }
@Override @Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException {
byte random[] = new byte[6]; byte random[] = new byte[6];
this.randomGen.nextBytes(random); this.randomGen.nextBytes(random);
return crypt(password, gensaltPrivate(stringToUtf8(new String(random)))); return crypt(password, gensaltPrivate(stringToUtf8(new String(random))));

View File

@ -8,14 +8,16 @@ public class XAUTH implements EncryptionMethod {
public String getHash(String password, String salt, String name) public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException { throws NoSuchAlgorithmException {
String hash = getWhirlpool(salt + password).toLowerCase(); String hash = getWhirlpool(salt + password).toLowerCase();
int saltPos = (password.length() >= hash.length() ? hash.length() - 1 : password.length()); int saltPos = (password.length() >= hash.length() ? hash.length() - 1
: password.length());
return hash.substring(0, saltPos) + salt + hash.substring(saltPos); return hash.substring(0, saltPos) + salt + hash.substring(saltPos);
} }
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
int saltPos = (password.length() >= hash.length() ? hash.length() - 1 : password.length()); int saltPos = (password.length() >= hash.length() ? hash.length() - 1
: password.length());
String salt = hash.substring(saltPos, saltPos + 12); String salt = hash.substring(saltPos, saltPos + 12);
return hash.equals(getHash(password, salt, "")); return hash.equals(getHash(password, salt, ""));
} }

View File

@ -9,38 +9,37 @@ import java.util.regex.Pattern;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
public class XF implements EncryptionMethod { public class XF implements EncryptionMethod {
@Override @Override
public String getHash(String password, String salt, String name) public String getHash(String password, String salt, String name)
throws NoSuchAlgorithmException { throws NoSuchAlgorithmException {
return getSHA256(getSHA256(password) + regmatch("\"salt\";.:..:\"(.*)\";.:.:\"hashFunc\"", salt)); return getSHA256(getSHA256(password)
+ regmatch("\"salt\";.:..:\"(.*)\";.:.:\"hashFunc\"", salt));
} }
@Override @Override
public boolean comparePassword(String hash, String password, public boolean comparePassword(String hash, String password,
String playerName) throws NoSuchAlgorithmException { String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); String salt = AuthMe.getInstance().database.getAuth(playerName)
return hash.equals(regmatch("\"hash\";.:..:\"(.*)\";.:.:\"salt\"", salt)); .getSalt();
return hash
.equals(regmatch("\"hash\";.:..:\"(.*)\";.:.:\"salt\"", salt));
} }
public String getSHA256(String password) throws NoSuchAlgorithmException public String getSHA256(String password) throws NoSuchAlgorithmException {
{
MessageDigest md = MessageDigest.getInstance("SHA-256"); MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes()); md.update(password.getBytes());
byte byteData[] = md.digest(); byte byteData[] = md.digest();
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (byte element : byteData) for (byte element : byteData) {
{ sb.append(Integer.toString((element & 0xff) + 0x100, 16).substring(
sb.append(Integer.toString((element & 0xff) + 0x100, 16).substring(1)); 1));
} }
StringBuffer hexString = new StringBuffer(); StringBuffer hexString = new StringBuffer();
for (byte element : byteData) for (byte element : byteData) {
{
String hex = Integer.toHexString(0xff & element); String hex = Integer.toHexString(0xff & element);
if (hex.length() == 1) if (hex.length() == 1) {
{
hexString.append('0'); hexString.append('0');
} }
hexString.append(hex); hexString.append(hex);
@ -48,12 +47,10 @@ public class XF implements EncryptionMethod {
return hexString.toString(); return hexString.toString();
} }
public String regmatch(String pattern, String line) public String regmatch(String pattern, String line) {
{
List<String> allMatches = new ArrayList<String>(); List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile(pattern).matcher(line); Matcher m = Pattern.compile(pattern).matcher(line);
while (m.find()) while (m.find()) {
{
allMatches.add(m.group(1)); allMatches.add(m.group(1));
} }
return allMatches.get(0); return allMatches.get(0);

View File

@ -23,14 +23,14 @@ package fr.xephi.authme.security.pbkdf2;
* </p> * </p>
* <p> * <p>
* For Details, see <a * For Details, see <a
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>. * href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
* >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* </p> * </p>
* *
* @author Matthias G&auml;rtner * @author Matthias G&auml;rtner
* @version 1.0 * @version 1.0
*/ */
public class BinTools public class BinTools {
{
public static final String hex = "0123456789ABCDEF"; public static final String hex = "0123456789ABCDEF";
/** /**
@ -41,15 +41,12 @@ public class BinTools
* @return Hexadecimal representation of b. Uppercase A-F, two characters * @return Hexadecimal representation of b. Uppercase A-F, two characters
* per byte. Empty string on <code>null</code> input. * per byte. Empty string on <code>null</code> input.
*/ */
public static String bin2hex(final byte[] b) public static String bin2hex(final byte[] b) {
{ if (b == null) {
if (b == null)
{
return ""; return "";
} }
StringBuffer sb = new StringBuffer(2 * b.length); StringBuffer sb = new StringBuffer(2 * b.length);
for (int i = 0; i < b.length; i++) for (int i = 0; i < b.length; i++) {
{
int v = (256 + b[i]) % 256; int v = (256 + b[i]) % 256;
sb.append(hex.charAt((v / 16) & 15)); sb.append(hex.charAt((v / 16) & 15));
sb.append(hex.charAt((v % 16) & 15)); sb.append(hex.charAt((v % 16) & 15));
@ -61,28 +58,23 @@ public class BinTools
* Convert hex string to array of bytes. * Convert hex string to array of bytes.
* *
* @param s * @param s
* String containing hexadecimal digits. May be <code>null</code>. * String containing hexadecimal digits. May be <code>null</code>
* On odd length leading zero will be assumed. * . On odd length leading zero will be assumed.
* @return Array on bytes, non-<code>null</code>. * @return Array on bytes, non-<code>null</code>.
* @throws IllegalArgumentException * @throws IllegalArgumentException
* when string contains non-hex character * when string contains non-hex character
*/ */
public static byte[] hex2bin(final String s) public static byte[] hex2bin(final String s) {
{
String m = s; String m = s;
if (s == null) if (s == null) {
{
// Allow empty input string. // Allow empty input string.
m = ""; m = "";
} } else if (s.length() % 2 != 0) {
else if (s.length() % 2 != 0)
{
// Assume leading zero for odd string length // Assume leading zero for odd string length
m = "0" + s; m = "0" + s;
} }
byte r[] = new byte[m.length() / 2]; byte r[] = new byte[m.length() / 2];
for (int i = 0, n = 0; i < m.length(); n++) for (int i = 0, n = 0; i < m.length(); n++) {
{
char h = m.charAt(i++); char h = m.charAt(i++);
char l = m.charAt(i++); char l = m.charAt(i++);
r[n] = (byte) (hex2bin(h) * 16 + hex2bin(l)); r[n] = (byte) (hex2bin(h) * 16 + hex2bin(l));
@ -99,18 +91,14 @@ public class BinTools
* @throws IllegalArgumentException * @throws IllegalArgumentException
* on non-hex character * on non-hex character
*/ */
public static int hex2bin(char c) public static int hex2bin(char c) {
{ if (c >= '0' && c <= '9') {
if (c >= '0' && c <= '9')
{
return (c - '0'); return (c - '0');
} }
if (c >= 'A' && c <= 'F') if (c >= 'A' && c <= 'F') {
{
return (c - 'A' + 10); return (c - 'A' + 10);
} }
if (c >= 'a' && c <= 'f') if (c >= 'a' && c <= 'f') {
{
return (c - 'a' + 10); return (c - 'a' + 10);
} }
throw new IllegalArgumentException( throw new IllegalArgumentException(
@ -118,19 +106,16 @@ public class BinTools
+ "'"); + "'");
} }
public static void main(String[] args) public static void main(String[] args) {
{
byte b[] = new byte[256]; byte b[] = new byte[256];
byte bb = 0; byte bb = 0;
for (int i = 0; i < 256; i++) for (int i = 0; i < 256; i++) {
{
b[i] = bb++; b[i] = bb++;
} }
String s = bin2hex(b); String s = bin2hex(b);
byte c[] = hex2bin(s); byte c[] = hex2bin(s);
String t = bin2hex(c); String t = bin2hex(c);
if (!s.equals(t)) if (!s.equals(t)) {
{
throw new AssertionError("Mismatch"); throw new AssertionError("Mismatch");
} }
} }

View File

@ -34,14 +34,14 @@ import javax.crypto.spec.SecretKeySpec;
* </p> * </p>
* <p> * <p>
* For Details, see <a * For Details, see <a
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>. * href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
* >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* </p> * </p>
* *
* @author Matthias G&auml;rtner * @author Matthias G&auml;rtner
* @version 1.0 * @version 1.0
*/ */
public class MacBasedPRF implements PRF public class MacBasedPRF implements PRF {
{
protected Mac mac; protected Mac mac;
protected int hLen; protected int hLen;
@ -54,57 +54,41 @@ public class MacBasedPRF implements PRF
* @param macAlgorithm * @param macAlgorithm
* Mac algorithm to use, i.e. HMacSHA1 or HMacMD5. * Mac algorithm to use, i.e. HMacSHA1 or HMacMD5.
*/ */
public MacBasedPRF(String macAlgorithm) public MacBasedPRF(String macAlgorithm) {
{
this.macAlgorithm = macAlgorithm; this.macAlgorithm = macAlgorithm;
try try {
{
mac = Mac.getInstance(macAlgorithm); mac = Mac.getInstance(macAlgorithm);
hLen = mac.getMacLength(); hLen = mac.getMacLength();
} } catch (NoSuchAlgorithmException e) {
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public MacBasedPRF(String macAlgorithm, String provider) public MacBasedPRF(String macAlgorithm, String provider) {
{
this.macAlgorithm = macAlgorithm; this.macAlgorithm = macAlgorithm;
try try {
{
mac = Mac.getInstance(macAlgorithm, provider); mac = Mac.getInstance(macAlgorithm, provider);
hLen = mac.getMacLength(); hLen = mac.getMacLength();
} } catch (NoSuchAlgorithmException e) {
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e); throw new RuntimeException(e);
} } catch (NoSuchProviderException e) {
catch (NoSuchProviderException e)
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public byte[] doFinal(byte[] M) public byte[] doFinal(byte[] M) {
{
byte[] r = mac.doFinal(M); byte[] r = mac.doFinal(M);
return r; return r;
} }
public int getHLen() public int getHLen() {
{
return hLen; return hLen;
} }
public void init(byte[] P) public void init(byte[] P) {
{ try {
try
{
mac.init(new SecretKeySpec(P, macAlgorithm)); mac.init(new SecretKeySpec(P, macAlgorithm));
} } catch (InvalidKeyException e) {
catch (InvalidKeyException e)
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }

View File

@ -24,14 +24,14 @@ package fr.xephi.authme.security.pbkdf2;
* </p> * </p>
* <p> * <p>
* For Details, see <a * For Details, see <a
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>. * href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
* >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* </p> * </p>
* *
* @author Matthias G&auml;rtner * @author Matthias G&auml;rtner
* @version 1.0 * @version 1.0
*/ */
public interface PBKDF2 public interface PBKDF2 {
{
/** /**
* Convert String-based input to internal byte array, then invoke PBKDF2. * Convert String-based input to internal byte array, then invoke PBKDF2.
* Desired key length defaults to Pseudo Random Function block size. * Desired key length defaults to Pseudo Random Function block size.
@ -60,8 +60,8 @@ public interface PBKDF2
* *
* @param inputPassword * @param inputPassword
* Candidate password to compute the derived key for. * Candidate password to compute the derived key for.
* @return <code>true</code> password match; <code>false</code> * @return <code>true</code> password match; <code>false</code> incorrect
* incorrect password * password
*/ */
public abstract boolean verifyKey(String inputPassword); public abstract boolean verifyKey(String inputPassword);

View File

@ -61,15 +61,15 @@ import java.security.SecureRandom;
* </p> * </p>
* <p> * <p>
* For Details, see <a * For Details, see <a
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>. * href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
* >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* </p> * </p>
* *
* @see <a href="http://tools.ietf.org/html/rfc2898">RFC 2898</a> * @see <a href="http://tools.ietf.org/html/rfc2898">RFC 2898</a>
* @author Matthias G&auml;rtner * @author Matthias G&auml;rtner
* @version 1.0 * @version 1.0
*/ */
public class PBKDF2Engine implements PBKDF2 public class PBKDF2Engine implements PBKDF2 {
{
protected PBKDF2Parameters parameters; protected PBKDF2Parameters parameters;
protected PRF prf; protected PRF prf;
@ -78,8 +78,7 @@ public class PBKDF2Engine implements PBKDF2
* Constructor for PBKDF2 implementation object. PBKDF2 parameters must be * Constructor for PBKDF2 implementation object. PBKDF2 parameters must be
* passed later. * passed later.
*/ */
public PBKDF2Engine() public PBKDF2Engine() {
{
this.parameters = null; this.parameters = null;
prf = null; prf = null;
} }
@ -92,8 +91,7 @@ public class PBKDF2Engine implements PBKDF2
* @param parameters * @param parameters
* Data holder for iteration count, method to use et cetera. * Data holder for iteration count, method to use et cetera.
*/ */
public PBKDF2Engine(PBKDF2Parameters parameters) public PBKDF2Engine(PBKDF2Parameters parameters) {
{
this.parameters = parameters; this.parameters = parameters;
prf = null; prf = null;
} }
@ -108,44 +106,33 @@ public class PBKDF2Engine implements PBKDF2
* @param prf * @param prf
* Supply customer Pseudo Random Function. * Supply customer Pseudo Random Function.
*/ */
public PBKDF2Engine(PBKDF2Parameters parameters, PRF prf) public PBKDF2Engine(PBKDF2Parameters parameters, PRF prf) {
{
this.parameters = parameters; this.parameters = parameters;
this.prf = prf; this.prf = prf;
} }
public byte[] deriveKey(String inputPassword) public byte[] deriveKey(String inputPassword) {
{
return deriveKey(inputPassword, 0); return deriveKey(inputPassword, 0);
} }
public byte[] deriveKey(String inputPassword, int dkLen) public byte[] deriveKey(String inputPassword, int dkLen) {
{
byte[] r = null; byte[] r = null;
byte P[] = null; byte P[] = null;
String charset = parameters.getHashCharset(); String charset = parameters.getHashCharset();
if (inputPassword == null) if (inputPassword == null) {
{
inputPassword = ""; inputPassword = "";
} }
try try {
{ if (charset == null) {
if (charset == null)
{
P = inputPassword.getBytes(); P = inputPassword.getBytes();
} } else {
else
{
P = inputPassword.getBytes(charset); P = inputPassword.getBytes(charset);
} }
} } catch (UnsupportedEncodingException e) {
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
assertPRF(P); assertPRF(P);
if (dkLen == 0) if (dkLen == 0) {
{
dkLen = prf.getHLen(); dkLen = prf.getHLen();
} }
r = PBKDF2(prf, parameters.getSalt(), parameters.getIterationCount(), r = PBKDF2(prf, parameters.getSalt(), parameters.getIterationCount(),
@ -153,23 +140,18 @@ public class PBKDF2Engine implements PBKDF2
return r; return r;
} }
public boolean verifyKey(String inputPassword) public boolean verifyKey(String inputPassword) {
{
byte[] referenceKey = getParameters().getDerivedKey(); byte[] referenceKey = getParameters().getDerivedKey();
if (referenceKey == null || referenceKey.length == 0) if (referenceKey == null || referenceKey.length == 0) {
{
return false; return false;
} }
byte[] inputKey = deriveKey(inputPassword, referenceKey.length); byte[] inputKey = deriveKey(inputPassword, referenceKey.length);
if (inputKey == null || inputKey.length != referenceKey.length) if (inputKey == null || inputKey.length != referenceKey.length) {
{
return false; return false;
} }
for (int i = 0; i < inputKey.length; i++) for (int i = 0; i < inputKey.length; i++) {
{ if (inputKey[i] != referenceKey[i]) {
if (inputKey[i] != referenceKey[i])
{
return false; return false;
} }
} }
@ -183,17 +165,14 @@ public class PBKDF2Engine implements PBKDF2
* @param P * @param P
* User-supplied candidate password as array of bytes. * User-supplied candidate password as array of bytes.
*/ */
protected void assertPRF(byte[] P) protected void assertPRF(byte[] P) {
{ if (prf == null) {
if (prf == null)
{
prf = new MacBasedPRF(parameters.getHashAlgorithm()); prf = new MacBasedPRF(parameters.getHashAlgorithm());
} }
prf.init(P); prf.init(P);
} }
public PRF getPseudoRandomFunction() public PRF getPseudoRandomFunction() {
{
return prf; return prf;
} }
@ -211,10 +190,8 @@ public class PBKDF2Engine implements PBKDF2
* desired length of derived key. * desired length of derived key.
* @return internal byte array * @return internal byte array
*/ */
protected byte[] PBKDF2(PRF prf, byte[] S, int c, int dkLen) protected byte[] PBKDF2(PRF prf, byte[] S, int c, int dkLen) {
{ if (S == null) {
if (S == null)
{
S = new byte[0]; S = new byte[0];
} }
int hLen = prf.getHLen(); int hLen = prf.getHLen();
@ -222,13 +199,11 @@ public class PBKDF2Engine implements PBKDF2
int r = dkLen - (l - 1) * hLen; int r = dkLen - (l - 1) * hLen;
byte T[] = new byte[l * hLen]; byte T[] = new byte[l * hLen];
int ti_offset = 0; int ti_offset = 0;
for (int i = 1; i <= l; i++) for (int i = 1; i <= l; i++) {
{
_F(T, ti_offset, prf, S, c, i); _F(T, ti_offset, prf, S, c, i);
ti_offset += hLen; ti_offset += hLen;
} }
if (r < hLen) if (r < hLen) {
{
// Incomplete last block // Incomplete last block
byte DK[] = new byte[dkLen]; byte DK[] = new byte[dkLen];
System.arraycopy(T, 0, DK, 0, dkLen); System.arraycopy(T, 0, DK, 0, dkLen);
@ -240,16 +215,15 @@ public class PBKDF2Engine implements PBKDF2
/** /**
* Integer division with ceiling function. * Integer division with ceiling function.
* *
* @see <a href="http://tools.ietf.org/html/rfc2898">RFC 2898 5.2 Step 2.</a> * @see <a href="http://tools.ietf.org/html/rfc2898">RFC 2898 5.2 Step
* 2.</a>
* @param a * @param a
* @param b * @param b
* @return ceil(a/b) * @return ceil(a/b)
*/ */
protected int ceil(int a, int b) protected int ceil(int a, int b) {
{
int m = 0; int m = 0;
if (a % b > 0) if (a % b > 0) {
{
m = 1; m = 1;
} }
return a / b + m; return a / b + m;
@ -258,7 +232,8 @@ public class PBKDF2Engine implements PBKDF2
/** /**
* Function F. * Function F.
* *
* @see <a href="http://tools.ietf.org/html/rfc2898">RFC 2898 5.2 Step 3.</a> * @see <a href="http://tools.ietf.org/html/rfc2898">RFC 2898 5.2 Step
* 3.</a>
* @param dest * @param dest
* Destination byte buffer * Destination byte buffer
* @param offset * @param offset
@ -272,8 +247,7 @@ public class PBKDF2Engine implements PBKDF2
* @param blockIndex * @param blockIndex
*/ */
protected void _F(byte[] dest, int offset, PRF prf, byte[] S, int c, protected void _F(byte[] dest, int offset, PRF prf, byte[] S, int c,
int blockIndex) int blockIndex) {
{
int hLen = prf.getHLen(); int hLen = prf.getHLen();
byte U_r[] = new byte[hLen]; byte U_r[] = new byte[hLen];
@ -282,8 +256,7 @@ public class PBKDF2Engine implements PBKDF2
System.arraycopy(S, 0, U_i, 0, S.length); System.arraycopy(S, 0, U_i, 0, S.length);
INT(U_i, S.length, blockIndex); INT(U_i, S.length, blockIndex);
for (int i = 0; i < c; i++) for (int i = 0; i < c; i++) {
{
U_i = prf.doFinal(U_i); U_i = prf.doFinal(U_i);
xor(U_r, U_i); xor(U_r, U_i);
} }
@ -297,10 +270,8 @@ public class PBKDF2Engine implements PBKDF2
* @param dest * @param dest
* @param src * @param src
*/ */
protected void xor(byte[] dest, byte[] src) protected void xor(byte[] dest, byte[] src) {
{ for (int i = 0; i < dest.length; i++) {
for (int i = 0; i < dest.length; i++)
{
dest[i] ^= src[i]; dest[i] ^= src[i];
} }
} }
@ -308,31 +279,28 @@ public class PBKDF2Engine implements PBKDF2
/** /**
* Four-octet encoding of the integer i, most significant octet first. * Four-octet encoding of the integer i, most significant octet first.
* *
* @see <a href="http://tools.ietf.org/html/rfc2898">RFC 2898 5.2 Step 3.</a> * @see <a href="http://tools.ietf.org/html/rfc2898">RFC 2898 5.2 Step
* 3.</a>
* @param dest * @param dest
* @param offset * @param offset
* @param i * @param i
*/ */
protected void INT(byte[] dest, int offset, int i) protected void INT(byte[] dest, int offset, int i) {
{
dest[offset + 0] = (byte) (i / (256 * 256 * 256)); dest[offset + 0] = (byte) (i / (256 * 256 * 256));
dest[offset + 1] = (byte) (i / (256 * 256)); dest[offset + 1] = (byte) (i / (256 * 256));
dest[offset + 2] = (byte) (i / (256)); dest[offset + 2] = (byte) (i / (256));
dest[offset + 3] = (byte) (i); dest[offset + 3] = (byte) (i);
} }
public PBKDF2Parameters getParameters() public PBKDF2Parameters getParameters() {
{
return parameters; return parameters;
} }
public void setParameters(PBKDF2Parameters parameters) public void setParameters(PBKDF2Parameters parameters) {
{
this.parameters = parameters; this.parameters = parameters;
} }
public void setPseudoRandomFunction(PRF prf) public void setPseudoRandomFunction(PRF prf) {
{
this.prf = prf; this.prf = prf;
} }
@ -352,22 +320,18 @@ public class PBKDF2Engine implements PBKDF2
* @throws NoSuchAlgorithmException * @throws NoSuchAlgorithmException
*/ */
public static void main(String[] args) throws IOException, public static void main(String[] args) throws IOException,
NoSuchAlgorithmException NoSuchAlgorithmException {
{
String password = "password"; String password = "password";
String candidate = null; String candidate = null;
PBKDF2Formatter formatter = new PBKDF2HexFormatter(); PBKDF2Formatter formatter = new PBKDF2HexFormatter();
if (args.length >= 1) if (args.length >= 1) {
{
password = args[0]; password = args[0];
} }
if (args.length >= 2) if (args.length >= 2) {
{
candidate = args[1]; candidate = args[1];
} }
if (candidate == null) if (candidate == null) {
{
// Creation mode // Creation mode
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[8]; byte[] salt = new byte[8];
@ -379,15 +343,12 @@ public class PBKDF2Engine implements PBKDF2
p.setDerivedKey(e.deriveKey(password)); p.setDerivedKey(e.deriveKey(password));
candidate = formatter.toString(p); candidate = formatter.toString(p);
System.out.println(candidate); System.out.println(candidate);
} } else {
else
{
// Verification mode // Verification mode
PBKDF2Parameters p = new PBKDF2Parameters(); PBKDF2Parameters p = new PBKDF2Parameters();
p.setHashAlgorithm("HmacSHA1"); p.setHashAlgorithm("HmacSHA1");
p.setHashCharset("ISO-8859-1"); p.setHashCharset("ISO-8859-1");
if (formatter.fromString(p, candidate)) if (formatter.fromString(p, candidate)) {
{
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Candidate data does not have correct format (\"" "Candidate data does not have correct format (\""
+ candidate + "\")"); + candidate + "\")");

View File

@ -24,14 +24,14 @@ package fr.xephi.authme.security.pbkdf2;
* </p> * </p>
* <p> * <p>
* For Details, see <a * For Details, see <a
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>. * href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
* >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* </p> * </p>
* *
* @author Matthias G&auml;rtner * @author Matthias G&auml;rtner
* @version 1.0 * @version 1.0
*/ */
public interface PBKDF2Formatter public interface PBKDF2Formatter {
{
/** /**
* Convert parameters to String. * Convert parameters to String.
* *

View File

@ -24,24 +24,21 @@ package fr.xephi.authme.security.pbkdf2;
* </p> * </p>
* <p> * <p>
* For Details, see <a * For Details, see <a
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>. * href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
* >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* </p> * </p>
* *
* @author Matthias G&auml;rtner * @author Matthias G&auml;rtner
* @version 1.0 * @version 1.0
*/ */
public class PBKDF2HexFormatter implements PBKDF2Formatter public class PBKDF2HexFormatter implements PBKDF2Formatter {
{ public boolean fromString(PBKDF2Parameters p, String s) {
public boolean fromString(PBKDF2Parameters p, String s) if (p == null || s == null) {
{
if (p == null || s == null)
{
return true; return true;
} }
String[] p123 = s.split(":"); String[] p123 = s.split(":");
if (p123 == null || p123.length != 3) if (p123 == null || p123.length != 3) {
{
return true; return true;
} }
@ -55,8 +52,7 @@ public class PBKDF2HexFormatter implements PBKDF2Formatter
return false; return false;
} }
public String toString(PBKDF2Parameters p) public String toString(PBKDF2Parameters p) {
{
String s = BinTools.bin2hex(p.getSalt()) + ":" String s = BinTools.bin2hex(p.getSalt()) + ":"
+ String.valueOf(p.getIterationCount()) + ":" + String.valueOf(p.getIterationCount()) + ":"
+ BinTools.bin2hex(p.getDerivedKey()); + BinTools.bin2hex(p.getDerivedKey());

View File

@ -29,14 +29,14 @@ package fr.xephi.authme.security.pbkdf2;
* </p> * </p>
* <p> * <p>
* For Details, see <a * For Details, see <a
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>. * href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
* >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* </p> * </p>
* *
* @author Matthias G&auml;rtner * @author Matthias G&auml;rtner
* @version 1.0 * @version 1.0
*/ */
public class PBKDF2Parameters public class PBKDF2Parameters {
{
protected byte[] salt; protected byte[] salt;
protected int iterationCount; protected int iterationCount;
@ -56,8 +56,7 @@ public class PBKDF2Parameters
* character set and 1000 for iteration count. * character set and 1000 for iteration count.
* *
*/ */
public PBKDF2Parameters() public PBKDF2Parameters() {
{
this.hashAlgorithm = null; this.hashAlgorithm = null;
this.hashCharset = "UTF-8"; this.hashCharset = "UTF-8";
this.salt = null; this.salt = null;
@ -73,14 +72,12 @@ public class PBKDF2Parameters
* @param hashCharset * @param hashCharset
* for example UTF-8 * for example UTF-8
* @param salt * @param salt
* Salt as byte array, may be <code>null</code> (not * Salt as byte array, may be <code>null</code> (not recommended)
* recommended)
* @param iterationCount * @param iterationCount
* Number of iterations to execute. Recommended value 1000. * Number of iterations to execute. Recommended value 1000.
*/ */
public PBKDF2Parameters(String hashAlgorithm, String hashCharset, public PBKDF2Parameters(String hashAlgorithm, String hashCharset,
byte[] salt, int iterationCount) byte[] salt, int iterationCount) {
{
this.hashAlgorithm = hashAlgorithm; this.hashAlgorithm = hashAlgorithm;
this.hashCharset = hashCharset; this.hashCharset = hashCharset;
this.salt = salt; this.salt = salt;
@ -96,16 +93,14 @@ public class PBKDF2Parameters
* @param hashCharset * @param hashCharset
* for example UTF-8 * for example UTF-8
* @param salt * @param salt
* Salt as byte array, may be <code>null</code> (not * Salt as byte array, may be <code>null</code> (not recommended)
* recommended)
* @param iterationCount * @param iterationCount
* Number of iterations to execute. Recommended value 1000. * Number of iterations to execute. Recommended value 1000.
* @param derivedKey * @param derivedKey
* Convenience data holder, not used during computation. * Convenience data holder, not used during computation.
*/ */
public PBKDF2Parameters(String hashAlgorithm, String hashCharset, public PBKDF2Parameters(String hashAlgorithm, String hashCharset,
byte[] salt, int iterationCount, byte[] derivedKey) byte[] salt, int iterationCount, byte[] derivedKey) {
{
this.hashAlgorithm = hashAlgorithm; this.hashAlgorithm = hashAlgorithm;
this.hashCharset = hashCharset; this.hashCharset = hashCharset;
this.salt = salt; this.salt = salt;
@ -113,53 +108,43 @@ public class PBKDF2Parameters
this.derivedKey = derivedKey; this.derivedKey = derivedKey;
} }
public int getIterationCount() public int getIterationCount() {
{
return iterationCount; return iterationCount;
} }
public void setIterationCount(int iterationCount) public void setIterationCount(int iterationCount) {
{
this.iterationCount = iterationCount; this.iterationCount = iterationCount;
} }
public byte[] getSalt() public byte[] getSalt() {
{
return salt; return salt;
} }
public void setSalt(byte[] salt) public void setSalt(byte[] salt) {
{
this.salt = salt; this.salt = salt;
} }
public byte[] getDerivedKey() public byte[] getDerivedKey() {
{
return derivedKey; return derivedKey;
} }
public void setDerivedKey(byte[] derivedKey) public void setDerivedKey(byte[] derivedKey) {
{
this.derivedKey = derivedKey; this.derivedKey = derivedKey;
} }
public String getHashAlgorithm() public String getHashAlgorithm() {
{
return hashAlgorithm; return hashAlgorithm;
} }
public void setHashAlgorithm(String hashAlgorithm) public void setHashAlgorithm(String hashAlgorithm) {
{
this.hashAlgorithm = hashAlgorithm; this.hashAlgorithm = hashAlgorithm;
} }
public String getHashCharset() public String getHashCharset() {
{
return hashCharset; return hashCharset;
} }
public void setHashCharset(String hashCharset) public void setHashCharset(String hashCharset) {
{
this.hashCharset = hashCharset; this.hashCharset = hashCharset;
} }
} }

View File

@ -24,14 +24,14 @@ package fr.xephi.authme.security.pbkdf2;
* </p> * </p>
* <p> * <p>
* For Details, see <a * For Details, see <a
* href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>. * href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
* >http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</a>.
* </p> * </p>
* *
* @author Matthias G&auml;rtner * @author Matthias G&auml;rtner
* @version 1.0 * @version 1.0
*/ */
public interface PRF public interface PRF {
{
/** /**
* Initialize this instance with the user-supplied password. * Initialize this instance with the user-supplied password.
* *

View File

@ -22,31 +22,35 @@ public class CustomConfiguration extends YamlConfiguration{
private File configFile; private File configFile;
public CustomConfiguration(File file) public CustomConfiguration(File file) {
{
this.configFile = file; this.configFile = file;
load(); load();
} }
public void load() public void load() {
{
try { try {
super.load(configFile); super.load(configFile);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not find " + configFile.getName() + ", creating new one..."); Logger.getLogger(JavaPlugin.class.getName()).log(
Level.SEVERE,
"Could not find " + configFile.getName()
+ ", creating new one...");
reLoad(); reLoad();
} catch (IOException e) { } catch (IOException e) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not load " + configFile.getName(), e); Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE,
"Could not load " + configFile.getName(), e);
} catch (InvalidConfigurationException e) { } catch (InvalidConfigurationException e) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, configFile.getName() + " is no valid configuration file", e); Logger.getLogger(JavaPlugin.class.getName())
.log(Level.SEVERE,
configFile.getName()
+ " is no valid configuration file", e);
} }
} }
public boolean reLoad() { public boolean reLoad() {
boolean out = true; boolean out = true;
if (!configFile.exists()) if (!configFile.exists()) {
{
out = loadRessource(configFile); out = loadRessource(configFile);
} }
if (out) load(); if (out) load();
@ -57,7 +61,8 @@ public class CustomConfiguration extends YamlConfiguration{
try { try {
super.save(configFile); super.save(configFile);
} catch (IOException ex) { } catch (IOException ex) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not save config to " + configFile.getName(), ex); Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE,
"Could not save config to " + configFile.getName(), ex);
} }
} }
@ -65,11 +70,15 @@ public class CustomConfiguration extends YamlConfiguration{
boolean out = true; boolean out = true;
if (!file.exists()) { if (!file.exists()) {
try { try {
InputStream fis = getClass().getResourceAsStream("/" + file.getName()); InputStream fis = getClass().getResourceAsStream(
BufferedReader reader = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8").newDecoder())); "/" + file.getName());
BufferedReader reader = new BufferedReader(
new InputStreamReader(fis, Charset.forName("UTF-8")
.newDecoder()));
String str; String str;
Writer writer = new BufferedWriter(new OutputStreamWriter( Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), Charset.forName("UTF-8").newEncoder())); new FileOutputStream(file), Charset.forName("UTF-8")
.newEncoder()));
while ((str = reader.readLine()) != null) { while ((str = reader.readLine()) != null) {
writer.append(str).append("\r\n"); writer.append(str).append("\r\n");
} }
@ -78,32 +87,20 @@ public class CustomConfiguration extends YamlConfiguration{
reader.close(); reader.close();
fis.close(); fis.close();
} catch (Exception e) { } catch (Exception e) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Failed to load config from JAR"); Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE,
"Failed to load config from JAR");
out = false; out = false;
} }
/*FileOutputStream fos = null; /*
try { * FileOutputStream fos = null; try { fos = new
fos = new FileOutputStream(file); * FileOutputStream(file); byte[] buf = new byte[1024]; int i = 0;
byte[] buf = new byte[1024]; * while ((i = fis.read(buf)) != -1) { fos.write(buf, 0, i); } }
int i = 0; * catch (Exception e) {
while ((i = fis.read(buf)) != -1) { * Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE,
fos.write(buf, 0, i); * "Failed to load config from JAR"); out = false; } finally { try {
} * if (fis != null) { fis.close(); } if (fos != null) { fos.close();
} catch (Exception e) { * } } catch (Exception e) { } } }
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Failed to load config from JAR"); */
out = false;
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
}
}
}*/
} }
return out; return out;
} }

View File

@ -22,7 +22,8 @@ public class Messages extends CustomConfiguration {
/** /**
* Loads a file from the plugin jar and sets as default * Loads a file from the plugin jar and sets as default
* *
* @param filename The filename to open * @param filename
* The filename to open
*/ */
public final void loadDefaults(File file) { public final void loadDefaults(File file) {
InputStream stream = AuthMe.getInstance().getResource(file.getName()); InputStream stream = AuthMe.getInstance().getResource(file.getName());
@ -70,7 +71,9 @@ public class Messages extends CustomConfiguration {
String loc = (String) this.get(msg); String loc = (String) this.get(msg);
if (loc == null) { if (loc == null) {
loc = "Error with Translation files; Please contact the admin for verify or update translation"; loc = "Error with Translation files; Please contact the admin for verify or update translation";
ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml !"); ConsoleLogger.showError("Error with the " + msg
+ " translation, verify in your " + Settings.MESSAGE_FILE
+ "_" + Settings.messagesLanguage + ".yml !");
} }
for (String l : loc.split("&n")) { for (String l : loc.split("&n")) {
sender.sendMessage(l.replace("&", "\u00a7")); sender.sendMessage(l.replace("&", "\u00a7"));
@ -82,18 +85,24 @@ public class Messages extends CustomConfiguration {
String[] loc = new String[i]; String[] loc = new String[i];
int a; int a;
for (a = 0; a < i; a++) { for (a = 0; a < i; a++) {
loc[a] = ((String) this.get(msg)).split("&n")[a].replace("&", "\u00a7"); loc[a] = ((String) this.get(msg)).split("&n")[a].replace("&",
"\u00a7");
} }
if (loc == null || loc.length == 0) { if (loc == null || loc.length == 0) {
loc[0] = "Error with " + msg + " translation; Please contact the admin for verify or update translation files"; loc[0] = "Error with "
ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml !"); + msg
+ " translation; Please contact the admin for verify or update translation files";
ConsoleLogger.showError("Error with the " + msg
+ " translation, verify in your " + Settings.MESSAGE_FILE
+ "_" + Settings.messagesLanguage + ".yml !");
} }
return loc; return loc;
} }
public static Messages getInstance() { public static Messages getInstance() {
if (singleton == null) { if (singleton == null) {
singleton = new Messages(new File(Settings.MESSAGE_FILE+"_"+Settings.messagesLanguage+".yml")); singleton = new Messages(new File(Settings.MESSAGE_FILE + "_"
+ Settings.messagesLanguage + ".yml"));
} }
return singleton; return singleton;
} }

File diff suppressed because it is too large Load Diff

View File

@ -85,8 +85,13 @@ public class Spawn extends CustomConfiguration {
public Location getSpawn() { public Location getSpawn() {
try { try {
if (this.getString("spawn.world").isEmpty() || this.getString("spawn.world") == "") return null; if (this.getString("spawn.world").isEmpty()
Location location = new Location(Bukkit.getWorld(this.getString("spawn.world")), this.getDouble("spawn.x"), this.getDouble("spawn.y"), this.getDouble("spawn.z"), Float.parseFloat(this.getString("spawn.yaw")), Float.parseFloat(this.getString("spawn.pitch"))); || this.getString("spawn.world") == "") return null;
Location location = new Location(Bukkit.getWorld(this
.getString("spawn.world")), this.getDouble("spawn.x"),
this.getDouble("spawn.y"), this.getDouble("spawn.z"),
Float.parseFloat(this.getString("spawn.yaw")),
Float.parseFloat(this.getString("spawn.pitch")));
return location; return location;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return null; return null;
@ -97,8 +102,15 @@ public class Spawn extends CustomConfiguration {
public Location getFirstSpawn() { public Location getFirstSpawn() {
try { try {
if (this.getString("firstspawn.world").isEmpty() || this.getString("firstspawn.world") == "") return null; if (this.getString("firstspawn.world").isEmpty()
Location location = new Location(Bukkit.getWorld(this.getString("firstspawn.world")), this.getDouble("firstspawn.x"), this.getDouble("firstspawn.y"), this.getDouble("firstspawn.z"), Float.parseFloat(this.getString("firstspawn.yaw")), Float.parseFloat(this.getString("firstspawn.pitch"))); || this.getString("firstspawn.world") == "") return null;
Location location = new Location(Bukkit.getWorld(this
.getString("firstspawn.world")),
this.getDouble("firstspawn.x"),
this.getDouble("firstspawn.y"),
this.getDouble("firstspawn.z"), Float.parseFloat(this
.getString("firstspawn.yaw")),
Float.parseFloat(this.getString("firstspawn.pitch")));
return location; return location;
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
return null; return null;

Some files were not shown because too many files have changed in this diff Show More