Make use of the awesome Java 8 features

This commit is contained in:
games647
2016-09-16 17:40:42 +02:00
parent 31d6b67381
commit 17c2099bf1
15 changed files with 85 additions and 114 deletions

View File

@ -10,6 +10,7 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
import java.util.stream.Stream;
import javax.crypto.BadPaddingException; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher; import javax.crypto.Cipher;
@ -48,9 +49,7 @@ public class EncryptionUtil {
private static byte[] digestOperation(String algo, byte[]... content) { private static byte[] digestOperation(String algo, byte[]... content) {
try { try {
MessageDigest messagedigest = MessageDigest.getInstance(algo); MessageDigest messagedigest = MessageDigest.getInstance(algo);
for (byte[] data : content) { Stream.of(content).forEach(messagedigest::update);
messagedigest.update(data);
}
return messagedigest.digest(); return messagedigest.digest();
} catch (NoSuchAlgorithmException nosuchalgorithmexception) { } catch (NoSuchAlgorithmException nosuchalgorithmexception) {

View File

@ -37,9 +37,10 @@ public class CrackedCommand implements CommandExecutor {
} }
} else { } else {
//todo: load async if //todo: load async if
final PlayerProfile profile = plugin.getCore().getStorage().loadProfile(sender.getName()); PlayerProfile profile = plugin.getCore().getStorage().loadProfile(sender.getName());
if (profile.isPremium()) { if (profile.isPremium()) {
sender.sendMessage(plugin.getCore().getMessage("remove-premium")); sender.sendMessage(plugin.getCore().getMessage("remove-premium"));
profile.setPremium(false); profile.setPremium(false);
profile.setUuid(null); profile.setUuid(null);
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
@ -72,7 +73,7 @@ public class CrackedCommand implements CommandExecutor {
} }
} else { } else {
//todo: load async //todo: load async
final PlayerProfile profile = plugin.getCore().getStorage().loadProfile(args[0]); PlayerProfile profile = plugin.getCore().getStorage().loadProfile(args[0]);
if (profile == null) { if (profile == null) {
sender.sendMessage("Error occured"); sender.sendMessage("Error occured");
return; return;

View File

@ -53,7 +53,7 @@ public class PremiumCommand implements CommandExecutor {
plugin.getCore().getPendingConfirms().remove(id); plugin.getCore().getPendingConfirms().remove(id);
//todo: load async //todo: load async
final PlayerProfile profile = plugin.getCore().getStorage().loadProfile(sender.getName()); PlayerProfile profile = plugin.getCore().getStorage().loadProfile(sender.getName());
if (profile.isPremium()) { if (profile.isPremium()) {
sender.sendMessage(plugin.getCore().getMessage("already-exists")); sender.sendMessage(plugin.getCore().getMessage("already-exists"));
} else { } else {
@ -89,7 +89,7 @@ public class PremiumCommand implements CommandExecutor {
} }
} else { } else {
//todo: load async //todo: load async
final PlayerProfile profile = plugin.getCore().getStorage().loadProfile(args[0]); PlayerProfile profile = plugin.getCore().getStorage().loadProfile(args[0]);
if (profile == null) { if (profile == null) {
sender.sendMessage(plugin.getCore().getMessage("player-unknown")); sender.sendMessage(plugin.getCore().getMessage("player-unknown"));
return; return;

View File

@ -29,10 +29,10 @@ public class CrazyLoginHook implements AuthPlugin<Player> {
private final PlayerListener playerListener = getListener(); private final PlayerListener playerListener = getListener();
@Override @Override
public boolean forceLogin(final Player player) { public boolean forceLogin(Player player) {
//not thread-safe operation //not thread-safe operation
Future<LoginPlayerData> future = Bukkit.getScheduler().callSyncMethod(crazyLoginPlugin, () -> { Future<LoginPlayerData> future = Bukkit.getScheduler().callSyncMethod(crazyLoginPlugin, () -> {
LoginPlayerData playerData = crazyLoginPlugin.getPlayerData(player.getName()); LoginPlayerData playerData = crazyLoginPlugin.getPlayerData(player);
if (playerData != null) { if (playerData != null) {
//mark the account as logged in //mark the account as logged in
playerData.setLoggedIn(true); playerData.setLoggedIn(true);

View File

@ -24,11 +24,10 @@ public class RoyalAuthHook implements AuthPlugin<Player> {
private final RoyalAuth royalAuthPlugin = (RoyalAuth) Bukkit.getPluginManager().getPlugin("RoyalAuth"); private final RoyalAuth royalAuthPlugin = (RoyalAuth) Bukkit.getPluginManager().getPlugin("RoyalAuth");
@Override @Override
public boolean forceLogin(final Player player) { public boolean forceLogin(Player player) {
//not thread-safe AuthPlayer authPlayer = AuthPlayer.getAuthPlayer(player);
Future<Boolean> future = Bukkit.getScheduler().callSyncMethod(royalAuthPlugin, () -> {
AuthPlayer authPlayer = AuthPlayer.getAuthPlayer(player);
Future<Boolean> future = Bukkit.getScheduler().callSyncMethod(royalAuthPlugin, () -> {
//https://github.com/RoyalDev/RoyalAuth/blob/master/src/main/java/org/royaldev/royalauth/commands/CmdLogin.java#L62 //https://github.com/RoyalDev/RoyalAuth/blob/master/src/main/java/org/royaldev/royalauth/commands/CmdLogin.java#L62
//not thread-safe //not thread-safe
authPlayer.login(); authPlayer.login();
@ -56,11 +55,8 @@ public class RoyalAuthHook implements AuthPlugin<Player> {
AuthPlayer authPlayer = AuthPlayer.getAuthPlayer(player); AuthPlayer authPlayer = AuthPlayer.getAuthPlayer(player);
boolean registerSuccess = authPlayer.setPassword(password, Config.passwordHashType); boolean registerSuccess = authPlayer.setPassword(password, Config.passwordHashType);
if (registerSuccess) {
//login in the player after registration
return forceLogin(player);
}
return false; //login in the player after registration
return registerSuccess && forceLogin(player);
} }
} }

View File

@ -25,7 +25,7 @@ public class xAuthHook implements AuthPlugin<Player> {
protected final xAuth xAuthPlugin = xAuth.getPlugin(); protected final xAuth xAuthPlugin = xAuth.getPlugin();
@Override @Override
public boolean forceLogin(final Player player) { public boolean forceLogin(Player player) {
//not thread-safe //not thread-safe
Future<Boolean> future = Bukkit.getScheduler().callSyncMethod(xAuthPlugin, () -> { Future<Boolean> future = Bukkit.getScheduler().callSyncMethod(xAuthPlugin, () -> {
xAuthPlayer xAuthPlayer = xAuthPlugin.getPlayerManager().getPlayer(player); xAuthPlayer xAuthPlayer = xAuthPlugin.getPlayerManager().getPlayer(player);
@ -56,7 +56,7 @@ public class xAuthHook implements AuthPlugin<Player> {
} }
@Override @Override
public boolean forceRegister(final Player player, final String password) { public boolean forceRegister(Player player, final String password) {
//not thread-safe //not thread-safe
Future<Boolean> future = Bukkit.getScheduler().callSyncMethod(xAuthPlugin, () -> { Future<Boolean> future = Bukkit.getScheduler().callSyncMethod(xAuthPlugin, () -> {
xAuthPlayer xAuthPlayer = xAuthPlugin.getPlayerManager().getPlayer(player); xAuthPlayer xAuthPlayer = xAuthPlugin.getPlayerManager().getPlayer(player);
@ -73,13 +73,8 @@ public class xAuthHook implements AuthPlugin<Player> {
}); });
try { try {
boolean success = future.get(); //login in the player after registration
if (success) { return future.get() && forceLogin(player);
//login in the player after registration
return forceLogin(player);
}
return false;
} catch (InterruptedException | ExecutionException ex) { } catch (InterruptedException | ExecutionException ex) {
xAuthPlugin.getLogger().log(Level.SEVERE, "Failed to forceLogin", ex); xAuthPlugin.getLogger().log(Level.SEVERE, "Failed to forceLogin", ex);
return false; return false;

View File

@ -5,7 +5,6 @@ import com.github.games647.fastlogin.bukkit.FastLoginBukkit;
import com.github.games647.fastlogin.bukkit.tasks.ForceLoginTask; import com.github.games647.fastlogin.bukkit.tasks.ForceLoginTask;
import com.github.games647.fastlogin.core.hooks.AuthPlugin; import com.github.games647.fastlogin.core.hooks.AuthPlugin;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.google.common.collect.Sets;
import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import com.google.common.io.Files; import com.google.common.io.Files;
@ -16,6 +15,7 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -42,7 +42,7 @@ public class BungeeCordListener implements PluginMessageListener {
} }
@Override @Override
public void onPluginMessageReceived(String channel, final Player player, byte[] message) { public void onPluginMessageReceived(String channel, Player player, byte[] message) {
if (!channel.equals(plugin.getName())) { if (!channel.equals(plugin.getName())) {
return; return;
} }
@ -69,7 +69,7 @@ public class BungeeCordListener implements PluginMessageListener {
//fail if BungeeCord support is disabled (id = null) //fail if BungeeCord support is disabled (id = null)
if (proxyIds.contains(sourceId)) { if (proxyIds.contains(sourceId)) {
final String id = '/' + checkedPlayer.getAddress().getAddress().getHostAddress() + ':' String id = '/' + checkedPlayer.getAddress().getAddress().getHostAddress() + ':'
+ checkedPlayer.getAddress().getPort(); + checkedPlayer.getAddress().getPort();
if ("AUTO_LOGIN".equalsIgnoreCase(subchannel)) { if ("AUTO_LOGIN".equalsIgnoreCase(subchannel)) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, true); BukkitLoginSession playerSession = new BukkitLoginSession(playerName, true);
@ -105,19 +105,8 @@ public class BungeeCordListener implements PluginMessageListener {
whitelistFile.createNewFile(); whitelistFile.createNewFile();
} }
Set<UUID> ids = Sets.newHashSet();
List<String> lines = Files.readLines(whitelistFile, Charsets.UTF_8); List<String> lines = Files.readLines(whitelistFile, Charsets.UTF_8);
for (String line : lines) { return lines.stream().map(String::trim).map(UUID::fromString).collect(Collectors.toSet());
if (line == null || line.trim().isEmpty()) {
continue;
}
UUID uuid = UUID.fromString(line.trim());
ids.add(uuid);
}
return ids;
} catch (IOException ex) { } catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Failed to create file for Proxy whitelist", ex); plugin.getLogger().log(Level.SEVERE, "Failed to create file for Proxy whitelist", ex);
} catch (Exception ex) { } catch (Exception ex) {

View File

@ -42,17 +42,18 @@ public class LoginSkinApplyListener implements Listener {
Collection<BukkitLoginSession> sessions = plugin.getSessions().values(); Collection<BukkitLoginSession> sessions = plugin.getSessions().values();
for (BukkitLoginSession session : sessions) { for (BukkitLoginSession session : sessions) {
if (session.getUsername().equals(player.getName())) { if (session.getUsername().equals(player.getName())) {
applySkin(player, session); String signature = session.getSkinSignature();
String skinData = session.getEncodedSkinData();
applySkin(player, skinData, signature);
break; break;
} }
} }
} }
} }
private void applySkin(Player player, BukkitLoginSession session) { private void applySkin(Player player, String skinData, String signature) {
WrappedGameProfile gameProfile = WrappedGameProfile.fromPlayer(player); WrappedGameProfile gameProfile = WrappedGameProfile.fromPlayer(player);
String skinData = session.getEncodedSkinData();
String signature = session.getSkinSignature();
if (skinData != null && signature != null) { if (skinData != null && signature != null) {
WrappedSignedProperty skin = WrappedSignedProperty.fromValues("textures", skinData, signature); WrappedSignedProperty skin = WrappedSignedProperty.fromValues("textures", skinData, signature);
try { try {

View File

@ -56,6 +56,11 @@ public class VerifyResponseTask implements Runnable {
verifyResponse(session); verifyResponse(session);
} }
} finally { } finally {
//this is a fake packet; it shouldn't be send to the server
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
ProtocolLibrary.getProtocolManager().getAsynchronousManager().signalPacketTransmission(packetEvent); ProtocolLibrary.getProtocolManager().getAsynchronousManager().signalPacketTransmission(packetEvent);
} }
} }
@ -90,11 +95,6 @@ public class VerifyResponseTask implements Runnable {
, "Player {0} ({1}) tried to log in with an invalid session ServerId: {2}" , "Player {0} ({1}) tried to log in with an invalid session ServerId: {2}"
, session.getUsername(), fromPlayer.getAddress(), serverId); , session.getUsername(), fromPlayer.getAddress(), serverId);
} }
//this is a fake packet; it shouldn't be send to the server
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
} }
private void setPremiumUUID(UUID premiumUUID) { private void setPremiumUUID(UUID premiumUUID) {
@ -169,10 +169,6 @@ public class VerifyResponseTask implements Runnable {
} }
kickPlayer(packetEvent.getPlayer(), kickReason); kickPlayer(packetEvent.getPlayer(), kickReason);
//cancel the event in order to prevent the server receiving an invalid packet
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
} }
private void kickPlayer(Player player, String reason) { private void kickPlayer(Player player, String reason) {

View File

@ -43,6 +43,7 @@ public class DelayedAuthHook implements Runnable {
List<Class<? extends AuthPlugin<Player>>> supportedHooks = Lists.newArrayList(AuthMeHook.class List<Class<? extends AuthPlugin<Player>>> supportedHooks = Lists.newArrayList(AuthMeHook.class
, CrazyLoginHook.class, LogItHook.class, LoginSecurityHook.class, UltraAuthHook.class , CrazyLoginHook.class, LogItHook.class, LoginSecurityHook.class, UltraAuthHook.class
, xAuthHook.class); , xAuthHook.class);
for (Class<? extends AuthPlugin<Player>> clazz : supportedHooks) { for (Class<? extends AuthPlugin<Player>> clazz : supportedHooks) {
String pluginName = clazz.getSimpleName().replace("Hook", ""); String pluginName = clazz.getSimpleName().replace("Hook", "");
//uses only member classes which uses AuthPlugin interface (skip interfaces) //uses only member classes which uses AuthPlugin interface (skip interfaces)

View File

@ -1,18 +1,17 @@
package com.github.games647.fastlogin.bungee; package com.github.games647.fastlogin.bungee;
import com.github.games647.fastlogin.core.shared.FastLoginCore; import com.github.games647.fastlogin.core.shared.FastLoginCore;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadFactory;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.stream.Collectors;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
@ -24,13 +23,7 @@ import net.md_5.bungee.config.YamlConfiguration;
public class BungeeCore extends FastLoginCore<ProxiedPlayer> { public class BungeeCore extends FastLoginCore<ProxiedPlayer> {
private static Map<String, Object> generateConfigMap(Configuration config) { private static Map<String, Object> generateConfigMap(Configuration config) {
Map<String, Object> configMap = Maps.newHashMap(); return config.getKeys().stream().collect(Collectors.toMap(key -> key, key -> config.get(key)));
Collection<String> keys = config.getKeys();
keys.forEach(key -> {
configMap.put(key, config.get(key));
});
return configMap;
} }
private final FastLoginBungee plugin; private final FastLoginBungee plugin;

View File

@ -1,6 +1,5 @@
package com.github.games647.fastlogin.bungee; package com.github.games647.fastlogin.bungee;
import com.github.games647.fastlogin.bungee.FastLoginBungee;
import com.github.games647.fastlogin.core.AuthStorage; import com.github.games647.fastlogin.core.AuthStorage;
import com.github.games647.fastlogin.core.importer.ImportPlugin; import com.github.games647.fastlogin.core.importer.ImportPlugin;

View File

@ -38,52 +38,56 @@ public class PluginMessageListener implements Listener {
//check if the message is sent from the server //check if the message is sent from the server
if (Server.class.isAssignableFrom(pluginMessageEvent.getSender().getClass())) { if (Server.class.isAssignableFrom(pluginMessageEvent.getSender().getClass())) {
readMessage(pluginMessageEvent); //so that we can safely process this in the background
byte[] data = Arrays.copyOf(pluginMessageEvent.getData(), pluginMessageEvent.getData().length);
ProxiedPlayer forPlayer = (ProxiedPlayer) pluginMessageEvent.getReceiver();
ProxyServer.getInstance().getScheduler().runAsync(plugin, () -> {
readMessage(forPlayer, data);
});
} }
} }
private void readMessage(PluginMessageEvent pluginMessageEvent) { private void readMessage(ProxiedPlayer forPlayer, byte[] data) {
//so that we can safely process this in the background ByteArrayDataInput dataInput = ByteStreams.newDataInput(data);
byte[] data = Arrays.copyOf(pluginMessageEvent.getData(), pluginMessageEvent.getData().length); String subchannel = dataInput.readUTF();
ProxiedPlayer forPlayer = (ProxiedPlayer) pluginMessageEvent.getReceiver(); if ("ON".equals(subchannel)) {
String playerName = dataInput.readUTF();
ProxyServer.getInstance().getScheduler().runAsync(plugin, () -> { if (playerName.equals(forPlayer.getName()) && plugin.getConfig().getBoolean("premium-warning")
ByteArrayDataInput dataInput = ByteStreams.newDataInput(data); && !plugin.getCore().getPendingConfirms().contains(forPlayer.getUniqueId())) {
String subchannel = dataInput.readUTF(); String message = plugin.getCore().getMessage("premium-warning");
if ("ON".equals(subchannel)) { forPlayer.sendMessage(TextComponent.fromLegacyText(message));
String playerName = dataInput.readUTF(); plugin.getCore().getPendingConfirms().add(forPlayer.getUniqueId());
return;
if (playerName.equals(forPlayer.getName()) && plugin.getConfig().getBoolean("premium-warning")
&& !plugin.getCore().getPendingConfirms().contains(forPlayer.getUniqueId())) {
String message = plugin.getCore().getMessage("premium-warning");
forPlayer.sendMessage(TextComponent.fromLegacyText(message));
plugin.getCore().getPendingConfirms().add(forPlayer.getUniqueId());
return;
}
plugin.getCore().getPendingConfirms().remove(forPlayer.getUniqueId());
AsyncToggleMessage task = new AsyncToggleMessage(plugin, forPlayer, playerName, true);
ProxyServer.getInstance().getScheduler().runAsync(plugin, task);
} else if ("OFF".equals(subchannel)) {
String playerName = dataInput.readUTF();
AsyncToggleMessage task = new AsyncToggleMessage(plugin, forPlayer, playerName, false);
ProxyServer.getInstance().getScheduler().runAsync(plugin, task);
} else if ("SUCCESS".equals(subchannel)) {
if (forPlayer.getPendingConnection().isOnlineMode()) {
//bukkit module successfully received and force logged in the user
//update only on success to prevent corrupt data
BungeeLoginSession loginSession = plugin.getSession().get(forPlayer.getPendingConnection());
PlayerProfile playerProfile = loginSession.getProfile();
loginSession.setRegistered(true);
if (!loginSession.isAlreadySaved()) {
playerProfile.setPremium(true);
plugin.getCore().getStorage().save(playerProfile);
loginSession.setAlreadySaved(true);
}
}
} }
});
plugin.getCore().getPendingConfirms().remove(forPlayer.getUniqueId());
AsyncToggleMessage task = new AsyncToggleMessage(plugin, forPlayer, playerName, true);
ProxyServer.getInstance().getScheduler().runAsync(plugin, task);
} else if ("OFF".equals(subchannel)) {
String playerName = dataInput.readUTF();
AsyncToggleMessage task = new AsyncToggleMessage(plugin, forPlayer, playerName, false);
ProxyServer.getInstance().getScheduler().runAsync(plugin, task);
} else if ("SUCCESS".equals(subchannel)) {
onSuccessMessage(forPlayer);
}
}
private void onSuccessMessage(ProxiedPlayer forPlayer) {
if (forPlayer.getPendingConnection().isOnlineMode()) {
//bukkit module successfully received and force logged in the user
//update only on success to prevent corrupt data
BungeeLoginSession loginSession = plugin.getSession().get(forPlayer.getPendingConnection());
PlayerProfile playerProfile = loginSession.getProfile();
loginSession.setRegistered(true);
if (!loginSession.isAlreadySaved()) {
playerProfile.setPremium(true);
plugin.getCore().getStorage().save(playerProfile);
loginSession.setAlreadySaved(true);
}
}
} }
} }

View File

@ -42,12 +42,9 @@ public abstract class FastLoginCore<P> {
builder.maximumSize(maxSize); builder.maximumSize(maxSize);
} }
return builder.build(new CacheLoader<K, V>() { return builder.build(CacheLoader.from(() -> {
@Override throw new UnsupportedOperationException();
public V load(K key) throws Exception { }));
throw new UnsupportedOperationException("Not supported yet.");
}
});
} }
public static UUID parseId(String withoutDashes) { public static UUID parseId(String withoutDashes) {

View File

@ -62,7 +62,7 @@ public abstract class MojangApiConnector {
try { try {
InetAddress address = InetAddress.getByName(localAddress); InetAddress address = InetAddress.getByName(localAddress);
if (!address.isAnyLocalAddress()) { if (!address.isAnyLocalAddress()) {
logger.log(Level.WARNING, "Submitted IP-Address is not local", address); logger.log(Level.WARNING, "Submitted IP-Address is not local {0}", address);
continue; continue;
} }