Migrate SLF4J logging (Fixes #177)

This commit is contained in:
games647
2017-09-29 16:54:29 +02:00
parent 1f917f3a8d
commit dce44295d0
20 changed files with 99 additions and 78 deletions

View File

@@ -6,6 +6,8 @@ sudo: false
# This is a java project # This is a java project
language: java language: java
script: mvn compile test script: mvn test -B
jdk: [oraclejdk8] jdk:
- oraclejdk8
- oraclejdk9

View File

@@ -38,7 +38,7 @@ So they don't need to enter passwords. This is also called auto login (auto-logi
### Requirements: ### Requirements:
* Plugin: [ProtocolLib](https://www.spigotmc.org/resources/protocollib.1997/) or [ProtocolSupport](https://www.spigotmc.org/resources/protocolsupport.7201/) * Plugin: [ProtocolLib](https://www.spigotmc.org/resources/protocollib.1997/) or [ProtocolSupport](https://www.spigotmc.org/resources/protocolsupport.7201/)
* Tested [Spigot](https://www.spigotmc.org) 1.8+ (could also work with other versions) * [Spigot](https://www.spigotmc.org) 1.7+
* Java 8+ * Java 8+
* Run Spigot and/or BungeeCord/Waterfall in offline mode (see server.properties or config.yml) * Run Spigot and/or BungeeCord/Waterfall in offline mode (see server.properties or config.yml)
* An auth plugin. Supported plugins * An auth plugin. Supported plugins

View File

@@ -27,6 +27,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.messaging.PluginMessageRecipient; import org.bukkit.plugin.messaging.PluginMessageRecipient;
import org.slf4j.Logger;
/** /**
* This plugin checks if a player has a paid account and if so tries to skip offline mode authentication. * This plugin checks if a player has a paid account and if so tries to skip offline mode authentication.
@@ -35,6 +36,7 @@ public class FastLoginBukkit extends JavaPlugin implements PlatformPlugin<Comman
//provide a immutable key pair to be thread safe | used for encrypting and decrypting traffic //provide a immutable key pair to be thread safe | used for encrypting and decrypting traffic
private final KeyPair keyPair = EncryptionUtil.generateKeyPair(); private final KeyPair keyPair = EncryptionUtil.generateKeyPair();
private final Logger logger = CommonUtil.createLoggerFromJDK(getLogger());
private boolean bungeeCord; private boolean bungeeCord;
private FastLoginCore<Player, CommandSender, FastLoginBukkit> core; private FastLoginCore<Player, CommandSender, FastLoginBukkit> core;
@@ -52,12 +54,12 @@ public class FastLoginBukkit extends JavaPlugin implements PlatformPlugin<Comman
} catch (ClassNotFoundException notFoundEx) { } catch (ClassNotFoundException notFoundEx) {
//ignore server has no bungee support //ignore server has no bungee support
} catch (Exception ex) { } catch (Exception ex) {
getLogger().log(Level.WARNING, "Cannot check bungeecord support. You use a non-spigot build", ex); logger.warn("Cannot check bungeecord support. You use a non-spigot build", ex);
} }
if (getServer().getOnlineMode()) { if (getServer().getOnlineMode()) {
//we need to require offline to prevent a loginSession request for a offline player //we need to require offline to prevent a loginSession request for a offline player
getLogger().severe("Server have to be in offline mode"); logger.error("Server have to be in offline mode");
setEnabled(false); setEnabled(false);
return; return;
} }
@@ -85,8 +87,7 @@ public class FastLoginBukkit extends JavaPlugin implements PlatformPlugin<Comman
getServer().getPluginManager().registerEvents(new LoginSkinApplyListener(this), this); getServer().getPluginManager().registerEvents(new LoginSkinApplyListener(this), this);
} else { } else {
getLogger().warning("Either ProtocolLib or ProtocolSupport have to be installed " logger.warn("Either ProtocolLib or ProtocolSupport have to be installed if you don't use BungeeCord");
+ "if you don't use BungeeCord");
} }
} }
@@ -127,7 +128,7 @@ public class FastLoginBukkit extends JavaPlugin implements PlatformPlugin<Comman
} else { } else {
Player firstPlayer = Iterables.getFirst(getServer().getOnlinePlayers(), null); Player firstPlayer = Iterables.getFirst(getServer().getOnlinePlayers(), null);
if (firstPlayer == null) { if (firstPlayer == null) {
getLogger().info("No player online to send a plugin message to the proxy"); logger.info("No player online to send a plugin message to the proxy");
return; return;
} }
@@ -187,6 +188,11 @@ public class FastLoginBukkit extends JavaPlugin implements PlatformPlugin<Comman
sender.sendPluginMessage(this, getName(), dataOutput.toByteArray()); sender.sendPluginMessage(this, getName(), dataOutput.toByteArray());
} }
@Override
public Logger getLog() {
return logger;
}
@Override @Override
public void sendMessage(CommandSender receiver, String message) { public void sendMessage(CommandSender receiver, String message) {
receiver.sendMessage(message); receiver.sendMessage(message);
@@ -200,6 +206,6 @@ public class FastLoginBukkit extends JavaPlugin implements PlatformPlugin<Comman
@Override @Override
public MojangApiConnector makeApiConnector(List<String> addresses, int requests, List<HostAndPort> proxies) { public MojangApiConnector makeApiConnector(List<String> addresses, int requests, List<HostAndPort> proxies) {
return new MojangApiBukkit(getLogger(), addresses, requests, proxies); return new MojangApiBukkit(getLog(), addresses, requests, proxies);
} }
} }

View File

@@ -13,14 +13,14 @@ import java.net.InetSocketAddress;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger; import org.slf4j.Logger;
public class MojangApiBukkit extends MojangApiConnector { public class MojangApiBukkit extends MojangApiConnector {
//mojang api check to prove a player is logged in minecraft and made a join server request //mojang api check to prove a player is logged in minecraft and made a join server request
private static final String HAS_JOINED_URL = "https://sessionserver.mojang.com/session/minecraft/hasJoined?" + private static final String HAS_JOINED_URL = "https://sessionserver.mojang.com/session/minecraft/hasJoined?" +
"username=%s&serverId=%s"; "username=%s&serverId=%s&ip=%s";
public MojangApiBukkit(Logger logger, Collection<String> localAddresses, int rateLimit public MojangApiBukkit(Logger logger, Collection<String> localAddresses, int rateLimit
, List<HostAndPort> proxies) { , List<HostAndPort> proxies) {
@@ -31,11 +31,9 @@ public class MojangApiBukkit extends MojangApiConnector {
public boolean hasJoinedServer(LoginSession session, String serverId, InetSocketAddress ip) { public boolean hasJoinedServer(LoginSession session, String serverId, InetSocketAddress ip) {
BukkitLoginSession playerSession = (BukkitLoginSession) session; BukkitLoginSession playerSession = (BukkitLoginSession) session;
String url = String.format(HAS_JOINED_URL, playerSession.getUsername(), serverId);
try { try {
if (ip != null) { String encodedIp = URLEncoder.encode(ip.getAddress().getHostAddress(), "UTF-8");
url += "&ip=" + URLEncoder.encode(ip.getAddress().getHostAddress(), "UTF-8"); String url = String.format(HAS_JOINED_URL, playerSession.getUsername(), serverId, encodedIp);
}
HttpURLConnection conn = getConnection(url); HttpURLConnection conn = getConnection(url);
@@ -55,7 +53,7 @@ public class MojangApiBukkit extends MojangApiConnector {
} }
} catch (Exception ex) { } catch (Exception ex) {
//catch not only io-exceptions also parse and NPE on unexpected json format //catch not only io-exceptions also parse and NPE on unexpected json format
logger.log(Level.WARNING, "Failed to verify session", ex); logger.warn("Failed to verify session", ex);
} }
//this connection doesn't need to be closed. So can make use of keep alive in java //this connection doesn't need to be closed. So can make use of keep alive in java

View File

@@ -14,7 +14,6 @@ import java.nio.file.Path;
import java.util.Collections; import java.util.Collections;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -48,20 +47,19 @@ public class BungeeListener implements PluginMessageListener {
ByteArrayDataInput dataInput = ByteStreams.newDataInput(message); ByteArrayDataInput dataInput = ByteStreams.newDataInput(message);
String subChannel = dataInput.readUTF(); String subChannel = dataInput.readUTF();
plugin.getLogger().log(Level.FINEST, "Received plugin message for sub channel {0} from {1}" plugin.getLog().debug("Received plugin message for sub channel {} from {}", subChannel, player);
, new Object[]{subChannel, player});
String playerName = dataInput.readUTF(); String playerName = dataInput.readUTF();
//check if the player is still online or disconnected //check if the player is still online or disconnected
Player checkedPlayer = plugin.getServer().getPlayerExact(playerName); Player checkedPlayer = Bukkit.getPlayerExact(playerName);
//fail if target player is blacklisted because already authenticated or wrong bungeecord id //fail if target player is blacklisted because already authenticated or wrong bungeecord id
if (checkedPlayer != null && !checkedPlayer.hasMetadata(plugin.getName())) { if (checkedPlayer != null && !checkedPlayer.hasMetadata(plugin.getName())) {
//bungeecord UUID //bungeecord UUID
long mostSignificantBits = dataInput.readLong(); long mostSignificantBits = dataInput.readLong();
long leastSignificantBits = dataInput.readLong(); long leastSignificantBits = dataInput.readLong();
UUID sourceId = new UUID(mostSignificantBits, leastSignificantBits); UUID sourceId = new UUID(mostSignificantBits, leastSignificantBits);
plugin.getLogger().log(Level.FINEST, "Received proxy id {0} from {1}", new Object[]{sourceId, player}); plugin.getLog().debug("Received proxy id {} from {}", sourceId, player);
//fail if BungeeCord support is disabled (id = null) //fail if BungeeCord support is disabled (id = null)
if (proxyIds.contains(sourceId)) { if (proxyIds.contains(sourceId)) {
@@ -90,7 +88,7 @@ public class BungeeListener implements PluginMessageListener {
new ForceLoginTask(plugin.getCore(), player).run(); new ForceLoginTask(plugin.getCore(), player).run();
} }
} catch (Exception ex) { } catch (Exception ex) {
plugin.getLogger().log(Level.SEVERE, "Failed to query isRegistered", ex); plugin.getLog().error("Failed to query isRegistered", ex);
} }
}); });
} }
@@ -108,9 +106,9 @@ public class BungeeListener implements PluginMessageListener {
.map(UUID::fromString) .map(UUID::fromString)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
} catch (IOException ex) { } catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Failed to create file for Proxy whitelist", ex); plugin.getLog().error("Failed to create file for Proxy whitelist", ex);
} catch (Exception ex) { } catch (Exception ex) {
plugin.getLogger().log(Level.SEVERE, "Failed to retrieve proxy Id. Disabling BungeeCord support", ex); plugin.getLog().error("Failed to retrieve proxy Id. Disabling BungeeCord support", ex);
} }
return Collections.emptySet(); return Collections.emptySet();

View File

@@ -11,7 +11,6 @@ import com.github.games647.fastlogin.bukkit.FastLoginBukkit;
import com.github.games647.fastlogin.core.mojang.SkinProperties; import com.github.games647.fastlogin.core.mojang.SkinProperties;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@@ -65,7 +64,7 @@ public class LoginSkinApplyListener implements Listener {
try { try {
MethodUtils.invokeMethod(map, "put", new Object[]{"textures", skin.getHandle()}); MethodUtils.invokeMethod(map, "put", new Object[]{"textures", skin.getHandle()});
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
plugin.getLogger().log(Level.SEVERE, "Error setting premium skin", ex); plugin.getLog().error("Error setting premium skin", ex);
} }
} }
} }

View File

@@ -8,7 +8,6 @@ import com.github.games647.fastlogin.core.PlayerProfile;
import com.github.games647.fastlogin.core.shared.JoinManagement; import com.github.games647.fastlogin.core.shared.JoinManagement;
import java.util.Random; import java.util.Random;
import java.util.logging.Level;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -50,7 +49,7 @@ public class NameCheckTask extends JoinManagement<Player, CommandSender, Protoco
try { try {
source.setOnlineMode(); source.setOnlineMode();
} catch (Exception ex) { } catch (Exception ex) {
plugin.getLogger().log(Level.SEVERE, "Cannot send encryption packet. Falling back to cracked login", ex); plugin.getLog().error("Cannot send encryption packet. Falling back to cracked login", ex);
return; return;
} }

View File

@@ -8,7 +8,6 @@ import com.comphenix.protocol.events.PacketEvent;
import com.github.games647.fastlogin.bukkit.FastLoginBukkit; import com.github.games647.fastlogin.bukkit.FastLoginBukkit;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.logging.Level;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -77,7 +76,7 @@ public class ProtocolLibListener extends PacketAdapter {
PacketContainer packet = packetEvent.getPacket(); PacketContainer packet = packetEvent.getPacket();
String username = packet.getGameProfiles().read(0).getName(); String username = packet.getGameProfiles().read(0).getName();
plugin.getLogger().log(Level.FINER, "GameProfile {0} with {1} connecting", new Object[]{sessionKey, username}); plugin.getLog().trace("GameProfile {} with {} connecting", sessionKey, username);
packetEvent.getAsyncMarker().incrementProcessingDelay(); packetEvent.getAsyncMarker().incrementProcessingDelay();
Runnable nameCheckTask = new NameCheckTask(plugin, packetEvent, random, player, username); Runnable nameCheckTask = new NameCheckTask(plugin, packetEvent, random, player, username);

View File

@@ -20,7 +20,6 @@ import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
import java.util.Arrays; import java.util.Arrays;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
@@ -97,7 +96,7 @@ public class VerifyResponseTask implements Runnable {
String username = session.getUsername(); String username = session.getUsername();
if (plugin.getCore().getApiConnector().hasJoinedServer(session, serverId, player.getAddress())) { if (plugin.getCore().getApiConnector().hasJoinedServer(session, serverId, player.getAddress())) {
plugin.getLogger().log(Level.INFO, "GameProfile {0} has a verified premium account", username); plugin.getLog().info("GameProfile {} has a verified premium account", username);
session.setVerified(true); session.setVerified(true);
setPremiumUUID(session.getUuid()); setPremiumUUID(session.getUuid());
@@ -117,7 +116,7 @@ public class VerifyResponseTask implements Runnable {
//https://github.com/bergerkiller/CraftSource/blob/master/net.minecraft.server/NetworkManager.java#L69 //https://github.com/bergerkiller/CraftSource/blob/master/net.minecraft.server/NetworkManager.java#L69
FieldUtils.writeField(networkManager, "spoofedUUID", premiumUUID, true); FieldUtils.writeField(networkManager, "spoofedUUID", premiumUUID, true);
} catch (Exception exc) { } catch (Exception exc) {
plugin.getLogger().log(Level.SEVERE, "Error setting premium uuid", exc); plugin.getLog().error("Error setting premium uuid", exc);
} }
} }
} }
@@ -172,9 +171,9 @@ public class VerifyResponseTask implements Runnable {
private void disconnect(String kickReason, boolean debug, String logMessage, Object... arguments) { private void disconnect(String kickReason, boolean debug, String logMessage, Object... arguments) {
if (debug) { if (debug) {
plugin.getLogger().log(Level.FINE, logMessage, arguments); plugin.getLog().debug(logMessage, arguments);
} else { } else {
plugin.getLogger().log(Level.SEVERE, logMessage, arguments); plugin.getLog().error(logMessage, arguments);
} }
kickPlayer(plugin.getCore().getMessage(kickReason)); kickPlayer(plugin.getCore().getMessage(kickReason));
@@ -192,7 +191,7 @@ public class VerifyResponseTask implements Runnable {
//tell the server that we want to close the connection //tell the server that we want to close the connection
player.kickPlayer("Disconnect"); player.kickPlayer("Disconnect");
} catch (InvocationTargetException ex) { } catch (InvocationTargetException ex) {
plugin.getLogger().log(Level.SEVERE, "Error sending kick packet", ex); plugin.getLog().error("Error sending kick packet", ex);
} }
} }
@@ -210,7 +209,7 @@ public class VerifyResponseTask implements Runnable {
//we don't want to handle our own packets so ignore filters //we don't want to handle our own packets so ignore filters
protocolManager.recieveClientPacket(player, startPacket, false); protocolManager.recieveClientPacket(player, startPacket, false);
} catch (InvocationTargetException | IllegalAccessException ex) { } catch (InvocationTargetException | IllegalAccessException ex) {
plugin.getLogger().log(Level.WARNING, "Failed to fake a new start packet", ex); plugin.getLog().warn("Failed to fake a new start packet", ex);
//cancel the event in order to prevent the server receiving an invalid packet //cancel the event in order to prevent the server receiving an invalid packet
kickPlayer(plugin.getCore().getMessage("error-kick")); kickPlayer(plugin.getCore().getMessage("error-kick"));
} }

View File

@@ -11,7 +11,6 @@ import com.github.games647.fastlogin.core.hooks.AuthPlugin;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -28,9 +27,9 @@ public class DelayedAuthHook implements Runnable {
public void run() { public void run() {
boolean hookFound = plugin.getCore().getAuthPluginHook() != null || registerHooks(); boolean hookFound = plugin.getCore().getAuthPluginHook() != null || registerHooks();
if (plugin.isBungeeCord()) { if (plugin.isBungeeCord()) {
plugin.getLogger().info("BungeeCord setting detected. No auth plugin is required"); plugin.getLog().info("BungeeCord setting detected. No auth plugin is required");
} else if (!hookFound) { } else if (!hookFound) {
plugin.getLogger().warning("No auth plugin were found by this plugin " plugin.getLog().warn("No auth plugin were found by this plugin "
+ "(other plugins could hook into this after the initialization of this plugin)" + "(other plugins could hook into this after the initialization of this plugin)"
+ "and BungeeCord is deactivated. " + "and BungeeCord is deactivated. "
+ "Either one or both of the checks have to pass in order to use this plugin"); + "Either one or both of the checks have to pass in order to use this plugin");
@@ -53,20 +52,20 @@ public class DelayedAuthHook implements Runnable {
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)
if (Bukkit.getServer().getPluginManager().isPluginEnabled(pluginName)) { if (Bukkit.getPluginManager().isPluginEnabled(pluginName)) {
//check only for enabled plugins. A single plugin could be disabled by plugin managers //check only for enabled plugins. A single plugin could be disabled by plugin managers
authPluginHook = clazz.newInstance(); authPluginHook = clazz.newInstance();
plugin.getLogger().log(Level.INFO, "Hooking into auth plugin: {0}", pluginName); plugin.getLog().info("Hooking into auth plugin: {}", pluginName);
break; break;
} }
} }
} catch (InstantiationException | IllegalAccessException ex) { } catch (InstantiationException | IllegalAccessException ex) {
plugin.getLogger().log(Level.SEVERE, "Couldn't load the integration class", ex); plugin.getLog().error("Couldn't load the integration class", ex);
} }
if (authPluginHook == null) { if (authPluginHook == null) {
//run this check for exceptions (errors) and not found plugins //run this check for exceptions (errors) and not found plugins
plugin.getLogger().warning("No support offline Auth plugin found. "); plugin.getLog().warn("No support offline Auth plugin found. ");
return false; return false;
} }

View File

@@ -9,7 +9,6 @@ import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@@ -56,7 +55,7 @@ public class ForceLoginTask extends ForceLoginManagement<Player, CommandSender,
//the player-list isn't thread-safe //the player-list isn't thread-safe
return Bukkit.getScheduler().callSyncMethod(core.getPlugin(), player::isOnline).get(); return Bukkit.getScheduler().callSyncMethod(core.getPlugin(), player::isOnline).get();
} catch (InterruptedException | ExecutionException ex) { } catch (InterruptedException | ExecutionException ex) {
core.getPlugin().getLogger().log(Level.SEVERE, "Failed to perform thread-safe online check", ex); core.getPlugin().getLog().error("Failed to perform thread-safe online check", ex);
return false; return false;
} }
} }

View File

@@ -3,6 +3,7 @@ package com.github.games647.fastlogin.bungee;
import com.github.games647.fastlogin.bungee.hooks.BungeeAuthHook; import com.github.games647.fastlogin.bungee.hooks.BungeeAuthHook;
import com.github.games647.fastlogin.bungee.listener.ConnectListener; import com.github.games647.fastlogin.bungee.listener.ConnectListener;
import com.github.games647.fastlogin.bungee.listener.MessageListener; import com.github.games647.fastlogin.bungee.listener.MessageListener;
import com.github.games647.fastlogin.core.CommonUtil;
import com.github.games647.fastlogin.core.mojang.MojangApiConnector; import com.github.games647.fastlogin.core.mojang.MojangApiConnector;
import com.github.games647.fastlogin.core.shared.FastLoginCore; import com.github.games647.fastlogin.core.shared.FastLoginCore;
import com.github.games647.fastlogin.core.shared.PlatformPlugin; import com.github.games647.fastlogin.core.shared.PlatformPlugin;
@@ -20,12 +21,15 @@ import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.api.scheduler.GroupedThreadFactory; import net.md_5.bungee.api.scheduler.GroupedThreadFactory;
import org.slf4j.Logger;
/** /**
* BungeeCord version of FastLogin. This plugin keeps track on online mode connections. * BungeeCord version of FastLogin. This plugin keeps track on online mode connections.
*/ */
public class FastLoginBungee extends Plugin implements PlatformPlugin<CommandSender> { public class FastLoginBungee extends Plugin implements PlatformPlugin<CommandSender> {
private final ConcurrentMap<PendingConnection, BungeeLoginSession> session = Maps.newConcurrentMap(); private final ConcurrentMap<PendingConnection, BungeeLoginSession> session = Maps.newConcurrentMap();
private final Logger logger = CommonUtil.createLoggerFromJDK(getLogger());
private FastLoginCore<ProxiedPlayer, CommandSender, FastLoginBungee> core; private FastLoginCore<ProxiedPlayer, CommandSender, FastLoginBungee> core;
@@ -66,7 +70,7 @@ public class FastLoginBungee extends Plugin implements PlatformPlugin<CommandSen
Plugin plugin = getProxy().getPluginManager().getPlugin("BungeeAuth"); Plugin plugin = getProxy().getPluginManager().getPlugin("BungeeAuth");
if (plugin != null) { if (plugin != null) {
core.setAuthPluginHook(new BungeeAuthHook()); core.setAuthPluginHook(new BungeeAuthHook());
getLogger().info("Hooked into BungeeAuth"); logger.info("Hooked into BungeeAuth");
} }
} }
@@ -75,6 +79,11 @@ public class FastLoginBungee extends Plugin implements PlatformPlugin<CommandSen
return getDescription().getName(); return getDescription().getName();
} }
@Override
public Logger getLog() {
return logger;
}
@Override @Override
public void sendMessage(CommandSender receiver, String message) { public void sendMessage(CommandSender receiver, String message) {
receiver.sendMessage(TextComponent.fromLegacyText(message)); receiver.sendMessage(TextComponent.fromLegacyText(message));
@@ -88,6 +97,6 @@ public class FastLoginBungee extends Plugin implements PlatformPlugin<CommandSen
@Override @Override
public MojangApiConnector makeApiConnector(List<String> addresses, int requests, List<HostAndPort> proxies) { public MojangApiConnector makeApiConnector(List<String> addresses, int requests, List<HostAndPort> proxies) {
return new MojangApiConnector(getLogger(), addresses, requests, proxies); return new MojangApiConnector(getLog(), addresses, requests, proxies);
} }
} }

View File

@@ -9,7 +9,6 @@ import com.google.common.base.Charsets;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.PendingConnection; import net.md_5.bungee.api.connection.PendingConnection;
@@ -82,7 +81,7 @@ public class ConnectListener implements Listener {
idField.setAccessible(true); idField.setAccessible(true);
idField.set(connection, offlineUUID); idField.set(connection, offlineUUID);
} catch (NoSuchFieldException | IllegalAccessException ex) { } catch (NoSuchFieldException | IllegalAccessException ex) {
plugin.getLogger().log(Level.SEVERE, "Failed to set offline uuid", ex); plugin.getLog().error("Failed to set offline uuid", ex);
} }
} }

