From 3b6997a7239b538c3676b49cd76986035f54931e Mon Sep 17 00:00:00 2001 From: Gravita Date: Tue, 13 Apr 2021 16:47:42 +0700 Subject: [PATCH] [FEATURE][EXPERIMENTAL] Log4j logging --- LaunchServer/build.gradle | 3 +- .../pro/gravit/launchserver/LaunchServer.java | 63 ++++++++++--------- .../launchserver/LaunchServerStarter.java | 39 ++++++------ .../launchserver/auth/MySQLSourceConfig.java | 7 ++- .../auth/PostgreSQLSourceConfig.java | 7 ++- .../auth/handler/CachedAuthHandler.java | 13 ++-- .../auth/handler/MySQLAuthHandler.java | 16 ++--- .../auth/handler/RequestAuthHandler.java | 46 +++++++------- .../auth/protect/AdvancedProtectHandler.java | 9 ++- .../auth/session/MemorySessionStorage.java | 7 ++- .../auth/texture/RequestTextureProvider.java | 5 -- .../launchserver/binary/BinaryPipeline.java | 12 ++-- .../launchserver/binary/BuildContext.java | 8 +-- .../binary/EXELauncherBinary.java | 1 - LaunchServer/src/main/resources/log4j2.xml | 30 +++++++++ LaunchServer/src/test/resources/log4j2.xml | 13 ++++ props.gradle | 1 + 17 files changed, 170 insertions(+), 110 deletions(-) create mode 100644 LaunchServer/src/main/resources/log4j2.xml create mode 100644 LaunchServer/src/test/resources/log4j2.xml diff --git a/LaunchServer/build.gradle b/LaunchServer/build.gradle index 91e939bd..47d6de15 100644 --- a/LaunchServer/build.gradle +++ b/LaunchServer/build.gradle @@ -78,13 +78,14 @@ pack project(':LauncherAPI') bundle group: 'org.bouncycastle', name: 'bcpkix-jdk15on', version: rootProject['verBcpkix'] bundle group: 'org.ow2.asm', name: 'asm-commons', version: rootProject['verAsm'] bundle group: 'io.netty', name: 'netty-all', version: rootProject['verNetty'] - bundle group: 'org.slf4j', name: 'slf4j-simple', version: rootProject['verSlf4j'] bundle group: 'org.slf4j', name: 'slf4j-api', version: rootProject['verSlf4j'] bundle group: 'org.hibernate', name: 'hibernate-core', version: rootProject['verHibernate'] bundle group: 'org.hibernate', name: 'hibernate-hikaricp', version: rootProject['verHibernate'] bundle group: 'mysql', name: 'mysql-connector-java', version: rootProject['verMySQLConn'] bundle group: 'org.postgresql', name: 'postgresql', version: rootProject['verPostgreSQLConn'] bundle group: 'com.guardsquare', name: 'proguard-base', version: rootProject['verProguard'] + bundle group: 'org.apache.logging.log4j', name: 'log4j-core', version: rootProject['verLog4j'] + bundle group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: rootProject['verLog4j'] testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter', version: rootProject['verJunit'] hikari 'io.micrometer:micrometer-core:1.5.10' diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServer.java b/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServer.java index cf0ec0b0..73ffb3c8 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServer.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServer.java @@ -1,5 +1,7 @@ package pro.gravit.launchserver; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import pro.gravit.launcher.Launcher; import pro.gravit.launcher.NeedGarbageCollection; import pro.gravit.launcher.hasher.HashedDir; @@ -24,7 +26,6 @@ import pro.gravit.utils.helper.CommonHelper; import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.JVMHelper; -import pro.gravit.utils.helper.LogHelper; import java.io.BufferedReader; import java.io.IOException; @@ -45,6 +46,7 @@ * Not a singletron */ public final class LaunchServer implements Runnable, AutoCloseable, Reconfigurable { + private final Logger logger = LogManager.getLogger(); public static final Class defaultLauncherEXEBinaryClass = null; /** @@ -179,13 +181,13 @@ public LaunchServer(LaunchServerDirectories directories, LaunchServerEnv env, La syncLauncherBinaries(); launcherModuleLoader = new LauncherModuleLoader(this); if (config.components != null) { - LogHelper.debug("Init components"); + logger.debug("Init components"); config.components.forEach((k, v) -> { - LogHelper.subDebug("Init component %s", k); + logger.debug("Init component {}", k); v.setComponentName(k); v.init(this); }); - LogHelper.debug("Init components successful"); + logger.debug("Init components successful"); } launcherModuleLoader.init(); nettyServerSocketHandler = new NettyServerSocketHandler(this); @@ -199,7 +201,7 @@ public void reload(ReloadType type) throws Exception { if (type.equals(ReloadType.NO_AUTH)) { pairs = config.auth; } - LogHelper.info("Reading LaunchServer config file"); + logger.info("Reading LaunchServer config file"); config = launchServerConfigManager.readConfig(); config.setLaunchServer(this); if (type.equals(ReloadType.NO_AUTH)) { @@ -208,13 +210,13 @@ public void reload(ReloadType type) throws Exception { config.verify(); config.init(type); if (type.equals(ReloadType.FULL) && config.components != null) { - LogHelper.debug("Init components"); + logger.debug("Init components"); config.components.forEach((k, v) -> { - LogHelper.subDebug("Init component %s", k); + logger.debug("Init component {}", k); v.setComponentName(k); v.init(this); }); - LogHelper.debug("Init components successful"); + logger.debug("Init components successful"); } } @@ -251,7 +253,7 @@ public void invoke(String... args) throws Exception { public void invoke(String... args) throws Exception { launchServerConfigManager.writeConfig(config); launchServerConfigManager.writeRuntimeConfig(runtime); - LogHelper.info("LaunchServerConfig saved"); + logger.info("LaunchServerConfig saved"); } }; commands.put("save", save); @@ -263,14 +265,14 @@ private LauncherBinary binary() { try { return (LauncherBinary) MethodHandles.publicLookup().findConstructor(launcherEXEBinaryClass, MethodType.methodType(void.class, LaunchServer.class)).invoke(this); } catch (Throwable e) { - LogHelper.error(e); + logger.error(e); } } try { Class.forName("net.sf.launch4j.Builder"); if (config.launch4j.enabled) return new EXEL4JLauncherBinary(this); } catch (ClassNotFoundException ignored) { - LogHelper.warning("Launch4J isn't in classpath."); + logger.warn("Launch4J isn't in classpath."); } return new EXELauncherBinary(this); } @@ -281,15 +283,15 @@ public void buildLauncherBinaries() throws IOException { } public void close() throws Exception { - LogHelper.info("Close server socket"); + logger.info("Close server socket"); nettyServerSocketHandler.close(); // Close handlers & providers config.close(ReloadType.FULL); modulesManager.invokeEvent(new ClosePhase()); - LogHelper.info("Save LaunchServer runtime config"); + logger.info("Save LaunchServer runtime config"); launchServerConfigManager.writeRuntimeConfig(runtime); // Print last message before death :( - LogHelper.info("LaunchServer stopped"); + logger.info("LaunchServer stopped"); } public List getProfiles() { @@ -324,7 +326,7 @@ public void run() { try { close(); } catch (Exception e) { - LogHelper.error(e); + logger.error(e); } })); CommonHelper.newThread("Command Thread", true, commandHandler).start(); @@ -342,8 +344,8 @@ public void run() { syncProfilesDir(); modulesManager.invokeEvent(new LaunchServerProfilesSyncEvent(this)); } catch (IOException e) { - LogHelper.error(e); - LogHelper.error("Updates/Profiles not synced"); + logger.error(e); + logger.error("Updates/Profiles not synced"); } }).start(); } @@ -352,29 +354,29 @@ public void run() { try { modulesManager.fullInitializedLaunchServer(this); modulesManager.invokeEvent(new LaunchServerFullInitEvent(this)); - LogHelper.info("LaunchServer started"); + logger.info("LaunchServer started"); } catch (Throwable e) { - LogHelper.error(e); + logger.error(e); JVMHelper.RUNTIME.exit(-1); } } public void syncLauncherBinaries() throws IOException { - LogHelper.info("Syncing launcher binaries"); + logger.info("Syncing launcher binaries"); // Syncing launcher binary - LogHelper.info("Syncing launcher binary file"); - if (!launcherBinary.sync()) LogHelper.warning("Missing launcher binary file"); + logger.info("Syncing launcher binary file"); + if (!launcherBinary.sync()) logger.warn("Missing launcher binary file"); // Syncing launcher EXE binary - LogHelper.info("Syncing launcher EXE binary file"); + logger.info("Syncing launcher EXE binary file"); if (!launcherEXEBinary.sync() && config.launch4j.enabled) - LogHelper.warning("Missing launcher EXE binary file"); + logger.warn("Missing launcher EXE binary file"); } public void syncProfilesDir() throws IOException { - LogHelper.info("Syncing profiles dir"); + logger.info("Syncing profiles dir"); List newProfies = new LinkedList<>(); IOHelper.walk(profilesDir, new ProfilesFileVisitor(newProfies), false); @@ -386,7 +388,7 @@ public void syncProfilesDir() throws IOException { } public void syncUpdatesDir(Collection dirs) throws IOException { - LogHelper.info("Syncing updates dir"); + logger.info("Syncing updates dir"); Map newUpdatesDirMap = new HashMap<>(16); try (DirectoryStream dirStream = Files.newDirectoryStream(updatesDir)) { for (final Path updateDir : dirStream) { @@ -397,7 +399,7 @@ public void syncUpdatesDir(Collection dirs) throws IOException { String name = IOHelper.getFileName(updateDir); if (!IOHelper.isDir(updateDir)) { if (!IOHelper.isFile(updateDir) && Stream.of(".jar", ".exe", ".hash").noneMatch(e -> updateDir.toString().endsWith(e))) - LogHelper.warning("Not update dir: '%s'", name); + logger.warn("Not update dir: '{}'", name); continue; } @@ -411,7 +413,7 @@ public void syncUpdatesDir(Collection dirs) throws IOException { } // Sync and sign update dir - LogHelper.info("Syncing '%s' update dir", name); + logger.info("Syncing '{}' update dir", name); HashedDir updateHDir = new HashedDir(updateDir, null, true, true); newUpdatesDirMap.put(name, updateHDir); } @@ -430,7 +432,7 @@ public void restart() { try { builder.start(); } catch (IOException e) { - LogHelper.error(e); + logger.error(e); } } @@ -483,6 +485,7 @@ public interface LaunchServerConfigManager { private static final class ProfilesFileVisitor extends SimpleFileVisitor { private final Collection result; + private final Logger logger = LogManager.getLogger(); private ProfilesFileVisitor(Collection result) { this.result = result; @@ -490,7 +493,7 @@ private ProfilesFileVisitor(Collection result) { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - LogHelper.info("Syncing '%s' profile", IOHelper.getFileName(file)); + logger.info("Syncing '{}' profile", IOHelper.getFileName(file)); // Read profile ClientProfile profile; diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServerStarter.java b/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServerStarter.java index 5dc95b7b..ff1351f3 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServerStarter.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServerStarter.java @@ -1,5 +1,7 @@ package pro.gravit.launchserver; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.bouncycastle.jce.provider.BouncyCastleProvider; import pro.gravit.launcher.Launcher; import pro.gravit.launcher.LauncherTrustManager; @@ -45,11 +47,12 @@ public class LaunchServerStarter { public static final boolean allowUnsigned = Boolean.getBoolean("launchserver.allowUnsigned"); public static final boolean inDocker = Boolean.getBoolean("launchserver.dockered"); public static final boolean prepareMode = Boolean.getBoolean("launchserver.prepareMode"); + private static final Logger logger = LogManager.getLogger(); public static void main(String[] args) throws Exception { JVMHelper.checkStackTrace(LaunchServerStarter.class); JVMHelper.verifySystemProperties(LaunchServer.class, true); - LogHelper.addOutput(IOHelper.WORKING_DIR.resolve("LaunchServer.log")); + //LogHelper.addOutput(IOHelper.WORKING_DIR.resolve("LaunchServer.log")); LogHelper.printVersion("LaunchServer"); LogHelper.printLicense("LaunchServer"); if (!StarterAgent.isAgentStarted()) { @@ -78,14 +81,14 @@ public static void main(String[] args) throws Exception { { LauncherTrustManager.CheckClassResult result = certificateManager.checkClass(LaunchServer.class); if (result.type == LauncherTrustManager.CheckClassResultType.SUCCESS) { - LogHelper.info("LaunchServer signed by %s", result.endCertificate.getSubjectDN().getName()); + logger.info("LaunchServer signed by {}", result.endCertificate.getSubjectDN().getName()); } else if (result.type == LauncherTrustManager.CheckClassResultType.NOT_SIGNED) { // None } else { if (result.exception != null) { - LogHelper.error(result.exception); + logger.error(result.exception); } - LogHelper.warning("LaunchServer signed incorrectly. Status: %s", result.type.name()); + logger.warn("LaunchServer signed incorrectly. Status: {}", result.type.name()); } } @@ -113,38 +116,38 @@ public static void main(String[] args) throws Exception { // JLine2 available localCommandHandler = new JLineCommandHandler(); - LogHelper.info("JLine2 terminal enabled"); + logger.info("JLine2 terminal enabled"); } catch (ClassNotFoundException ignored) { localCommandHandler = new StdCommandHandler(true); - LogHelper.warning("JLine2 isn't in classpath, using std"); + logger.warn("JLine2 isn't in classpath, using std"); } if (IOHelper.isFile(publicKeyFile) && IOHelper.isFile(privateKeyFile)) { - LogHelper.info("Reading EC keypair"); + logger.info("Reading EC keypair"); publicKey = SecurityHelper.toPublicECDSAKey(IOHelper.read(publicKeyFile)); privateKey = SecurityHelper.toPrivateECDSAKey(IOHelper.read(privateKeyFile)); } else { - LogHelper.info("Generating EC keypair"); + logger.info("Generating EC keypair"); KeyPair pair = SecurityHelper.genECDSAKeyPair(new SecureRandom()); publicKey = (ECPublicKey) pair.getPublic(); privateKey = (ECPrivateKey) pair.getPrivate(); // Write key pair list - LogHelper.info("Writing EC keypair list"); + logger.info("Writing EC keypair list"); IOHelper.write(publicKeyFile, publicKey.getEncoded()); IOHelper.write(privateKeyFile, privateKey.getEncoded()); } modulesManager.invokeEvent(new PreConfigPhase()); generateConfigIfNotExists(configFile, localCommandHandler, env); - LogHelper.info("Reading LaunchServer config file"); + logger.info("Reading LaunchServer config file"); try (BufferedReader reader = IOHelper.newReader(configFile)) { config = Launcher.gsonManager.gson.fromJson(reader, LaunchServerConfig.class); } if (!Files.exists(runtimeConfigFile)) { - LogHelper.info("Reset LaunchServer runtime config file"); + logger.info("Reset LaunchServer runtime config file"); runtimeConfig = new LaunchServerRuntimeConfig(); runtimeConfig.reset(); } else { - LogHelper.info("Reading LaunchServer runtime config file"); + logger.info("Reading LaunchServer runtime config file"); try (BufferedReader reader = IOHelper.newReader(runtimeConfigFile)) { runtimeConfig = Launcher.gsonManager.gson.fromJson(reader, LaunchServerRuntimeConfig.class); } @@ -175,7 +178,7 @@ public void writeConfig(LaunchServerConfig config) throws IOException { if (Launcher.gsonManager.configGson != null) { Launcher.gsonManager.configGson.toJson(config, writer); } else { - LogHelper.error("Error writing LaunchServer runtime config file. Gson is null"); + logger.error("Error writing LaunchServer runtime config file. Gson is null"); } } } @@ -186,7 +189,7 @@ public void writeRuntimeConfig(LaunchServerRuntimeConfig config) throws IOExcept if (Launcher.gsonManager.configGson != null) { Launcher.gsonManager.configGson.toJson(config, writer); } else { - LogHelper.error("Error writing LaunchServer runtime config file. Gson is null"); + logger.error("Error writing LaunchServer runtime config file. Gson is null"); } } } @@ -240,7 +243,7 @@ public static void generateConfigIfNotExists(Path configFile, CommandHandler com return; // Create new config - LogHelper.info("Creating LaunchServer config"); + logger.info("Creating LaunchServer config"); LaunchServerConfig newConfig = LaunchServerConfig.getDefault(env); @@ -256,11 +259,11 @@ public static void generateConfigIfNotExists(Path configFile, CommandHandler com newConfig.setProjectName(commandHandler.readLine()); } if (address == null || address.isEmpty()) { - LogHelper.error("Address null. Using localhost"); + logger.error("Address null. Using localhost"); address = "localhost"; } if (newConfig.projectName == null || newConfig.projectName.isEmpty()) { - LogHelper.error("ProjectName null. Using MineCraft"); + logger.error("ProjectName null. Using MineCraft"); newConfig.projectName = "MineCraft"; } @@ -270,7 +273,7 @@ public static void generateConfigIfNotExists(Path configFile, CommandHandler com newConfig.netty.launcherEXEURL = "http://" + address + ":9274/Launcher.exe"; // Write LaunchServer config - LogHelper.info("Writing LaunchServer config file"); + logger.info("Writing LaunchServer config file"); try (BufferedWriter writer = IOHelper.newWriter(configFile)) { Launcher.gsonManager.configGson.toJson(newConfig, writer); } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/MySQLSourceConfig.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/MySQLSourceConfig.java index a3b787f5..17955096 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/MySQLSourceConfig.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/MySQLSourceConfig.java @@ -3,6 +3,8 @@ import com.mysql.cj.jdbc.MysqlDataSource; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import pro.gravit.utils.helper.LogHelper; import pro.gravit.utils.helper.VerifyHelper; @@ -21,6 +23,7 @@ public final class MySQLSourceConfig implements AutoCloseable { // Instance private transient final String poolName; + private transient final Logger logger = LogManager.getLogger(); // Config private String address; @@ -106,9 +109,9 @@ public synchronized Connection getConnection() throws SQLException { // Set HikariCP pool // Replace source with hds source = new HikariDataSource(cfg); - LogHelper.warning("HikariCP pooling enabled for '%s'", poolName); + logger.warn("HikariCP pooling enabled for '{}'", poolName); } catch (ClassNotFoundException ignored) { - LogHelper.debug("HikariCP isn't in classpath for '%s'", poolName); + logger.debug("HikariCP isn't in classpath for '{}'", poolName); } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/PostgreSQLSourceConfig.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/PostgreSQLSourceConfig.java index f32e219c..f4a62909 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/PostgreSQLSourceConfig.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/PostgreSQLSourceConfig.java @@ -1,6 +1,8 @@ package pro.gravit.launchserver.auth; import com.zaxxer.hikari.HikariDataSource; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.postgresql.ds.PGSimpleDataSource; import pro.gravit.utils.helper.LogHelper; import pro.gravit.utils.helper.VerifyHelper; @@ -19,6 +21,7 @@ public final class PostgreSQLSourceConfig implements AutoCloseable { // Instance private String poolName; + private transient final Logger logger = LogManager.getLogger(); // Config private String[] addresses; @@ -69,9 +72,9 @@ public synchronized Connection getConnection() throws SQLException { // Replace source with hds source = hikariSource; - LogHelper.info("HikariCP pooling enabled for '%s'", poolName); + logger.info("HikariCP pooling enabled for '{}'", poolName); } catch (ClassNotFoundException ignored) { - LogHelper.warning("HikariCP isn't in classpath for '%s'", poolName); + logger.warn("HikariCP isn't in classpath for '{}'", poolName); } } return source.getConnection(); diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/CachedAuthHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/CachedAuthHandler.java index edcb0509..45337457 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/CachedAuthHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/CachedAuthHandler.java @@ -1,5 +1,7 @@ package pro.gravit.launchserver.auth.handler; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import pro.gravit.launcher.Launcher; import pro.gravit.launcher.NeedGarbageCollection; import pro.gravit.launchserver.Reconfigurable; @@ -20,6 +22,7 @@ public abstract class CachedAuthHandler extends AuthHandler implements NeedGarbageCollection, Reconfigurable { private transient final Map entryCache = new HashMap<>(1024); private transient final Map usernamesCache = new HashMap<>(1024); + private transient final Logger logger = LogManager.getLogger(); @Override public Map getCommands() { @@ -31,7 +34,7 @@ public void invoke(String... args) { long usernamesCacheSize = usernamesCache.size(); entryCache.clear(); usernamesCache.clear(); - LogHelper.info("Cleared cache: %d Entry %d Usernames", entryCacheSize, usernamesCacheSize); + logger.info("Cleared cache: {} Entry {} Usernames", entryCacheSize, usernamesCacheSize); } }); commands.put("load", new SubCommand() { @@ -39,7 +42,7 @@ public void invoke(String... args) { public void invoke(String... args) throws Exception { verifyArgs(args, 2); - LogHelper.info("CachedAuthHandler read from %s", args[0]); + logger.info("CachedAuthHandler read from {}", args[0]); int size_entry; int size_username; try (Reader reader = IOHelper.newReader(Paths.get(args[1]))) { @@ -50,7 +53,7 @@ public void invoke(String... args) throws Exception { loadUsernameCache(entryAndUsername.usernameCache); } - LogHelper.subInfo("Readed %d entryCache %d usernameCache", size_entry, size_username); + logger.info("Read {} entryCache {} usernameCache", size_entry, size_username); } }); commands.put("unload", new SubCommand() { @@ -58,7 +61,7 @@ public void invoke(String... args) throws Exception { public void invoke(String... args) throws Exception { verifyArgs(args, 2); - LogHelper.info("CachedAuthHandler write to %s", args[1]); + logger.info("CachedAuthHandler write to {}", args[1]); Map entryCache = getEntryCache(); Map usernamesCache = getUsernamesCache(); EntryAndUsername serializable = new EntryAndUsername(); @@ -67,7 +70,7 @@ public void invoke(String... args) throws Exception { try (Writer writer = IOHelper.newWriter(Paths.get(args[1]))) { Launcher.gsonManager.configGson.toJson(serializable, writer); } - LogHelper.subInfo("Write %d entryCache, %d usernameCache", entryCache.size(), usernamesCache.size()); + logger.info("Write {} entryCache, {} usernameCache", entryCache.size(), usernamesCache.size()); } }); return commands; diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/MySQLAuthHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/MySQLAuthHandler.java index f6368280..863566b0 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/MySQLAuthHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/MySQLAuthHandler.java @@ -1,8 +1,9 @@ package pro.gravit.launchserver.auth.handler; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.auth.MySQLSourceConfig; -import pro.gravit.utils.helper.LogHelper; import java.io.IOException; import java.sql.Connection; @@ -12,6 +13,7 @@ import java.util.UUID; public final class MySQLAuthHandler extends CachedAuthHandler { + private transient final Logger logger = LogManager.getLogger(); private MySQLSourceConfig mySQLHolder; private String uuidColumn; private String usernameColumn; @@ -29,12 +31,12 @@ public final class MySQLAuthHandler extends CachedAuthHandler { public void init(LaunchServer srv) { super.init(srv); //Verify - if (mySQLHolder == null) LogHelper.error("[Verify][AuthHandler] mySQLHolder cannot be null"); - if (uuidColumn == null) LogHelper.error("[Verify][AuthHandler] uuidColumn cannot be null"); - if (usernameColumn == null) LogHelper.error("[Verify][AuthHandler] usernameColumn cannot be null"); - if (accessTokenColumn == null) LogHelper.error("[Verify][AuthHandler] accessTokenColumn cannot be null"); - if (serverIDColumn == null) LogHelper.error("[Verify][AuthHandler] serverIDColumn cannot be null"); - if (table == null) LogHelper.error("[Verify][AuthHandler] table cannot be null"); + if (mySQLHolder == null) logger.error("mySQLHolder cannot be null"); + if (uuidColumn == null) logger.error("uuidColumn cannot be null"); + if (usernameColumn == null) logger.error("usernameColumn cannot be null"); + if (accessTokenColumn == null) logger.error("accessTokenColumn cannot be null"); + if (serverIDColumn == null) logger.error("serverIDColumn cannot be null"); + if (table == null) logger.error("table cannot be null"); // Prepare SQL queries queryByUUIDSQL = String.format("SELECT %s, %s, %s, %s FROM %s WHERE %s=? LIMIT 1", uuidColumn, usernameColumn, accessTokenColumn, serverIDColumn, table, uuidColumn); diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/RequestAuthHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/RequestAuthHandler.java index a11c4d82..dfa2f8f7 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/RequestAuthHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/RequestAuthHandler.java @@ -1,15 +1,17 @@ package pro.gravit.launchserver.auth.handler; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import pro.gravit.launchserver.LaunchServer; import pro.gravit.utils.helper.CommonHelper; import pro.gravit.utils.helper.IOHelper; -import pro.gravit.utils.helper.LogHelper; import java.io.IOException; import java.net.URL; import java.util.UUID; public final class RequestAuthHandler extends CachedAuthHandler { + private transient final Logger logger = LogManager.getLogger(); private final String splitSymbol = ":"; private final String goodResponse = "OK"; private String usernameFetch; @@ -21,13 +23,13 @@ public final class RequestAuthHandler extends CachedAuthHandler { public void init(LaunchServer srv) { super.init(srv); if (usernameFetch == null) - LogHelper.error("[Verify][AuthHandler] usernameFetch cannot be null"); + logger.error("usernameFetch cannot be null"); if (uuidFetch == null) - LogHelper.error("[Verify][AuthHandler] uuidFetch cannot be null"); + logger.error("uuidFetch cannot be null"); if (updateAuth == null) - LogHelper.error("[Verify][AuthHandler] updateAuth cannot be null"); + logger.error("updateAuth cannot be null"); if (updateServerID == null) - LogHelper.error("[Verify][AuthHandler] updateServerID cannot be null"); + logger.error("updateServerID cannot be null"); } @Override @@ -37,11 +39,11 @@ protected Entry fetchEntry(UUID uuid) throws IOException { String username = parts[0]; String accessToken = parts[1]; String serverID = parts[2]; - if (LogHelper.isDebugEnabled()) { - LogHelper.debug("[AuthHandler] Got username: " + username); - LogHelper.debug("[AuthHandler] Got accessToken: " + accessToken); - LogHelper.debug("[AuthHandler] Got serverID: " + serverID); - LogHelper.debug("[AuthHandler] Got UUID: " + uuid); + if (logger.isDebugEnabled()) { + logger.debug("[AuthHandler] Got username: " + username); + logger.debug("[AuthHandler] Got accessToken: " + accessToken); + logger.debug("[AuthHandler] Got serverID: " + serverID); + logger.debug("[AuthHandler] Got UUID: " + uuid); } return new Entry(uuid, username, accessToken, serverID); } @@ -53,11 +55,11 @@ protected Entry fetchEntry(String username) throws IOException { UUID uuid = UUID.fromString(parts[0]); String accessToken = parts[1]; String serverID = parts[2]; - if (LogHelper.isDebugEnabled()) { - LogHelper.debug("[AuthHandler] Got username: " + username); - LogHelper.debug("[AuthHandler] Got accessToken: " + accessToken); - LogHelper.debug("[AuthHandler] Got serverID: " + serverID); - LogHelper.debug("[AuthHandler] Got UUID: " + uuid); + if (logger.isDebugEnabled()) { + logger.debug("[AuthHandler] Got username: " + username); + logger.debug("[AuthHandler] Got accessToken: " + accessToken); + logger.debug("[AuthHandler] Got serverID: " + serverID); + logger.debug("[AuthHandler] Got UUID: " + uuid); } return new Entry(uuid, username, accessToken, serverID); } @@ -65,10 +67,10 @@ protected Entry fetchEntry(String username) throws IOException { @Override protected boolean updateAuth(UUID uuid, String username, String accessToken) throws IOException { String response = IOHelper.request(new URL(CommonHelper.replace(updateAuth, "user", IOHelper.urlEncode(username), "uuid", IOHelper.urlEncode(uuid.toString()), "token", IOHelper.urlEncode(accessToken)))); - if (LogHelper.isDebugEnabled()) { - LogHelper.debug("[AuthHandler] Set accessToken: " + accessToken); - LogHelper.debug("[AuthHandler] Set UUID: " + uuid); - LogHelper.debug("[AuthHandler] For this username: " + username); + if (logger.isDebugEnabled()) { + logger.debug("[AuthHandler] Set accessToken: " + accessToken); + logger.debug("[AuthHandler] Set UUID: " + uuid); + logger.debug("[AuthHandler] For this username: " + username); } return goodResponse.equals(response); } @@ -76,9 +78,9 @@ protected boolean updateAuth(UUID uuid, String username, String accessToken) thr @Override protected boolean updateServerID(UUID uuid, String serverID) throws IOException { String response = IOHelper.request(new URL(CommonHelper.replace(updateAuth, "serverid", IOHelper.urlEncode(serverID), "uuid", IOHelper.urlEncode(uuid.toString())))); - if (LogHelper.isDebugEnabled()) { - LogHelper.debug("[AuthHandler] Set serverID: " + serverID); - LogHelper.debug("[AuthHandler] For this UUID: " + uuid); + if (logger.isDebugEnabled()) { + logger.debug("[AuthHandler] Set serverID: " + serverID); + logger.debug("[AuthHandler] For this UUID: " + uuid); } return goodResponse.equals(response); } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java index de6ec57c..a72e0679 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java @@ -1,5 +1,7 @@ package pro.gravit.launchserver.auth.protect; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import pro.gravit.launcher.events.request.GetSecureLevelInfoRequestEvent; import pro.gravit.launcher.events.request.HardwareReportRequestEvent; import pro.gravit.launcher.events.request.VerifySecureLevelKeyRequestEvent; @@ -20,6 +22,7 @@ import java.util.Map; public class AdvancedProtectHandler extends StdProtectHandler implements SecureProtectHandler, HardwareProtectHandler, JoinServerProtectHandler, Reconfigurable { + private transient final Logger logger = LogManager.getLogger(); public boolean enableHardwareFeature; public HWIDProvider provider; private transient LaunchServer server; @@ -56,9 +59,9 @@ public void onHardwareReport(HardwareReportResponse response, Client client) { return; } provider.normalizeHardwareInfo(response.hardware); - LogHelper.debug("[HardwareInfo] HardwareInfo received"); + logger.debug("HardwareInfo received"); boolean needCreate = !provider.addPublicKeyToHardwareInfo(response.hardware, client.trustLevel.publicKey, client); - LogHelper.debug("[HardwareInfo] HardwareInfo needCreate: %s", needCreate ? "true" : "false"); + logger.debug("HardwareInfo needCreate: {}", needCreate ? "true" : "false"); if (needCreate) provider.createHardwareInfo(response.hardware, client.trustLevel.publicKey, client); client.trustLevel.hardwareInfo = response.hardware; @@ -72,7 +75,7 @@ public void onHardwareReport(HardwareReportResponse response, Client client) { public VerifySecureLevelKeyRequestEvent onSuccessVerify(Client client) { if (enableHardwareFeature) { if (provider == null) { - LogHelper.warning("HWIDProvider null. HardwareInfo not checked!"); + logger.warn("HWIDProvider null. HardwareInfo not checked!"); } else { try { client.trustLevel.hardwareInfo = provider.findHardwareInfoByPublicKey(client.trustLevel.publicKey, client); diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/session/MemorySessionStorage.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/session/MemorySessionStorage.java index c9bfa0e3..86043483 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/session/MemorySessionStorage.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/session/MemorySessionStorage.java @@ -1,5 +1,7 @@ package pro.gravit.launchserver.auth.session; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import pro.gravit.launcher.Launcher; import pro.gravit.launcher.NeedGarbageCollection; import pro.gravit.launchserver.LaunchServer; @@ -23,6 +25,7 @@ public class MemorySessionStorage extends SessionStorage implements NeedGarbageC private transient final Map clientSet = new ConcurrentHashMap<>(128); private transient final Map> uuidIndex = new ConcurrentHashMap<>(32); + private transient final Logger logger = LogManager.getLogger(); public boolean autoDump = false; public String dumpFile = "sessions.json"; @@ -100,7 +103,7 @@ public void dumpSessionsData() { try (Writer writer = IOHelper.newWriter(path)) { Launcher.gsonManager.gson.toJson(dumpedData, writer); } catch (IOException e) { - LogHelper.error(e); + logger.error(e); } } @@ -112,7 +115,7 @@ public void loadSessionsData() { clientSet.putAll(data.clientSet); uuidIndex.putAll(data.uuidIndex); } catch (IOException e) { - LogHelper.error(e); + logger.error(e); } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/texture/RequestTextureProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/texture/RequestTextureProvider.java index 5dbf3843..720393a4 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/texture/RequestTextureProvider.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/texture/RequestTextureProvider.java @@ -4,7 +4,6 @@ import pro.gravit.launcher.profiles.Texture; import pro.gravit.utils.helper.CommonHelper; import pro.gravit.utils.helper.IOHelper; -import pro.gravit.utils.helper.LogHelper; import java.io.FileNotFoundException; import java.io.IOException; @@ -24,13 +23,9 @@ public RequestTextureProvider(String skinURL, String cloakURL) { } private static Texture getTexture(String url, boolean cloak) throws IOException { - if (LogHelper.isDebugEnabled()) { - LogHelper.debug("Getting texture: '%s'", url); - } try { return new Texture(url, cloak); } catch (FileNotFoundException ignored) { - LogHelper.subDebug("Texture not found :("); return null; // Simply not found } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/binary/BinaryPipeline.java b/LaunchServer/src/main/java/pro/gravit/launchserver/binary/BinaryPipeline.java index 70629bc2..97672dbf 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/binary/BinaryPipeline.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/binary/BinaryPipeline.java @@ -1,9 +1,10 @@ package pro.gravit.launchserver.binary; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import pro.gravit.launchserver.binary.tasks.LauncherBuildTask; import pro.gravit.utils.helper.CommonHelper; import pro.gravit.utils.helper.IOHelper; -import pro.gravit.utils.helper.LogHelper; import java.io.IOException; import java.nio.file.Files; @@ -16,6 +17,7 @@ import java.util.stream.Collectors; public class BinaryPipeline { + private transient final Logger logger = LogManager.getLogger(); public final List tasks = new ArrayList<>(); public final AtomicLong count = new AtomicLong(0); public final Path buildDir; @@ -71,14 +73,14 @@ public Optional getTaskByClass(Class taskCla } public void build(Path target, boolean deleteTempFiles) throws IOException { - LogHelper.info("Building launcher binary file"); + logger.info("Building launcher binary file"); count.set(0); // set jar number Path thisPath = null; boolean isNeedDelete = false; long time_start = System.currentTimeMillis(); long time_this = time_start; for (LauncherBuildTask task : tasks) { - LogHelper.subInfo("Task %s", task.getName()); + logger.info("Task {}", task.getName()); Path oldPath = thisPath; thisPath = task.process(oldPath); long time_task_end = System.currentTimeMillis(); @@ -86,12 +88,12 @@ public void build(Path target, boolean deleteTempFiles) throws IOException { time_this = time_task_end; if (isNeedDelete && deleteTempFiles) Files.deleteIfExists(oldPath); isNeedDelete = task.allowDelete(); - LogHelper.subInfo("Task %s processed from %d millis", task.getName(), time_task); + logger.info("Task {} processed from {} millis", task.getName(), time_task); } long time_end = System.currentTimeMillis(); if (isNeedDelete && deleteTempFiles) IOHelper.move(thisPath, target); else IOHelper.copy(thisPath, target); - LogHelper.info("Build successful from %d millis", time_end - time_start); + logger.info("Build successful from {} millis", time_end - time_start); } public String nextName(String taskName) { diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/binary/BuildContext.java b/LaunchServer/src/main/java/pro/gravit/launchserver/binary/BuildContext.java index 0ce0dc34..4d2640e6 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/binary/BuildContext.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/binary/BuildContext.java @@ -121,13 +121,7 @@ public void pushJarFile(URL jarfile, Predicate filter, Predicate + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/LaunchServer/src/test/resources/log4j2.xml b/LaunchServer/src/test/resources/log4j2.xml new file mode 100644 index 00000000..2e56255a --- /dev/null +++ b/LaunchServer/src/test/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/props.gradle b/props.gradle index 0cf55ec8..fbe4303f 100644 --- a/props.gradle +++ b/props.gradle @@ -10,6 +10,7 @@ verGson = '2.8.6' verBcpkix = '1.68' verSlf4j = '1.7.30' + verLog4j = '2.14.1' verMySQLConn = '8.0.23' verPostgreSQLConn = '42.2.19' verProguard = '7.1.0-beta1'