View File

@@ -13,7 +13,6 @@ import java.sql.Statement;
import java.util.Properties; import java.util.Properties;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadFactory;
import java.util.logging.Level;
public class AuthStorage { public class AuthStorage {
@@ -104,7 +103,7 @@ public class AuthStorage {
} }
} }
} catch (SQLException sqlEx) { } catch (SQLException sqlEx) {
core.getPlugin().getLogger().log(Level.SEVERE, "Failed to query profile", sqlEx); core.getPlugin().getLog().error("Failed to query profile", sqlEx);
} }
return null; return null;
@@ -128,7 +127,7 @@ public class AuthStorage {
} }
} }
} catch (SQLException sqlEx) { } catch (SQLException sqlEx) {
core.getPlugin().getLogger().log(Level.SEVERE, "Failed to query profile", sqlEx); core.getPlugin().getLog().error("Failed to query profile", sqlEx);
} }
return null; return null;
@@ -179,7 +178,7 @@ public class AuthStorage {
return true; return true;
} catch (SQLException ex) { } catch (SQLException ex) {
core.getPlugin().getLogger().log(Level.SEVERE, "Failed to save playerProfile", ex); core.getPlugin().getLog().error("Failed to save playerProfile", ex);
} }
return false; return false;

View File

@@ -2,9 +2,15 @@ package com.github.games647.fastlogin.core;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
import java.lang.reflect.Constructor;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.JDK14LoggerAdapter;
public class CommonUtil { public class CommonUtil {
@@ -47,6 +53,19 @@ public class CommonUtil {
return new String(chars); return new String(chars);
} }
public static Logger createLoggerFromJDK(java.util.logging.Logger parent) {
try {
Class<JDK14LoggerAdapter> adapterClass = JDK14LoggerAdapter.class;
Constructor<JDK14LoggerAdapter> cons = adapterClass.getDeclaredConstructor(java.util.logging.Logger.class);
cons.setAccessible(true);
return cons.newInstance(parent);
} catch (ReflectiveOperationException reflectEx) {
parent.log(Level.WARNING, "Cannot create slf4j logging adapter", reflectEx);
parent.log(Level.WARNING, "Creating logger instance manually...");
return LoggerFactory.getLogger(parent.getName());
}
}
private CommonUtil() { private CommonUtil() {
//Utility class //Utility class
} }

View File

@@ -27,24 +27,23 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
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.Logger;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import org.slf4j.Logger;
public class MojangApiConnector { public class MojangApiConnector {
//http connection, read timeout and user agent for a connection to mojang api servers //http connection, read timeout and user agent for a connection to mojang api servers
private static final int TIMEOUT = 3 * 1_000; private static final int TIMEOUT = 3 * 1_000;
private static final String USER_AGENT = "Premium-Checker"; private static final String USER_AGENT = "Premium-Checker";
private static final int RATE_LIMIT_CODE = 429;
//only premium (paid account) users have a uuid from here //only premium (paid account) users have a uuid from here
private static final String UUID_LINK = "https://api.mojang.com/users/profiles/minecraft/"; private static final String UUID_LINK = "https://api.mojang.com/users/profiles/minecraft/";
private static final int RATE_LIMIT_CODE = 429;
//this includes a-zA-Z1-9_ //this includes a-zA-Z1-9_
//compile the pattern only on plugin enable -> and this have to be thread-safe //compile the pattern only on plugin enable -> and this have to be thread-safe
private final Pattern validNameMatcher = Pattern.compile("^\\w{2,16}$"); private final Pattern validNameMatcher = Pattern.compile("^\\w{2,16}$");
@@ -53,6 +52,7 @@ public class MojangApiConnector {
private final Map<Object, Object> requests = CommonUtil.buildCache(10, -1); private final Map<Object, Object> requests = CommonUtil.buildCache(10, -1);
private final SSLSocketFactory sslFactory; private final SSLSocketFactory sslFactory;
private final int rateLimit; private final int rateLimit;
private long lastRateLimit; private long lastRateLimit;
protected final Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create(); protected final Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
@@ -110,7 +110,7 @@ public class MojangApiConnector {
} }
//204 - no content for not found //204 - no content for not found
} catch (Exception ex) { } catch (Exception ex) {
logger.log(Level.SEVERE, "Failed to check if player has a paid account", ex); logger.error("Failed to check if player has a paid account", ex);
} }
return Optional.empty(); return Optional.empty();
@@ -161,13 +161,13 @@ public 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 {0}", address); logger.warn("Submitted IP-Address is not local {0}", address);
continue; continue;
} }
addresses.add(address); addresses.add(address);
} catch (UnknownHostException ex) { } catch (UnknownHostException ex) {
logger.log(Level.SEVERE, "IP-Address is unknown to us", ex); logger.error("IP-Address is unknown to us", ex);
} }
} }

View File

@@ -23,7 +23,6 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.function.Function; import java.util.function.Function;
import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.Configuration;
@@ -72,7 +71,7 @@ public class FastLoginCore<P extends C, C, T extends PlatformPlugin<C>> {
} }
}); });
} catch (IOException ioEx) { } catch (IOException ioEx) {
plugin.getLogger().log(Level.INFO, "Failed to load yaml files", ioEx); plugin.getLog().error("Failed to load yaml files", ioEx);
} }
List<String> ipAddresses = config.getStringList("ip-addresses"); List<String> ipAddresses = config.getStringList("ip-addresses");
@@ -134,7 +133,7 @@ public class FastLoginCore<P extends C, C, T extends PlatformPlugin<C>> {
storage.createTables(); storage.createTables();
return true; return true;
} catch (Exception ex) { } catch (Exception ex) {
plugin.getLogger().log(Level.SEVERE, "Failed to setup database. Disabling plugin...", ex); plugin.getLog().warn("Failed to setup database. Disabling plugin...", ex);
return false; return false;
} }
} }
@@ -180,7 +179,7 @@ public class FastLoginCore<P extends C, C, T extends PlatformPlugin<C>> {
} }
} }
} catch (IOException ioExc) { } catch (IOException ioExc) {
plugin.getLogger().log(Level.SEVERE, "Cannot create plugin folder " + dataFolder, ioExc); plugin.getLog().error("Cannot create plugin folder {}", dataFolder, ioExc);
} }
} }

View File

@@ -4,8 +4,6 @@ import com.github.games647.fastlogin.core.AuthStorage;
import com.github.games647.fastlogin.core.PlayerProfile; import com.github.games647.fastlogin.core.PlayerProfile;
import com.github.games647.fastlogin.core.hooks.AuthPlugin; import com.github.games647.fastlogin.core.hooks.AuthPlugin;
import java.util.logging.Level;
public abstract class ForceLoginManagement<P extends C, C, L extends LoginSession, T extends PlatformPlugin<C>> public abstract class ForceLoginManagement<P extends C, C, L extends LoginSession, T extends PlatformPlugin<C>>
implements Runnable { implements Runnable {
@@ -66,12 +64,12 @@ public abstract class ForceLoginManagement<P extends C, C, L extends LoginSessio
storage.save(playerProfile); storage.save(playerProfile);
} }
} catch (Exception ex) { } catch (Exception ex) {
core.getPlugin().getLogger().log(Level.WARNING, "ERROR ON FORCE LOGIN", ex); core.getPlugin().getLog().warn("ERROR ON FORCE LOGIN", ex);
} }
} }
public boolean forceRegister(P player) { public boolean forceRegister(P player) {
core.getPlugin().getLogger().log(Level.INFO, "Register player {0}", getName(player)); core.getPlugin().getLog().info("Register player {}", getName(player));
String generatedPassword = core.getPasswordGenerator().getRandomPassword(player); String generatedPassword = core.getPasswordGenerator().getRandomPassword(player);
boolean success = core.getAuthPluginHook().forceRegister(player, generatedPassword); boolean success = core.getAuthPluginHook().forceRegister(player, generatedPassword);
@@ -86,7 +84,7 @@ public abstract class ForceLoginManagement<P extends C, C, L extends LoginSessio
} }
public boolean forceLogin(P player) { public boolean forceLogin(P player) {
core.getPlugin().getLogger().log(Level.INFO, "Logging player {0} in", getName(player)); core.getPlugin().getLog().info("Logging player {} in", getName(player));
boolean success = core.getAuthPluginHook().forceLogin(player); boolean success = core.getAuthPluginHook().forceLogin(player);
if (success) { if (success) {

View File

@@ -5,7 +5,6 @@ import com.github.games647.fastlogin.core.hooks.AuthPlugin;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level;
import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.Configuration;
@@ -32,7 +31,7 @@ public abstract class JoinManagement<P extends C, C, S extends LoginSource> {
try { try {
if (profile.getUserId() == -1) { if (profile.getUserId() == -1) {
if (core.getPendingLogin().remove(ip + username) != null && config.get("secondAttemptCracked", false)) { if (core.getPendingLogin().remove(ip + username) != null && config.get("secondAttemptCracked", false)) {
core.getPlugin().getLogger().log(Level.INFO, "Second attempt login -> cracked {0}", username); core.getPlugin().getLog().info("Second attempt login -> cracked {}", username);
//first login request failed so make a cracked session //first login request failed so make a cracked session
startCrackedSession(source, profile, username); startCrackedSession(source, profile, username);
@@ -61,12 +60,12 @@ public abstract class JoinManagement<P extends C, C, S extends LoginSource> {
startCrackedSession(source, profile, username); startCrackedSession(source, profile, username);
} }
} catch (Exception ex) { } catch (Exception ex) {
core.getPlugin().getLogger().log(Level.SEVERE, "Failed to check premium state", ex); core.getPlugin().getLog().error("Failed to check premium state", ex);
} }
} }
private boolean checkPremiumName(S source, String username, PlayerProfile profile) throws Exception { private boolean checkPremiumName(S source, String username, PlayerProfile profile) throws Exception {
core.getPlugin().getLogger().log(Level.FINER, "GameProfile {0} uses a premium username", username); core.getPlugin().getLog().debug("GameProfile {} uses a premium username", username);
if (core.getConfig().get("autoRegister", false) && (authHook == null || !authHook.isRegistered(username))) { if (core.getConfig().get("autoRegister", false) && (authHook == null || !authHook.isRegistered(username))) {
requestPremiumLogin(source, profile, username, false); requestPremiumLogin(source, profile, username, false);
return true; return true;
@@ -81,7 +80,7 @@ public abstract class JoinManagement<P extends C, C, S extends LoginSource> {
PlayerProfile profile = core.getStorage().loadProfile(premiumUUID); PlayerProfile profile = core.getStorage().loadProfile(premiumUUID);
if (profile != null) { if (profile != null) {
//uuid exists in the database //uuid exists in the database
core.getPlugin().getLogger().log(Level.FINER, "GameProfile {0} changed it's username", premiumUUID); core.getPlugin().getLog().info("GameProfile {} changed it's username", premiumUUID);
//update the username to the new one in the database //update the username to the new one in the database
profile.setPlayerName(username); profile.setPlayerName(username);

View File

@@ -6,7 +6,8 @@ import com.google.common.net.HostAndPort;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadFactory;
import java.util.logging.Logger;
import org.slf4j.Logger;
public interface PlatformPlugin<C> { public interface PlatformPlugin<C> {
@@ -14,7 +15,7 @@ public interface PlatformPlugin<C> {
File getDataFolder(); File getDataFolder();
Logger getLogger(); Logger getLog();
void sendMessage(C receiver, String message); void sendMessage(C receiver, String message);