[REFACTOR] Idea Reformat Code

This commit is contained in:
Gravita 2021-05-25 16:17:29 +07:00
parent 2c41b510ad
commit cd99641327
123 changed files with 846 additions and 903 deletions

View file

@ -11,7 +11,10 @@
import pro.gravit.launcher.profiles.ClientProfile; import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launchserver.auth.AuthProviderPair; import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.auth.session.MemorySessionStorage; import pro.gravit.launchserver.auth.session.MemorySessionStorage;
import pro.gravit.launchserver.binary.*; import pro.gravit.launchserver.binary.EXEL4JLauncherBinary;
import pro.gravit.launchserver.binary.EXELauncherBinary;
import pro.gravit.launchserver.binary.JARLauncherBinary;
import pro.gravit.launchserver.binary.LauncherBinary;
import pro.gravit.launchserver.config.LaunchServerConfig; import pro.gravit.launchserver.config.LaunchServerConfig;
import pro.gravit.launchserver.config.LaunchServerRuntimeConfig; import pro.gravit.launchserver.config.LaunchServerRuntimeConfig;
import pro.gravit.launchserver.launchermodules.LauncherModuleLoader; import pro.gravit.launchserver.launchermodules.LauncherModuleLoader;
@ -50,8 +53,6 @@
* Not a singletron * Not a singletron
*/ */
public final class LaunchServer implements Runnable, AutoCloseable, Reconfigurable { public final class LaunchServer implements Runnable, AutoCloseable, Reconfigurable {
private final Logger logger = LogManager.getLogger();
public static final Class<? extends LauncherBinary> defaultLauncherEXEBinaryClass = null; public static final Class<? extends LauncherBinary> defaultLauncherEXEBinaryClass = null;
/** /**
* Working folder path * Working folder path
@ -69,12 +70,12 @@ public final class LaunchServer implements Runnable, AutoCloseable, Reconfigurab
* The path to the folder with compile-only libraries for the launcher * The path to the folder with compile-only libraries for the launcher
*/ */
public final Path launcherLibrariesCompile; public final Path launcherLibrariesCompile;
// Constant paths
/** /**
* The path to the folder with updates/webroot * The path to the folder with updates/webroot
*/ */
public final Path updatesDir; public final Path updatesDir;
// Constant paths
/** /**
* Save/Reload LaunchServer config * Save/Reload LaunchServer config
*/ */
@ -100,7 +101,6 @@ public final class LaunchServer implements Runnable, AutoCloseable, Reconfigurab
* Pipeline for building EXE * Pipeline for building EXE
*/ */
public final LauncherBinary launcherEXEBinary; public final LauncherBinary launcherEXEBinary;
//public static LaunchServer server = null; //public static LaunchServer server = null;
public final Class<? extends LauncherBinary> launcherEXEBinaryClass; public final Class<? extends LauncherBinary> launcherEXEBinaryClass;
// Server config // Server config
@ -125,6 +125,7 @@ public final class LaunchServer implements Runnable, AutoCloseable, Reconfigurab
public final ScheduledExecutorService service; public final ScheduledExecutorService service;
public final AtomicBoolean started = new AtomicBoolean(false); public final AtomicBoolean started = new AtomicBoolean(false);
public final LauncherModuleLoader launcherModuleLoader; public final LauncherModuleLoader launcherModuleLoader;
private final Logger logger = LogManager.getLogger();
public LaunchServerConfig config; public LaunchServerConfig config;
public volatile Map<String, HashedDir> updatesDirMap; public volatile Map<String, HashedDir> updatesDirMap;
// Updates and profiles // Updates and profiles
@ -541,13 +542,14 @@ public void collect() {
if (launcherLibrariesDir == null) launcherLibrariesDir = getPath(LAUNCHERLIBRARIES_NAME); if (launcherLibrariesDir == null) launcherLibrariesDir = getPath(LAUNCHERLIBRARIES_NAME);
if (launcherLibrariesCompileDir == null) if (launcherLibrariesCompileDir == null)
launcherLibrariesCompileDir = getPath(LAUNCHERLIBRARIESCOMPILE_NAME); launcherLibrariesCompileDir = getPath(LAUNCHERLIBRARIESCOMPILE_NAME);
if(keyDirectory == null) keyDirectory = getPath(KEY_NAME); if (keyDirectory == null) keyDirectory = getPath(KEY_NAME);
if(tmpDir ==null) tmpDir = Paths.get(System.getProperty("java.io.tmpdir")).resolve(String.format("launchserver-%s", SecurityHelper.randomStringToken())); if (tmpDir == null)
tmpDir = Paths.get(System.getProperty("java.io.tmpdir")).resolve(String.format("launchserver-%s", SecurityHelper.randomStringToken()));
} }
private Path getPath(String dirName) { private Path getPath(String dirName) {
String property = System.getProperty("launchserver.dir."+dirName, null); String property = System.getProperty("launchserver.dir." + dirName, null);
if(property == null) return dir.resolve(dirName); if (property == null) return dir.resolve(dirName);
else return Paths.get(property); else return Paths.get(property);
} }
} }

View file

@ -8,8 +8,6 @@
import pro.gravit.utils.command.CommandHandler; import pro.gravit.utils.command.CommandHandler;
import java.nio.file.Path; import java.nio.file.Path;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
public class LaunchServerBuilder { public class LaunchServerBuilder {
private LaunchServerConfig config; private LaunchServerConfig config;
@ -87,7 +85,7 @@ public void writeRuntimeConfig(LaunchServerRuntimeConfig config) {
} }
}; };
} }
if(keyAgreementManager == null) { if (keyAgreementManager == null) {
keyAgreementManager = new KeyAgreementManager(directories.keyDirectory); keyAgreementManager = new KeyAgreementManager(directories.keyDirectory);
} }
return new LaunchServer(directories, env, config, runtimeConfig, launchServerConfigManager, modulesManager, keyAgreementManager, commandHandler, certificateManager); return new LaunchServer(directories, env, config, runtimeConfig, launchServerConfigManager, modulesManager, keyAgreementManager, commandHandler, certificateManager);

View file

@ -31,7 +31,6 @@
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.JVMHelper; import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper; import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
@ -39,12 +38,8 @@
import java.io.Writer; import java.io.Writer;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.security.KeyPair;
import java.security.SecureRandom;
import java.security.Security; import java.security.Security;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
public class LaunchServerStarter { public class LaunchServerStarter {
public static final boolean allowUnsigned = Boolean.getBoolean("launchserver.allowUnsigned"); public static final boolean allowUnsigned = Boolean.getBoolean("launchserver.allowUnsigned");
@ -189,7 +184,7 @@ public void writeRuntimeConfig(LaunchServerRuntimeConfig config) throws IOExcept
.setLaunchServerConfigManager(launchServerConfigManager) .setLaunchServerConfigManager(launchServerConfigManager)
.setCertificateManager(certificateManager) .setCertificateManager(certificateManager)
.build(); .build();
if(!prepareMode) { if (!prepareMode) {
server.run(); server.run();
} else { } else {
server.close(); server.close();
@ -235,18 +230,18 @@ public static void generateConfigIfNotExists(Path configFile, CommandHandler com
newConfig.setProjectName("test"); newConfig.setProjectName("test");
} else { } else {
address = System.getenv("ADDRESS"); address = System.getenv("ADDRESS");
if(address == null) { if (address == null) {
address = System.getProperty("launchserver.address", null); address = System.getProperty("launchserver.address", null);
} }
if(address == null) { if (address == null) {
System.out.println("LaunchServer address(default: localhost): "); System.out.println("LaunchServer address(default: localhost): ");
address = commandHandler.readLine(); address = commandHandler.readLine();
} }
String projectName = System.getenv("PROJECTNAME"); String projectName = System.getenv("PROJECTNAME");
if(projectName == null) { if (projectName == null) {
projectName = System.getProperty("launchserver.projectname", null); projectName = System.getProperty("launchserver.projectname", null);
} }
if(projectName == null) { if (projectName == null) {
System.out.println("LaunchServer projectName: "); System.out.println("LaunchServer projectName: ");
projectName = commandHandler.readLine(); projectName = commandHandler.readLine();
} }

View file

@ -28,7 +28,7 @@ public AuthProviderPair(AuthProvider provider, AuthHandler handler, TextureProvi
public void init(LaunchServer srv, String name) { public void init(LaunchServer srv, String name) {
this.name = name; this.name = name;
if (links != null) link(srv); if (links != null) link(srv);
if(core == null) { if (core == null) {
if (provider == null) throw new NullPointerException(String.format("Auth %s provider null", name)); if (provider == null) throw new NullPointerException(String.format("Auth %s provider null", name));
if (handler == null) throw new NullPointerException(String.format("Auth %s handler null", name)); if (handler == null) throw new NullPointerException(String.format("Auth %s handler null", name));
provider.init(srv); provider.init(srv);
@ -65,7 +65,7 @@ public void link(LaunchServer srv) {
} }
public void close() throws IOException { public void close() throws IOException {
if(core == null) { if (core == null) {
provider.close(); provider.close();
handler.close(); handler.close();
} else { } else {

View file

@ -5,7 +5,6 @@
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.VerifyHelper; import pro.gravit.utils.helper.VerifyHelper;
import javax.sql.DataSource; import javax.sql.DataSource;

View file

@ -4,7 +4,6 @@
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.postgresql.ds.PGSimpleDataSource; import org.postgresql.ds.PGSimpleDataSource;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.VerifyHelper; import pro.gravit.utils.helper.VerifyHelper;
import javax.sql.DataSource; import javax.sql.DataSource;
@ -18,11 +17,9 @@ public final class PostgreSQLSourceConfig implements AutoCloseable {
private static final int MAX_POOL_SIZE = VerifyHelper.verifyInt( private static final int MAX_POOL_SIZE = VerifyHelper.verifyInt(
Integer.parseUnsignedInt(System.getProperty("launcher.postgresql.maxPoolSize", Integer.toString(3))), Integer.parseUnsignedInt(System.getProperty("launcher.postgresql.maxPoolSize", Integer.toString(3))),
VerifyHelper.POSITIVE, "launcher.postgresql.maxPoolSize can't be <= 0"); VerifyHelper.POSITIVE, "launcher.postgresql.maxPoolSize can't be <= 0");
private transient final Logger logger = LogManager.getLogger();
// Instance // Instance
private String poolName; private String poolName;
private transient final Logger logger = LogManager.getLogger();
// Config // Config
private String[] addresses; private String[] addresses;
private int[] ports; private int[] ports;

View file

@ -18,7 +18,6 @@
import pro.gravit.utils.command.Command; import pro.gravit.utils.command.Command;
import pro.gravit.utils.command.CommandException; import pro.gravit.utils.command.CommandException;
import pro.gravit.utils.command.SubCommand; import pro.gravit.utils.command.SubCommand;
import pro.gravit.utils.helper.SecurityHelper;
import java.io.IOException; import java.io.IOException;
import java.util.Collections; import java.util.Collections;
@ -31,8 +30,9 @@
*/ */
public abstract class AuthCoreProvider implements AutoCloseable, Reconfigurable { public abstract class AuthCoreProvider implements AutoCloseable, Reconfigurable {
public static final ProviderMap<AuthCoreProvider> providers = new ProviderMap<>("AuthCoreProvider"); public static final ProviderMap<AuthCoreProvider> providers = new ProviderMap<>("AuthCoreProvider");
private static boolean registredProviders = false;
private static final Logger logger = LogManager.getLogger(); private static final Logger logger = LogManager.getLogger();
private static boolean registredProviders = false;
public static void registerProviders() { public static void registerProviders() {
if (!registredProviders) { if (!registredProviders) {
providers.register("reject", RejectAuthCoreProvider.class); providers.register("reject", RejectAuthCoreProvider.class);
@ -40,14 +40,23 @@ public static void registerProviders() {
registredProviders = true; registredProviders = true;
} }
} }
public abstract User getUserByUsername(String username); public abstract User getUserByUsername(String username);
public abstract User getUserByUUID(UUID uuid); public abstract User getUserByUUID(UUID uuid);
public abstract UserSession getUserSessionByOAuthAccessToken(String accessToken) throws OAuthAccessTokenExpired; public abstract UserSession getUserSessionByOAuthAccessToken(String accessToken) throws OAuthAccessTokenExpired;
public abstract AuthManager.AuthReport refreshAccessToken(String refreshToken, AuthResponse.AuthContext context /* may be null */); public abstract AuthManager.AuthReport refreshAccessToken(String refreshToken, AuthResponse.AuthContext context /* may be null */);
public abstract void verifyAuth(AuthResponse.AuthContext context) throws AuthException; public abstract void verifyAuth(AuthResponse.AuthContext context) throws AuthException;
public abstract PasswordVerifyReport verifyPassword(User user, AuthRequest.AuthPasswordInterface password); public abstract PasswordVerifyReport verifyPassword(User user, AuthRequest.AuthPasswordInterface password);
public abstract AuthManager.AuthReport createOAuthSession(User user, AuthResponse.AuthContext context /* may be null */, PasswordVerifyReport report /* may be null */, boolean minecraftAccess) throws IOException; public abstract AuthManager.AuthReport createOAuthSession(User user, AuthResponse.AuthContext context /* may be null */, PasswordVerifyReport report /* may be null */, boolean minecraftAccess) throws IOException;
public abstract void init(LaunchServer server); public abstract void init(LaunchServer server);
// Auth Handler methods // Auth Handler methods
protected abstract boolean updateServerID(User user, String serverID) throws IOException; protected abstract boolean updateServerID(User user, String serverID) throws IOException;
@ -63,19 +72,19 @@ public Map<String, Command> getCommands() {
public void invoke(String... args) throws Exception { public void invoke(String... args) throws Exception {
verifyArgs(args, 2); verifyArgs(args, 2);
User user = getUserByUsername(args[0]); User user = getUserByUsername(args[0]);
if(user == null) throw new CommandException("User not found"); if (user == null) throw new CommandException("User not found");
AuthRequest.AuthPasswordInterface password; AuthRequest.AuthPasswordInterface password;
if(args[1].startsWith("{")) { if (args[1].startsWith("{")) {
password = Launcher.gsonManager.gson.fromJson(args[1], AuthRequest.AuthPasswordInterface.class); password = Launcher.gsonManager.gson.fromJson(args[1], AuthRequest.AuthPasswordInterface.class);
} else { } else {
password = new AuthPlainPassword(args[1]); password = new AuthPlainPassword(args[1]);
} }
PasswordVerifyReport report = verifyPassword(user, password); PasswordVerifyReport report = verifyPassword(user, password);
if(report.success) { if (report.success) {
logger.info("Password correct"); logger.info("Password correct");
} else { } else {
if(report.needMoreFactor) { if (report.needMoreFactor) {
if(report.factors.size() == 1 && report.factors.get(0) == -1) { if (report.factors.size() == 1 && report.factors.get(0) == -1) {
logger.info("Password not correct: Required 2FA"); logger.info("Password not correct: Required 2FA");
} else { } else {
logger.info("Password not correct: Required more factors: {}", report.factors.toString()); logger.info("Password not correct: Required more factors: {}", report.factors.toString());
@ -86,19 +95,19 @@ public void invoke(String... args) throws Exception {
} }
} }
}); });
if(this instanceof AuthSupportGetAllUsers) { if (this instanceof AuthSupportGetAllUsers) {
AuthSupportGetAllUsers instance = (AuthSupportGetAllUsers) this; AuthSupportGetAllUsers instance = (AuthSupportGetAllUsers) this;
map.put("getallusers", new SubCommand("(limit)", "print all users information") { map.put("getallusers", new SubCommand("(limit)", "print all users information") {
@Override @Override
public void invoke(String... args) throws Exception { public void invoke(String... args) throws Exception {
int max = Integer.MAX_VALUE; int max = Integer.MAX_VALUE;
if(args.length > 0) max = Integer.parseInt(args[0]); if (args.length > 0) max = Integer.parseInt(args[0]);
List<User> users = instance.getAllUsers(); List<User> users = instance.getAllUsers();
int counter = 0; int counter = 0;
for(User u : users) { for (User u : users) {
logger.info("User {}", u.toString()); logger.info("User {}", u.toString());
counter++; counter++;
if(counter == max) break; if (counter == max) break;
} }
logger.info("Found {} users", counter); logger.info("Found {} users", counter);
} }
@ -109,7 +118,7 @@ public void invoke(String... args) throws Exception {
public UUID checkServer(Client client, String username, String serverID) throws IOException { public UUID checkServer(Client client, String username, String serverID) throws IOException {
User user = getUserByUsername(username); User user = getUserByUsername(username);
if(user.getUsername().equals(username) && user.getServerId().equals(serverID)) { if (user.getUsername().equals(username) && user.getServerId().equals(serverID)) {
return user.getUUID(); return user.getUUID();
} }
return null; return null;
@ -117,7 +126,7 @@ public UUID checkServer(Client client, String username, String serverID) throws
public boolean joinServer(Client client, String username, String accessToken, String serverID) throws IOException { public boolean joinServer(Client client, String username, String accessToken, String serverID) throws IOException {
User user = client.getUser(); User user = client.getUser();
if(user == null) return false; if (user == null) return false;
return user.getUsername().equals(username) && user.getAccessToken().equals(accessToken) && updateServerID(user, serverID); return user.getUsername().equals(username) && user.getAccessToken().equals(accessToken) && updateServerID(user, serverID);
} }
@ -125,11 +134,11 @@ public boolean joinServer(Client client, String username, String accessToken, St
public abstract void close() throws IOException; public abstract void close() throws IOException;
public static class PasswordVerifyReport { public static class PasswordVerifyReport {
public static final PasswordVerifyReport REQUIRED_2FA = new PasswordVerifyReport(-1);
public static final PasswordVerifyReport FAILED = new PasswordVerifyReport(false);
public final boolean success; public final boolean success;
public final boolean needMoreFactor; public final boolean needMoreFactor;
public final List<Integer> factors; public final List<Integer> factors;
public static final PasswordVerifyReport REQUIRED_2FA = new PasswordVerifyReport(-1);
public static final PasswordVerifyReport FAILED = new PasswordVerifyReport(false);
public PasswordVerifyReport(boolean success) { public PasswordVerifyReport(boolean success) {
this.success = success; this.success = success;

View file

@ -75,7 +75,7 @@ public void verifyAuth(AuthResponse.AuthContext context) throws AuthException {
@Override @Override
public PasswordVerifyReport verifyPassword(User user, AuthRequest.AuthPasswordInterface password) { public PasswordVerifyReport verifyPassword(User user, AuthRequest.AuthPasswordInterface password) {
if(passwordVerifier.check(((MySQLUser)user).password, ((AuthPlainPassword)password).password)) { if (passwordVerifier.check(((MySQLUser) user).password, ((AuthPlainPassword) password).password)) {
return new PasswordVerifyReport(true); return new PasswordVerifyReport(true);
} else { } else {
return PasswordVerifyReport.FAILED; return PasswordVerifyReport.FAILED;
@ -84,7 +84,7 @@ public PasswordVerifyReport verifyPassword(User user, AuthRequest.AuthPasswordIn
@Override @Override
public AuthManager.AuthReport createOAuthSession(User user, AuthResponse.AuthContext context, PasswordVerifyReport report, boolean minecraftAccess) throws IOException { public AuthManager.AuthReport createOAuthSession(User user, AuthResponse.AuthContext context, PasswordVerifyReport report, boolean minecraftAccess) throws IOException {
if(minecraftAccess) { if (minecraftAccess) {
String minecraftAccessToken = SecurityHelper.randomStringToken(); String minecraftAccessToken = SecurityHelper.randomStringToken();
updateAuth(user, minecraftAccessToken); updateAuth(user, minecraftAccessToken);
return AuthManager.AuthReport.ofMinecraftAccessToken(minecraftAccessToken); return AuthManager.AuthReport.ofMinecraftAccessToken(minecraftAccessToken);

View file

@ -6,8 +6,12 @@
public interface User { public interface User {
String getUsername(); String getUsername();
UUID getUUID(); UUID getUUID();
String getServerId(); String getServerId();
String getAccessToken(); String getAccessToken();
ClientPermissions getPermissions(); ClientPermissions getPermissions();
} }

View file

@ -2,6 +2,8 @@
public interface UserSession { public interface UserSession {
String getID(); String getID();
User getUser(); User getUser();
long getExpireIn(); long getExpireIn();
} }

View file

@ -5,5 +5,6 @@
public interface AuthSupportExit { public interface AuthSupportExit {
boolean deleteSession(UserSession session); boolean deleteSession(UserSession session);
boolean exitUser(User user); boolean exitUser(User user);
} }

View file

@ -7,5 +7,6 @@
public interface AuthSupportGetSessionsFromUser { public interface AuthSupportGetSessionsFromUser {
List<UserSession> getSessionsByUser(User user); List<UserSession> getSessionsByUser(User user);
void clearSessionsByUser(User user); void clearSessionsByUser(User user);
} }

View file

@ -2,5 +2,6 @@
public interface UserSupportMoney { public interface UserSupportMoney {
long getMoney(); long getMoney();
long getDonateMoney(); long getDonateMoney();
} }

View file

@ -8,7 +8,10 @@
import pro.gravit.launchserver.auth.provider.AuthProviderResult; import pro.gravit.launchserver.auth.provider.AuthProviderResult;
import pro.gravit.utils.command.Command; import pro.gravit.utils.command.Command;
import pro.gravit.utils.command.SubCommand; import pro.gravit.utils.command.SubCommand;
import pro.gravit.utils.helper.*; import pro.gravit.utils.helper.CommonHelper;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.SecurityHelper;
import pro.gravit.utils.helper.VerifyHelper;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;

View file

@ -12,6 +12,7 @@
public class DigestPasswordVerifier extends PasswordVerifier { public class DigestPasswordVerifier extends PasswordVerifier {
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
public String algo; public String algo;
@Override @Override
public boolean check(String encryptedPassword, String password) { public boolean check(String encryptedPassword, String password) {
try { try {

View file

@ -13,6 +13,7 @@ public class DoubleDigestPasswordVerifier extends PasswordVerifier {
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
public String algo; public String algo;
public boolean toHexMode; public boolean toHexMode;
@Override @Override
public boolean check(String encryptedPassword, String password) { public boolean check(String encryptedPassword, String password) {
try { try {

View file

@ -5,13 +5,15 @@
public abstract class PasswordVerifier { public abstract class PasswordVerifier {
public static final ProviderMap<PasswordVerifier> providers = new ProviderMap<>("PasswordVerifier"); public static final ProviderMap<PasswordVerifier> providers = new ProviderMap<>("PasswordVerifier");
private static boolean registeredProviders = false; private static boolean registeredProviders = false;
public static void registerProviders() { public static void registerProviders() {
if(!registeredProviders) { if (!registeredProviders) {
providers.register("plain", PlainPasswordVerifier.class); providers.register("plain", PlainPasswordVerifier.class);
providers.register("digest", DigestPasswordVerifier.class); providers.register("digest", DigestPasswordVerifier.class);
providers.register("doubleDigest", DoubleDigestPasswordVerifier.class); providers.register("doubleDigest", DoubleDigestPasswordVerifier.class);
registeredProviders = true; registeredProviders = true;
} }
} }
public abstract boolean check(String encryptedPassword, String password); public abstract boolean check(String encryptedPassword, String password);
} }

View file

@ -16,7 +16,6 @@
import pro.gravit.launchserver.socket.response.auth.AuthResponse; import pro.gravit.launchserver.socket.response.auth.AuthResponse;
import pro.gravit.launchserver.socket.response.secure.HardwareReportResponse; import pro.gravit.launchserver.socket.response.secure.HardwareReportResponse;
import pro.gravit.utils.command.Command; import pro.gravit.utils.command.Command;
import pro.gravit.utils.helper.LogHelper;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;

View file

@ -16,10 +16,10 @@
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
public class MemoryHWIDProvider extends HWIDProvider implements Reconfigurable { public class MemoryHWIDProvider extends HWIDProvider implements Reconfigurable {
private transient final Logger logger = LogManager.getLogger();
public double warningSpoofingLevel = -1.0; public double warningSpoofingLevel = -1.0;
public double criticalCompareLevel = 1.0; public double criticalCompareLevel = 1.0;
public transient Set<MemoryHWIDEntity> db = ConcurrentHashMap.newKeySet(); public transient Set<MemoryHWIDEntity> db = ConcurrentHashMap.newKeySet();
private transient final Logger logger = LogManager.getLogger();
@Override @Override
public Map<String, Command> getCommands() { public Map<String, Command> getCommands() {

View file

@ -13,16 +13,15 @@
import java.sql.*; import java.sql.*;
public class MysqlHWIDProvider extends HWIDProvider { public class MysqlHWIDProvider extends HWIDProvider {
private transient final Logger logger = LogManager.getLogger();
public MySQLSourceConfig mySQLHolder; public MySQLSourceConfig mySQLHolder;
public double warningSpoofingLevel = -1.0; public double warningSpoofingLevel = -1.0;
public double criticalCompareLevel = 1.0; public double criticalCompareLevel = 1.0;
public String tableHWID = "hwids"; public String tableHWID = "hwids";
public String tableHWIDLog = "hwidLog"; public String tableHWIDLog = "hwidLog";
public String tableUsers; public String tableUsers;
public String usersNameColumn; public String usersNameColumn;
public String usersHWIDColumn; public String usersHWIDColumn;
private String sqlFindByPublicKey; private String sqlFindByPublicKey;
private String sqlFindByHardware; private String sqlFindByHardware;
private String sqlCreateHardware; private String sqlCreateHardware;
@ -30,8 +29,6 @@ public class MysqlHWIDProvider extends HWIDProvider {
private String sqlUpdateHardware; private String sqlUpdateHardware;
private String sqlUpdateUsers; private String sqlUpdateUsers;
private transient final Logger logger = LogManager.getLogger();
@Override @Override
public void init(LaunchServer server) { public void init(LaunchServer server) {
sqlFindByPublicKey = String.format("SELECT hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, banned FROM %s WHERE `publicKey` = ?", tableHWID); sqlFindByPublicKey = String.format("SELECT hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, banned FROM %s WHERE `publicKey` = ?", tableHWID);

View file

@ -24,18 +24,20 @@ public final class JsonAuthProvider extends AuthProvider {
public AuthProviderResult auth(String login, AuthRequest.AuthPasswordInterface password, String ip) throws IOException { public AuthProviderResult auth(String login, AuthRequest.AuthPasswordInterface password, String ip) throws IOException {
String firstPassword; String firstPassword;
String secondPassword; String secondPassword;
if(!enable2FA) { if (!enable2FA) {
if (!(password instanceof AuthPlainPassword)) throw new AuthException("This password type not supported"); if (!(password instanceof AuthPlainPassword)) throw new AuthException("This password type not supported");
firstPassword = ((AuthPlainPassword) password).password; firstPassword = ((AuthPlainPassword) password).password;
secondPassword = null; secondPassword = null;
} else { } else {
if(password instanceof AuthPlainPassword) { if (password instanceof AuthPlainPassword) {
firstPassword = ((AuthPlainPassword) password).password; firstPassword = ((AuthPlainPassword) password).password;
secondPassword = null; secondPassword = null;
} else if(password instanceof Auth2FAPassword) { } else if (password instanceof Auth2FAPassword) {
if (!(((Auth2FAPassword) password).firstPassword instanceof AuthPlainPassword)) throw new AuthException("This password type not supported"); if (!(((Auth2FAPassword) password).firstPassword instanceof AuthPlainPassword))
throw new AuthException("This password type not supported");
firstPassword = ((AuthPlainPassword) ((Auth2FAPassword) password).firstPassword).password; firstPassword = ((AuthPlainPassword) ((Auth2FAPassword) password).firstPassword).password;
if (!(((Auth2FAPassword) password).secondPassword instanceof AuthTOTPPassword)) throw new AuthException("This password type not supported"); if (!(((Auth2FAPassword) password).secondPassword instanceof AuthTOTPPassword))
throw new AuthException("This password type not supported");
secondPassword = ((AuthTOTPPassword) ((Auth2FAPassword) password).secondPassword).totp; secondPassword = ((AuthTOTPPassword) ((Auth2FAPassword) password).secondPassword).totp;
} else { } else {
throw new AuthException("This password type not supported"); throw new AuthException("This password type not supported");

View file

@ -8,7 +8,6 @@
import pro.gravit.launchserver.auth.AuthException; import pro.gravit.launchserver.auth.AuthException;
import pro.gravit.utils.command.Command; import pro.gravit.utils.command.Command;
import pro.gravit.utils.command.SubCommand; import pro.gravit.utils.command.SubCommand;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper; import pro.gravit.utils.helper.SecurityHelper;
import java.util.ArrayList; import java.util.ArrayList;
@ -16,11 +15,10 @@
import java.util.Map; import java.util.Map;
public final class RejectAuthProvider extends AuthProvider implements Reconfigurable { public final class RejectAuthProvider extends AuthProvider implements Reconfigurable {
private transient final Logger logger = LogManager.getLogger();
public String message; public String message;
public ArrayList<String> whitelist = new ArrayList<>(); public ArrayList<String> whitelist = new ArrayList<>();
private transient final Logger logger = LogManager.getLogger();
public RejectAuthProvider() { public RejectAuthProvider() {
} }

View file

@ -7,7 +7,6 @@
import pro.gravit.launchserver.auth.AuthException; import pro.gravit.launchserver.auth.AuthException;
import pro.gravit.utils.helper.CommonHelper; import pro.gravit.utils.helper.CommonHelper;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper; import pro.gravit.utils.helper.SecurityHelper;
import java.io.IOException; import java.io.IOException;

View file

@ -6,9 +6,7 @@
import pro.gravit.launcher.NeedGarbageCollection; import pro.gravit.launcher.NeedGarbageCollection;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import java.io.Writer; import java.io.Writer;
import java.nio.file.Files; import java.nio.file.Files;

View file

@ -17,11 +17,11 @@
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class BinaryPipeline { public class BinaryPipeline {
private transient final Logger logger = LogManager.getLogger();
public final List<LauncherBuildTask> tasks = new ArrayList<>(); public final List<LauncherBuildTask> tasks = new ArrayList<>();
public final AtomicLong count = new AtomicLong(0); public final AtomicLong count = new AtomicLong(0);
public final Path buildDir; public final Path buildDir;
public final String nameFormat; public final String nameFormat;
private transient final Logger logger = LogManager.getLogger();
public BinaryPipeline(Path buildDir, String nameFormat) { public BinaryPipeline(Path buildDir, String nameFormat) {
this.buildDir = buildDir; this.buildDir = buildDir;

View file

@ -1,12 +1,10 @@
package pro.gravit.launchserver.binary; package pro.gravit.launchserver.binary;
import org.jetbrains.annotations.NotNull;
import pro.gravit.launcher.Launcher; import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.serialize.HOutput; import pro.gravit.launcher.serialize.HOutput;
import pro.gravit.launcher.serialize.stream.StreamObject; import pro.gravit.launcher.serialize.stream.StreamObject;
import pro.gravit.launchserver.binary.tasks.MainBuildTask; import pro.gravit.launchserver.binary.tasks.MainBuildTask;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper; import pro.gravit.utils.helper.SecurityHelper;
import javax.crypto.Cipher; import javax.crypto.Cipher;
@ -33,7 +31,6 @@
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
@ -234,7 +231,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) { } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
try(OutputStream stream = new CipherOutputStream(new NoCloseOutputStream(output), cipher)) { try (OutputStream stream = new CipherOutputStream(new NoCloseOutputStream(output), cipher)) {
IOHelper.transfer(file, stream); IOHelper.transfer(file, stream);
} }

View file

@ -2,7 +2,6 @@
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;

View file

@ -3,7 +3,6 @@
import pro.gravit.launcher.Launcher; import pro.gravit.launcher.Launcher;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.binary.tasks.*; import pro.gravit.launchserver.binary.tasks.*;
import pro.gravit.launchserver.components.ProGuardComponent;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;

View file

@ -2,7 +2,6 @@
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
@ -60,7 +59,7 @@ private void attach(ZipOutputStream output, Path inputFile, List<Path> lst) thro
} }
private boolean filter(String name) { private boolean filter(String name) {
if(name.startsWith("META-INF/services")) return false; if (name.startsWith("META-INF/services")) return false;
return exclusions.stream().anyMatch(name::startsWith); return exclusions.stream().anyMatch(name::startsWith);
} }

View file

@ -34,12 +34,11 @@
public class CertificateAutogenTask implements LauncherBuildTask { public class CertificateAutogenTask implements LauncherBuildTask {
private final LaunchServer server; private final LaunchServer server;
private transient final Logger logger = LogManager.getLogger();
public X509Certificate certificate; public X509Certificate certificate;
public X509CertificateHolder bcCertificate; public X509CertificateHolder bcCertificate;
public CMSSignedDataGenerator signedDataGenerator; public CMSSignedDataGenerator signedDataGenerator;
private transient final Logger logger = LogManager.getLogger();
public CertificateAutogenTask(LaunchServer server) { public CertificateAutogenTask(LaunchServer server) {
this.server = server; this.server = server;
} }

View file

@ -17,7 +17,6 @@
import pro.gravit.launchserver.binary.BuildContext; import pro.gravit.launchserver.binary.BuildContext;
import pro.gravit.utils.HookException; import pro.gravit.utils.HookException;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper; import pro.gravit.utils.helper.SecurityHelper;
import java.io.IOException; import java.io.IOException;
@ -61,15 +60,16 @@ public Path process(Path inputJar) throws IOException {
properties.put("launcher.modules", context.clientModules.stream().map(e -> Type.getObjectType(e.replace('.', '/'))).collect(Collectors.toList())); properties.put("launcher.modules", context.clientModules.stream().map(e -> Type.getObjectType(e.replace('.', '/'))).collect(Collectors.toList()));
postInitProps(); postInitProps();
reader.getCp().add(new JarFile(inputJar.toFile())); reader.getCp().add(new JarFile(inputJar.toFile()));
for(Path e : server.launcherBinary.coreLibs) { for (Path e : server.launcherBinary.coreLibs) {
reader.getCp().add(new JarFile(e.toFile())); reader.getCp().add(new JarFile(e.toFile()));
}; }
;
context.pushJarFile(inputJar, (e) -> blacklist.contains(e.getName()), (e) -> true); context.pushJarFile(inputJar, (e) -> blacklist.contains(e.getName()), (e) -> true);
// map for guard // map for guard
Map<String, byte[]> runtime = new HashMap<>(256); Map<String, byte[]> runtime = new HashMap<>(256);
// Write launcher guard dir // Write launcher guard dir
if(server.config.launcher.encryptRuntime) { if (server.config.launcher.encryptRuntime) {
context.pushEncryptedDir(server.launcherBinary.runtimeDir, Launcher.RUNTIME_DIR, server.runtime.runtimeEncryptKey, runtime, false); context.pushEncryptedDir(server.launcherBinary.runtimeDir, Launcher.RUNTIME_DIR, server.runtime.runtimeEncryptKey, runtime, false);
} else { } else {
context.pushDir(server.launcherBinary.runtimeDir, Launcher.RUNTIME_DIR, runtime, false); context.pushDir(server.launcherBinary.runtimeDir, Launcher.RUNTIME_DIR, runtime, false);
@ -114,7 +114,8 @@ protected void initProps() {
properties.put("launchercore.env", server.config.env); properties.put("launchercore.env", server.config.env);
properties.put("launcher.memory", server.config.launcher.memoryLimit); properties.put("launcher.memory", server.config.launcher.memoryLimit);
if (server.config.launcher.encryptRuntime) { if (server.config.launcher.encryptRuntime) {
if (server.runtime.runtimeEncryptKey == null) server.runtime.runtimeEncryptKey = SecurityHelper.randomStringToken(); if (server.runtime.runtimeEncryptKey == null)
server.runtime.runtimeEncryptKey = SecurityHelper.randomStringToken();
properties.put("runtimeconfig.runtimeEncryptKey", server.runtime.runtimeEncryptKey); properties.put("runtimeconfig.runtimeEncryptKey", server.runtime.runtimeEncryptKey);
} }
properties.put("launcher.certificatePinning", server.config.launcher.certificatePinning); properties.put("launcher.certificatePinning", server.config.launcher.certificatePinning);

View file

@ -26,9 +26,9 @@
public class SignJarTask implements LauncherBuildTask { public class SignJarTask implements LauncherBuildTask {
private transient static final Logger logger = LogManager.getLogger();
private final LaunchServerConfig.JarSignerConf config; private final LaunchServerConfig.JarSignerConf config;
private final LaunchServer srv; private final LaunchServer srv;
private transient static final Logger logger = LogManager.getLogger();
public SignJarTask(LaunchServerConfig.JarSignerConf config, LaunchServer srv) { public SignJarTask(LaunchServerConfig.JarSignerConf config, LaunchServer srv) {
this.config = config; this.config = config;

View file

@ -8,7 +8,6 @@
import pro.gravit.launchserver.auth.provider.AuthProvider; import pro.gravit.launchserver.auth.provider.AuthProvider;
import pro.gravit.launchserver.auth.provider.AuthProviderResult; import pro.gravit.launchserver.auth.provider.AuthProviderResult;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.LogHelper;
import java.util.UUID; import java.util.UUID;

View file

@ -6,7 +6,6 @@
import pro.gravit.launchserver.auth.AuthProviderPair; import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.command.CommandException; import pro.gravit.utils.command.CommandException;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
import java.util.UUID; import java.util.UUID;

View file

@ -6,7 +6,6 @@
import pro.gravit.launchserver.auth.AuthProviderPair; import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.command.CommandException; import pro.gravit.utils.command.CommandException;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
import java.util.UUID; import java.util.UUID;

View file

@ -10,14 +10,13 @@
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.socket.handlers.NettyServerSocketHandler; import pro.gravit.launchserver.socket.handlers.NettyServerSocketHandler;
import pro.gravit.utils.helper.CommonHelper; import pro.gravit.utils.helper.CommonHelper;
import pro.gravit.utils.helper.LogHelper;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.security.KeyPair; import java.security.KeyPair;
public class TestCommand extends Command { public class TestCommand extends Command {
private NettyServerSocketHandler handler = null;
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
private NettyServerSocketHandler handler = null;
public TestCommand(LaunchServer server) { public TestCommand(LaunchServer server) {
super(server); super(server);

View file

@ -6,12 +6,12 @@
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.Version; import pro.gravit.utils.Version;
import pro.gravit.utils.helper.JVMHelper; import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper;
import java.lang.management.RuntimeMXBean; import java.lang.management.RuntimeMXBean;
public final class VersionCommand extends Command { public final class VersionCommand extends Command {
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
public VersionCommand(LaunchServer server) { public VersionCommand(LaunchServer server) {
super(server); super(server);
} }

View file

@ -5,7 +5,6 @@
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;

View file

@ -9,9 +9,7 @@
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.command.CommandException; import pro.gravit.utils.command.CommandException;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@ -46,7 +44,7 @@ public void invoke(String... args) throws IOException, CommandException {
Path clientDir = server.updatesDir.resolve(args[1]); Path clientDir = server.updatesDir.resolve(args[1]);
boolean isMirrorClientDownload = false; boolean isMirrorClientDownload = false;
if(args.length > 2) { if (args.length > 2) {
isMirrorClientDownload = args[2].equals("mirror"); isMirrorClientDownload = args[2].equals("mirror");
} }
@ -64,18 +62,18 @@ public void invoke(String... args) throws IOException, CommandException {
ClientProfile client = null; ClientProfile client = null;
try { try {
String internalVersion = versionName; String internalVersion = versionName;
if(internalVersion.contains("-")) { if (internalVersion.contains("-")) {
internalVersion = internalVersion.substring(0, versionName.indexOf('-')); internalVersion = internalVersion.substring(0, versionName.indexOf('-'));
} }
ClientProfile.Version version = ClientProfile.Version.byName(internalVersion); ClientProfile.Version version = ClientProfile.Version.byName(internalVersion);
if(version.compareTo(ClientProfile.Version.MC164) <= 0) { if (version.compareTo(ClientProfile.Version.MC164) <= 0) {
logger.warn("Minecraft 1.6.4 and below not supported. Use at your own risk"); logger.warn("Minecraft 1.6.4 and below not supported. Use at your own risk");
} }
client = SaveProfilesCommand.makeProfile(version, dirName, SaveProfilesCommand.getMakeProfileOptionsFromDir(clientDir, version)); client = SaveProfilesCommand.makeProfile(version, dirName, SaveProfilesCommand.getMakeProfileOptionsFromDir(clientDir, version));
} catch (Throwable e) { } catch (Throwable e) {
isMirrorClientDownload = true; isMirrorClientDownload = true;
} }
if(isMirrorClientDownload) { if (isMirrorClientDownload) {
JsonElement clientJson = server.mirrorManager.jsonRequest(null, "GET", "clients/%s.json", versionName); JsonElement clientJson = server.mirrorManager.jsonRequest(null, "GET", "clients/%s.json", versionName);
client = Launcher.gsonManager.configGson.fromJson(clientJson, ClientProfile.class); client = Launcher.gsonManager.configGson.fromJson(clientJson, ClientProfile.class);
client.setTitle(dirName); client.setTitle(dirName);

View file

@ -1,6 +1,5 @@
package pro.gravit.launchserver.command.hash; package pro.gravit.launchserver.command.hash;
import com.google.gson.Gson;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -9,7 +8,6 @@
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.command.CommandException; import pro.gravit.utils.command.CommandException;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper; import pro.gravit.utils.helper.SecurityHelper;
import pro.gravit.utils.helper.SecurityHelper.DigestAlgorithm; import pro.gravit.utils.helper.SecurityHelper.DigestAlgorithm;

View file

@ -3,7 +3,6 @@
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher; import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.hasher.HashedDir;
import pro.gravit.launcher.profiles.ClientProfile; import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.profiles.ClientProfileBuilder; import pro.gravit.launcher.profiles.ClientProfileBuilder;
import pro.gravit.launcher.profiles.optional.OptionalFile; import pro.gravit.launcher.profiles.optional.OptionalFile;
@ -12,7 +11,6 @@
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
@ -28,15 +26,11 @@ public SaveProfilesCommand(LaunchServer server) {
super(server); super(server);
} }
public enum MakeProfileOption {
LAUNCHWRAPPER, VANILLA, FORGE, FABRIC, LITELOADER
}
public static ClientProfile makeProfile(ClientProfile.Version version, String title, MakeProfileOption... options) { public static ClientProfile makeProfile(ClientProfile.Version version, String title, MakeProfileOption... options) {
ClientProfileBuilder builder = new ClientProfileBuilder(); ClientProfileBuilder builder = new ClientProfileBuilder();
builder.setVersion(version.name); builder.setVersion(version.name);
builder.setDir(title); builder.setDir(title);
builder.setAssetDir("asset"+version.name); builder.setAssetDir("asset" + version.name);
builder.setAssetIndex(version.name); builder.setAssetIndex(version.name);
builder.setInfo("Информация о сервере"); builder.setInfo("Информация о сервере");
builder.setTitle(title); builder.setTitle(title);
@ -57,16 +51,16 @@ public static ClientProfile makeProfile(ClientProfile.Version version, String ti
jvmArgs.add("-XX:MaxGCPauseMillis=50"); jvmArgs.add("-XX:MaxGCPauseMillis=50");
jvmArgs.add("-XX:G1HeapRegionSize=32M"); jvmArgs.add("-XX:G1HeapRegionSize=32M");
// ----------- // -----------
if(version.compareTo(ClientProfile.Version.MC1122) > 0) { if (version.compareTo(ClientProfile.Version.MC1122) > 0) {
jvmArgs.add("-Djava.library.path=natives"); jvmArgs.add("-Djava.library.path=natives");
if(optionContains(options, MakeProfileOption.FORGE)) { if (optionContains(options, MakeProfileOption.FORGE)) {
builder.setClassLoaderConfig(ClientProfile.ClassLoaderConfig.AGENT); builder.setClassLoaderConfig(ClientProfile.ClassLoaderConfig.AGENT);
} }
OptionalFile optionalMacOs = new OptionalFile(); OptionalFile optionalMacOs = new OptionalFile();
optionalMacOs.name = "MacOSArgs"; optionalMacOs.name = "MacOSArgs";
optionalMacOs.actions = new ArrayList<>(1); optionalMacOs.actions = new ArrayList<>(1);
optionalMacOs.actions.add(new OptionalActionJvmArgs(List.of("-XstartOnFirstThread"))); optionalMacOs.actions.add(new OptionalActionJvmArgs(List.of("-XstartOnFirstThread")));
optionalMacOs.triggers = new OptionalTrigger[]{ new OptionalTrigger(OptionalTrigger.TriggerType.OS_TYPE, 2) }; optionalMacOs.triggers = new OptionalTrigger[]{new OptionalTrigger(OptionalTrigger.TriggerType.OS_TYPE, 2)};
optionals.add(optionalMacOs); optionals.add(optionalMacOs);
} }
jvmArgs.add("-Dfml.ignorePatchDiscrepancies=true"); jvmArgs.add("-Dfml.ignorePatchDiscrepancies=true");
@ -74,14 +68,14 @@ public static ClientProfile makeProfile(ClientProfile.Version version, String ti
builder.setJvmArgs(jvmArgs); builder.setJvmArgs(jvmArgs);
builder.setUpdateOptional(optionals); builder.setUpdateOptional(optionals);
List<String> clientArgs = new ArrayList<>(); List<String> clientArgs = new ArrayList<>();
if(optionContains(options, MakeProfileOption.LAUNCHWRAPPER)) { if (optionContains(options, MakeProfileOption.LAUNCHWRAPPER)) {
if(optionContains(options, MakeProfileOption.LITELOADER)) { if (optionContains(options, MakeProfileOption.LITELOADER)) {
clientArgs.add("--tweakClass"); clientArgs.add("--tweakClass");
clientArgs.add("com.mumfrey.liteloader.launch.LiteLoaderTweaker"); clientArgs.add("com.mumfrey.liteloader.launch.LiteLoaderTweaker");
} }
if(optionContains(options, MakeProfileOption.FORGE)) { if (optionContains(options, MakeProfileOption.FORGE)) {
clientArgs.add("--tweakClass"); clientArgs.add("--tweakClass");
if(version.compareTo(ClientProfile.Version.MC1710) > 0) { if (version.compareTo(ClientProfile.Version.MC1710) > 0) {
clientArgs.add("net.minecraftforge.fml.common.launcher.FMLTweaker"); clientArgs.add("net.minecraftforge.fml.common.launcher.FMLTweaker");
} else { } else {
clientArgs.add("cpw.mods.fml.common.launcher.FMLTweaker"); clientArgs.add("cpw.mods.fml.common.launcher.FMLTweaker");
@ -98,7 +92,7 @@ private static boolean optionContains(MakeProfileOption[] options, MakeProfileOp
} }
public static String getMainClassByVersion(ClientProfile.Version version, MakeProfileOption... options) { public static String getMainClassByVersion(ClientProfile.Version version, MakeProfileOption... options) {
if(optionContains(options, MakeProfileOption.LAUNCHWRAPPER)) { if (optionContains(options, MakeProfileOption.LAUNCHWRAPPER)) {
return "net.minecraft.launchwrapper.Launch"; return "net.minecraft.launchwrapper.Launch";
} }
return "net.minecraft.client.main.Main"; return "net.minecraft.client.main.Main";
@ -106,13 +100,13 @@ public static String getMainClassByVersion(ClientProfile.Version version, MakePr
public static MakeProfileOption[] getMakeProfileOptionsFromDir(Path dir, ClientProfile.Version version) { public static MakeProfileOption[] getMakeProfileOptionsFromDir(Path dir, ClientProfile.Version version) {
List<MakeProfileOption> options = new ArrayList<>(2); List<MakeProfileOption> options = new ArrayList<>(2);
if(Files.exists(dir.resolve("forge.jar"))) { if (Files.exists(dir.resolve("forge.jar"))) {
options.add(MakeProfileOption.FORGE); options.add(MakeProfileOption.FORGE);
} }
if(Files.exists(dir.resolve("liteloader.jar"))) { if (Files.exists(dir.resolve("liteloader.jar"))) {
options.add(MakeProfileOption.LITELOADER); options.add(MakeProfileOption.LITELOADER);
} }
if(version.compareTo(ClientProfile.Version.MC1122) <= 0) { if (version.compareTo(ClientProfile.Version.MC1122) <= 0) {
options.add(MakeProfileOption.LAUNCHWRAPPER); options.add(MakeProfileOption.LAUNCHWRAPPER);
} }
return options.toArray(new MakeProfileOption[0]); return options.toArray(new MakeProfileOption[0]);
@ -191,4 +185,8 @@ public void invoke(String... args) throws Exception {
server.syncProfilesDir(); server.syncProfilesDir();
} }
} }
public enum MakeProfileOption {
LAUNCHWRAPPER, VANILLA, FORGE, FABRIC, LITELOADER
}
} }

View file

@ -4,12 +4,12 @@
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
public final class SyncBinariesCommand extends Command { public final class SyncBinariesCommand extends Command {
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
public SyncBinariesCommand(LaunchServer server) { public SyncBinariesCommand(LaunchServer server) {
super(server); super(server);
} }

View file

@ -4,12 +4,12 @@
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
public final class SyncProfilesCommand extends Command { public final class SyncProfilesCommand extends Command {
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
public SyncProfilesCommand(LaunchServer server) { public SyncProfilesCommand(LaunchServer server) {
super(server); super(server);
} }

View file

@ -4,7 +4,6 @@
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;

View file

@ -4,7 +4,6 @@
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
import java.util.Collections; import java.util.Collections;

View file

@ -9,7 +9,6 @@
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.command.CommandException; import pro.gravit.utils.command.CommandException;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.nio.file.Files; import java.nio.file.Files;

View file

@ -8,13 +8,13 @@
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.launchermodules.LauncherModuleLoader; import pro.gravit.launchserver.launchermodules.LauncherModuleLoader;
import pro.gravit.utils.helper.LogHelper;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.Arrays; import java.util.Arrays;
public class ModulesCommand extends Command { public class ModulesCommand extends Command {
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
public ModulesCommand(LaunchServer server) { public ModulesCommand(LaunchServer server) {
super(server); super(server);
} }
@ -37,7 +37,7 @@ public void invoke(String... args) {
logger.info("[MODULE] {} v: {} p: {} deps: {} sig: {}", info.name, info.version.getVersionString(), info.priority, Arrays.toString(info.dependencies), checkStatus == null ? "null" : checkStatus.type); logger.info("[MODULE] {} v: {} p: {} deps: {} sig: {}", info.name, info.version.getVersionString(), info.priority, Arrays.toString(info.dependencies), checkStatus == null ? "null" : checkStatus.type);
printCheckStatusInfo(checkStatus); printCheckStatusInfo(checkStatus);
} }
for(LauncherModuleLoader.ModuleEntity entity : server.launcherModuleLoader.launcherModules) { for (LauncherModuleLoader.ModuleEntity entity : server.launcherModuleLoader.launcherModules) {
LauncherTrustManager.CheckClassResult checkStatus = entity.checkResult; LauncherTrustManager.CheckClassResult checkStatus = entity.checkResult;
logger.info("[LAUNCHER MODULE] {} sig: {}", entity.path.getFileName().toString(), checkStatus == null ? "null" : checkStatus.type); logger.info("[LAUNCHER MODULE] {} sig: {}", entity.path.getFileName().toString(), checkStatus == null ? "null" : checkStatus.type);
printCheckStatusInfo(checkStatus); printCheckStatusInfo(checkStatus);

View file

@ -8,7 +8,6 @@
import pro.gravit.launchserver.socket.WebSocketService; import pro.gravit.launchserver.socket.WebSocketService;
import pro.gravit.launchserver.socket.handlers.WebSocketFrameHandler; import pro.gravit.launchserver.socket.handlers.WebSocketFrameHandler;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.util.Base64; import java.util.Base64;
@ -34,7 +33,7 @@ public void invoke(String... args) {
WebSocketService service = server.nettyServerSocketHandler.nettyServer.service; WebSocketService service = server.nettyServerSocketHandler.nettyServer.service;
service.channels.forEach((channel -> { service.channels.forEach((channel -> {
WebSocketFrameHandler frameHandler = channel.pipeline().get(WebSocketFrameHandler.class); WebSocketFrameHandler frameHandler = channel.pipeline().get(WebSocketFrameHandler.class);
if(frameHandler == null) { if (frameHandler == null) {
logger.info("Channel {}", IOHelper.getIP(channel.remoteAddress())); logger.info("Channel {}", IOHelper.getIP(channel.remoteAddress()));
return; return;
} }

View file

@ -3,13 +3,11 @@
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher; import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.NeedGarbageCollection;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.components.Component; import pro.gravit.launchserver.components.Component;
import pro.gravit.utils.command.SubCommand; import pro.gravit.utils.command.SubCommand;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.Reader; import java.io.Reader;
import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles;
@ -25,6 +23,28 @@ public ComponentCommand(LaunchServer server) {
childCommands.put("load", new LoadCommand()); childCommands.put("load", new LoadCommand());
} }
@Override
public String getArgsDescription() {
return "[action] [component name] [more args]";
}
@Override
public String getUsageDescription() {
return "component manager";
}
public void printHelp() {
logger.info("Print help for component:");
logger.info("component unload [componentName]");
logger.info("component load [componentName] [filename]");
logger.info("component gc [componentName]");
}
@Override
public void invoke(String... args) throws Exception {
invokeSubcommands(args);
}
private class UnloadCommand extends SubCommand { private class UnloadCommand extends SubCommand {
public UnloadCommand() { public UnloadCommand() {
super("[componentName]", "Unload component"); super("[componentName]", "Unload component");
@ -47,6 +67,7 @@ public void invoke(String... args) throws Exception {
logger.info("Component %s unloaded. Use 'config launchserver save' to save changes"); logger.info("Component %s unloaded. Use 'config launchserver save' to save changes");
} }
} }
private class LoadCommand extends SubCommand { private class LoadCommand extends SubCommand {
public LoadCommand() { public LoadCommand() {
super("[componentName] [componentType] (json file)", "Load component"); super("[componentName] [componentType] (json file)", "Load component");
@ -57,13 +78,13 @@ public void invoke(String... args) throws Exception {
verifyArgs(args, 2); verifyArgs(args, 2);
String componentName = args[0]; String componentName = args[0];
Class<? extends Component> componentClass = Component.providers.getClass(args[1]); Class<? extends Component> componentClass = Component.providers.getClass(args[1]);
if(componentClass == null) { if (componentClass == null) {
logger.error("Component type {} not registered", componentName); logger.error("Component type {} not registered", componentName);
return; return;
} }
try { try {
Component component; Component component;
if(args.length > 2) { if (args.length > 2) {
try (Reader reader = IOHelper.newReader(Paths.get(args[2]))) { try (Reader reader = IOHelper.newReader(Paths.get(args[2]))) {
component = Launcher.gsonManager.configGson.fromJson(reader, componentClass); component = Launcher.gsonManager.configGson.fromJson(reader, componentClass);
} }
@ -79,26 +100,4 @@ public void invoke(String... args) throws Exception {
} }
} }
} }
@Override
public String getArgsDescription() {
return "[action] [component name] [more args]";
}
@Override
public String getUsageDescription() {
return "component manager";
}
public void printHelp() {
logger.info("Print help for component:");
logger.info("component unload [componentName]");
logger.info("component load [componentName] [filename]");
logger.info("component gc [componentName]");
}
@Override
public void invoke(String... args) throws Exception {
invokeSubcommands(args);
}
} }

View file

@ -25,7 +25,7 @@ public String getUsageDescription() {
public void invoke(String... args) throws Exception { public void invoke(String... args) throws Exception {
verifyArgs(args, 2); verifyArgs(args, 2);
NotificationEvent event; NotificationEvent event;
if(args.length < 3) { if (args.length < 3) {
event = new NotificationEvent(args[0], args[1]); event = new NotificationEvent(args[0], args[1]);
} else { } else {
event = new NotificationEvent(args[0], args[1], Enum.valueOf(NotificationEvent.NotificationType.class, args[2])); event = new NotificationEvent(args[0], args[1], Enum.valueOf(NotificationEvent.NotificationType.class, args[2]));

View file

@ -5,7 +5,6 @@
import pro.gravit.launcher.request.management.PingServerReportRequest; import pro.gravit.launcher.request.management.PingServerReportRequest;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.LogHelper;
public class PingServersCommand extends Command { public class PingServersCommand extends Command {
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();

View file

@ -2,7 +2,6 @@
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.fusesource.jansi.Ansi;
import pro.gravit.launcher.profiles.ClientProfile; import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.handler.MemoryAuthHandler; import pro.gravit.launchserver.auth.handler.MemoryAuthHandler;
@ -13,14 +12,12 @@
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.components.ProGuardComponent; import pro.gravit.launchserver.components.ProGuardComponent;
import pro.gravit.launchserver.config.LaunchServerConfig; import pro.gravit.launchserver.config.LaunchServerConfig;
import pro.gravit.utils.helper.FormatHelper;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.JVMHelper; import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper; import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermission;
@ -198,38 +195,38 @@ public void invoke(String... args) {
} }
//Linux permissions check //Linux permissions check
if(JVMHelper.OS_TYPE == JVMHelper.OS.LINUX) { if (JVMHelper.OS_TYPE == JVMHelper.OS.LINUX) {
try { try {
int uid = 0, gid = 0; int uid = 0, gid = 0;
String[] status = new String(IOHelper.read(Paths.get("/proc/self/status"))).split("\n"); String[] status = new String(IOHelper.read(Paths.get("/proc/self/status"))).split("\n");
for(String line : status) { for (String line : status) {
String[] parts = line.split(":"); String[] parts = line.split(":");
if(parts.length == 0) continue; if (parts.length == 0) continue;
if(parts[0].trim().equalsIgnoreCase("Uid")) { if (parts[0].trim().equalsIgnoreCase("Uid")) {
String[] words = parts[1].trim().split(" "); String[] words = parts[1].trim().split(" ");
uid = Integer.parseInt(words[0]); uid = Integer.parseInt(words[0]);
if(Integer.parseInt(words[0]) == 0 || Integer.parseInt(words[0]) == 0) { if (Integer.parseInt(words[0]) == 0 || Integer.parseInt(words[0]) == 0) {
logger.error("The process is started as root! It is not recommended"); logger.error("The process is started as root! It is not recommended");
} }
} }
if(parts[0].trim().equalsIgnoreCase("Gid")) { if (parts[0].trim().equalsIgnoreCase("Gid")) {
String[] words = parts[1].trim().split(" "); String[] words = parts[1].trim().split(" ");
gid = Integer.parseInt(words[0]); gid = Integer.parseInt(words[0]);
if(Integer.parseInt(words[0]) == 0 || Integer.parseInt(words[0]) == 0) { if (Integer.parseInt(words[0]) == 0 || Integer.parseInt(words[0]) == 0) {
logger.error("The process is started as root group! It is not recommended"); logger.error("The process is started as root group! It is not recommended");
} }
} }
} }
if(checkOtherWriteAccess(IOHelper.getCodeSource(LaunchServer.class))) { if (checkOtherWriteAccess(IOHelper.getCodeSource(LaunchServer.class))) {
logger.warn("Write access to LaunchServer.jar. Please use 'chmod 755 LaunchServer.jar'"); logger.warn("Write access to LaunchServer.jar. Please use 'chmod 755 LaunchServer.jar'");
} }
if(Files.exists(server.dir.resolve("private.key")) && checkOtherReadOrWriteAccess(server.dir.resolve("private.key"))) { if (Files.exists(server.dir.resolve("private.key")) && checkOtherReadOrWriteAccess(server.dir.resolve("private.key"))) {
logger.warn("Write or read access to private.key. Please use 'chmod 600 private.key'"); logger.warn("Write or read access to private.key. Please use 'chmod 600 private.key'");
} }
if(Files.exists(server.dir.resolve("LaunchServerConfig.json")) && checkOtherReadOrWriteAccess(server.dir.resolve("LaunchServerConfig.json"))) { if (Files.exists(server.dir.resolve("LaunchServerConfig.json")) && checkOtherReadOrWriteAccess(server.dir.resolve("LaunchServerConfig.json"))) {
logger.warn("Write or read access to LaunchServerConfig.json. Please use 'chmod 600 LaunchServerConfig.json'"); logger.warn("Write or read access to LaunchServerConfig.json. Please use 'chmod 600 LaunchServerConfig.json'");
} }
if(Files.exists(server.dir.resolve("LaunchServerRuntimeConfig.json")) && checkOtherReadOrWriteAccess(server.dir.resolve("LaunchServerRuntimeConfig.json"))) { if (Files.exists(server.dir.resolve("LaunchServerRuntimeConfig.json")) && checkOtherReadOrWriteAccess(server.dir.resolve("LaunchServerRuntimeConfig.json"))) {
logger.warn("Write or read access to LaunchServerRuntimeConfig.json. Please use 'chmod 600 LaunchServerRuntimeConfig.json'"); logger.warn("Write or read access to LaunchServerRuntimeConfig.json. Please use 'chmod 600 LaunchServerRuntimeConfig.json'");
} }
} catch (IOException e) { } catch (IOException e) {
@ -238,10 +235,12 @@ public void invoke(String... args) {
} }
logger.info("Check completed"); logger.info("Check completed");
} }
public boolean checkOtherWriteAccess(Path file) throws IOException { public boolean checkOtherWriteAccess(Path file) throws IOException {
Set<PosixFilePermission> permissionSet = Files.getPosixFilePermissions(file); Set<PosixFilePermission> permissionSet = Files.getPosixFilePermissions(file);
return permissionSet.contains(PosixFilePermission.OTHERS_WRITE); return permissionSet.contains(PosixFilePermission.OTHERS_WRITE);
} }
public boolean checkOtherReadOrWriteAccess(Path file) throws IOException { public boolean checkOtherReadOrWriteAccess(Path file) throws IOException {
Set<PosixFilePermission> permissionSet = Files.getPosixFilePermissions(file); Set<PosixFilePermission> permissionSet = Files.getPosixFilePermissions(file);
return permissionSet.contains(PosixFilePermission.OTHERS_WRITE) || permissionSet.contains(PosixFilePermission.OTHERS_READ); return permissionSet.contains(PosixFilePermission.OTHERS_WRITE) || permissionSet.contains(PosixFilePermission.OTHERS_READ);

View file

@ -8,7 +8,6 @@
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.command.CommandHandler; import pro.gravit.utils.command.CommandHandler;
import pro.gravit.utils.helper.JVMHelper; import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper;
public class ServerStatusCommand extends Command { public class ServerStatusCommand extends Command {
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();

View file

@ -6,7 +6,6 @@
import pro.gravit.launchserver.binary.tasks.SignJarTask; import pro.gravit.launchserver.binary.tasks.SignJarTask;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
import java.nio.file.*; import java.nio.file.*;

View file

@ -5,7 +5,6 @@
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.binary.tasks.SignJarTask; import pro.gravit.launchserver.binary.tasks.SignJarTask;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.LogHelper;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;

View file

@ -6,7 +6,6 @@
import pro.gravit.launchserver.Reconfigurable; import pro.gravit.launchserver.Reconfigurable;
import pro.gravit.utils.command.Command; import pro.gravit.utils.command.Command;
import pro.gravit.utils.command.SubCommand; import pro.gravit.utils.command.SubCommand;
import pro.gravit.utils.helper.LogHelper;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -14,9 +13,9 @@
import java.util.Map; import java.util.Map;
public abstract class AbstractLimiter<T> extends Component implements NeedGarbageCollection, Reconfigurable { public abstract class AbstractLimiter<T> extends Component implements NeedGarbageCollection, Reconfigurable {
private transient final Logger logger = LogManager.getLogger();
public final List<T> exclude = new ArrayList<>(); public final List<T> exclude = new ArrayList<>();
protected final transient Map<T, LimitEntry> map = new HashMap<>(); protected final transient Map<T, LimitEntry> map = new HashMap<>();
private transient final Logger logger = LogManager.getLogger();
public int rateLimit; public int rateLimit;
public int rateLimitMillis; public int rateLimitMillis;

View file

@ -7,7 +7,10 @@
import pro.gravit.launchserver.binary.tasks.LauncherBuildTask; import pro.gravit.launchserver.binary.tasks.LauncherBuildTask;
import pro.gravit.utils.command.Command; import pro.gravit.utils.command.Command;
import pro.gravit.utils.command.SubCommand; import pro.gravit.utils.command.SubCommand;
import pro.gravit.utils.helper.*; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.SecurityHelper;
import pro.gravit.utils.helper.UnpackHelper;
import proguard.Configuration; import proguard.Configuration;
import proguard.ConfigurationParser; import proguard.ConfigurationParser;
import proguard.ParseException; import proguard.ParseException;
@ -20,9 +23,13 @@
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.*; import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class ProGuardComponent extends Component implements AutoCloseable, Reconfigurable { public class ProGuardComponent extends Component implements AutoCloseable, Reconfigurable {
private transient static final Logger logger = LogManager.getLogger();
public String modeAfter = "MainBuild"; public String modeAfter = "MainBuild";
public String dir = "proguard"; public String dir = "proguard";
public boolean enabled = true; public boolean enabled = true;
@ -30,7 +37,40 @@ public class ProGuardComponent extends Component implements AutoCloseable, Recon
public transient ProguardConf proguardConf; public transient ProguardConf proguardConf;
private transient LaunchServer launchServer; private transient LaunchServer launchServer;
private transient ProGuardBuildTask buildTask; private transient ProGuardBuildTask buildTask;
private transient static final Logger logger = LogManager.getLogger();
public static boolean checkFXJMods(Path path) {
if (!IOHelper.exists(path.resolve("javafx.base.jmod")))
return false;
if (!IOHelper.exists(path.resolve("javafx.graphics.jmod")))
return false;
return IOHelper.exists(path.resolve("javafx.controls.jmod"));
}
public static boolean checkJMods(Path path) {
return IOHelper.exists(path.resolve("java.base.jmod"));
}
public static Path tryFindOpenJFXPath(Path jvmDir) {
String dirName = jvmDir.getFileName().toString();
Path parent = jvmDir.getParent();
if (parent == null) return null;
Path archJFXPath = parent.resolve(dirName.replace("openjdk", "openjfx")).resolve("jmods");
if (Files.isDirectory(archJFXPath)) {
return archJFXPath;
}
Path arch2JFXPath = parent.resolve(dirName.replace("jdk", "openjfx")).resolve("jmods");
if (Files.isDirectory(arch2JFXPath)) {
return arch2JFXPath;
}
if (JVMHelper.OS_TYPE == JVMHelper.OS.LINUX) {
Path debianJfxPath = Paths.get("/usr/share/openjfx/jmods");
if (Files.isDirectory(debianJfxPath)) {
return debianJfxPath;
}
}
return null;
}
@Override @Override
public void init(LaunchServer launchServer) { public void init(LaunchServer launchServer) {
this.launchServer = launchServer; this.launchServer = launchServer;
@ -41,7 +81,7 @@ public void init(LaunchServer launchServer) {
@Override @Override
public void close() throws Exception { public void close() throws Exception {
if(launchServer != null && buildTask != null) { if (launchServer != null && buildTask != null) {
launchServer.launcherBinary.tasks.remove(buildTask); launchServer.launcherBinary.tasks.remove(buildTask);
} }
} }
@ -93,15 +133,14 @@ public Path process(Path inputFile) throws IOException {
Path outputJar = server.launcherBinary.nextLowerPath(this); Path outputJar = server.launcherBinary.nextLowerPath(this);
if (component.enabled) { if (component.enabled) {
Configuration proguard_cfg = new Configuration(); Configuration proguard_cfg = new Configuration();
if(!checkJMods(IOHelper.JVM_DIR.resolve("jmods"))) { if (!checkJMods(IOHelper.JVM_DIR.resolve("jmods"))) {
logger.error("Java path: {} is not JDK! Please install JDK", IOHelper.JVM_DIR); logger.error("Java path: {} is not JDK! Please install JDK", IOHelper.JVM_DIR);
} }
Path jfxPath = tryFindOpenJFXPath(IOHelper.JVM_DIR); Path jfxPath = tryFindOpenJFXPath(IOHelper.JVM_DIR);
if(checkFXJMods(IOHelper.JVM_DIR.resolve("jmods"))) { if (checkFXJMods(IOHelper.JVM_DIR.resolve("jmods"))) {
logger.debug("JavaFX jmods resolved in JDK path"); logger.debug("JavaFX jmods resolved in JDK path");
jfxPath = null; jfxPath = null;
} } else if (jfxPath != null && checkFXJMods(jfxPath)) {
else if(jfxPath != null && checkFXJMods(jfxPath)) {
logger.debug("JMods resolved in {}", jfxPath.toString()); logger.debug("JMods resolved in {}", jfxPath.toString());
} else { } else {
logger.error("JavaFX jmods not found. May be install OpenJFX?"); logger.error("JavaFX jmods not found. May be install OpenJFX?");
@ -126,39 +165,6 @@ public boolean allowDelete() {
} }
} }
public static boolean checkFXJMods(Path path) {
if (!IOHelper.exists(path.resolve("javafx.base.jmod")))
return false;
if (!IOHelper.exists(path.resolve("javafx.graphics.jmod")))
return false;
return IOHelper.exists(path.resolve("javafx.controls.jmod"));
}
public static boolean checkJMods(Path path) {
return IOHelper.exists(path.resolve("java.base.jmod"));
}
public static Path tryFindOpenJFXPath(Path jvmDir) {
String dirName = jvmDir.getFileName().toString();
Path parent = jvmDir.getParent();
if(parent == null) return null;
Path archJFXPath = parent.resolve(dirName.replace("openjdk", "openjfx")).resolve("jmods");
if(Files.isDirectory(archJFXPath)) {
return archJFXPath;
}
Path arch2JFXPath = parent.resolve(dirName.replace("jdk", "openjfx")).resolve("jmods");
if(Files.isDirectory(arch2JFXPath)) {
return arch2JFXPath;
}
if(JVMHelper.OS_TYPE == JVMHelper.OS.LINUX) {
Path debianJfxPath = Paths.get("/usr/share/openjfx/jmods");
if(Files.isDirectory(debianJfxPath)) {
return debianJfxPath;
}
}
return null;
}
public static class ProguardConf { public static class ProguardConf {
public static final String[] JAVA9_OPTS = new String[]{ public static final String[] JAVA9_OPTS = new String[]{
"-libraryjars '<java.home>/jmods/'" "-libraryjars '<java.home>/jmods/'"
@ -205,8 +211,8 @@ public String[] buildConfig(Path inputJar, Path outputJar, Path[] jfxPath) {
confStrs.add("-injar '" + inputJar.toAbsolutePath() + "'"); confStrs.add("-injar '" + inputJar.toAbsolutePath() + "'");
confStrs.add("-outjar '" + outputJar.toAbsolutePath() + "'"); confStrs.add("-outjar '" + outputJar.toAbsolutePath() + "'");
Collections.addAll(confStrs, JAVA9_OPTS); Collections.addAll(confStrs, JAVA9_OPTS);
if(jfxPath != null) { if (jfxPath != null) {
for(Path path : jfxPath) { for (Path path : jfxPath) {
confStrs.add(String.format("-libraryjars '%s'", path.toAbsolutePath())); confStrs.add(String.format("-libraryjars '%s'", path.toAbsolutePath()));
} }
} }

View file

@ -23,7 +23,6 @@
import pro.gravit.launchserver.dao.provider.DaoProvider; import pro.gravit.launchserver.dao.provider.DaoProvider;
import pro.gravit.utils.Version; import pro.gravit.utils.Version;
import pro.gravit.utils.helper.JVMHelper; import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.File; import java.io.File;
import java.util.Arrays; import java.util.Arrays;
@ -31,6 +30,7 @@
import java.util.Map; import java.util.Map;
public final class LaunchServerConfig { public final class LaunchServerConfig {
private transient final Logger logger = LogManager.getLogger();
public String projectName; public String projectName;
public String[] mirrors; public String[] mirrors;
public String binaryName; public String binaryName;
@ -40,7 +40,6 @@ public final class LaunchServerConfig {
@Deprecated @Deprecated
public DaoProvider dao; public DaoProvider dao;
public SessionStorage sessions; public SessionStorage sessions;
// Handlers & Providers // Handlers & Providers
public ProtectHandler protectHandler; public ProtectHandler protectHandler;
public Map<String, Component> components; public Map<String, Component> components;
@ -51,7 +50,6 @@ public final class LaunchServerConfig {
public String startScript; public String startScript;
private transient LaunchServer server = null; private transient LaunchServer server = null;
private transient AuthProviderPair authDefault; private transient AuthProviderPair authDefault;
private transient final Logger logger = LogManager.getLogger();
public static LaunchServerConfig getDefault(LaunchServer.LaunchServerEnv env) { public static LaunchServerConfig getDefault(LaunchServer.LaunchServerEnv env) {
LaunchServerConfig newConfig = new LaunchServerConfig(); LaunchServerConfig newConfig = new LaunchServerConfig();
@ -157,7 +155,7 @@ public void verify() {
throw new NullPointerException("AuthProviderPair`s count should be at least one"); throw new NullPointerException("AuthProviderPair`s count should be at least one");
} }
if(dao != null) { if (dao != null) {
logger.warn("DAO deprecated and may be remove in future release"); logger.warn("DAO deprecated and may be remove in future release");
} }

View file

@ -2,16 +2,15 @@
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper; import pro.gravit.utils.helper.SecurityHelper;
public class LaunchServerRuntimeConfig { public class LaunchServerRuntimeConfig {
private transient final Logger logger = LogManager.getLogger();
public String passwordEncryptKey; public String passwordEncryptKey;
public String runtimeEncryptKey; public String runtimeEncryptKey;
public String oemUnlockKey; public String oemUnlockKey;
public String registerApiKey; public String registerApiKey;
public String clientCheckSecret; public String clientCheckSecret;
private transient final Logger logger = LogManager.getLogger();
public void verify() { public void verify() {
if (passwordEncryptKey == null) logger.error("[RuntimeConfig] passwordEncryptKey must not be null"); if (passwordEncryptKey == null) logger.error("[RuntimeConfig] passwordEncryptKey must not be null");

View file

@ -17,37 +17,16 @@
import java.util.Set; import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
@Plugin(name="LogCollect", category="Core", elementType="appender", printObject=true) @Plugin(name = "LogCollect", category = "Core", elementType = "appender", printObject = true)
public class LogAppender extends AbstractAppender { public class LogAppender extends AbstractAppender {
private static volatile LogAppender INSTANCE; private static volatile LogAppender INSTANCE;
private final Set<Consumer<LogEvent>> set = new HashSet<>(); private final Set<Consumer<LogEvent>> set = new HashSet<>();
public LogAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions, Property[] properties) { public LogAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions, Property[] properties) {
super(name, filter, layout, ignoreExceptions, properties); super(name, filter, layout, ignoreExceptions, properties);
INSTANCE = this; INSTANCE = this;
} }
@Override
public void append(LogEvent event) {
try {
for(Consumer<LogEvent> consumer : set) {
consumer.accept(event);
}
} catch (Throwable e) {
if(!ignoreExceptions()) {
throw new AppenderLoggingException(e);
}
}
}
public void addListener(Consumer<LogEvent> consumer) {
set.add(consumer);
}
public void removeListener(Consumer<LogEvent> consumer) {
set.remove(consumer);
}
public static LogAppender getInstance() { public static LogAppender getInstance() {
return INSTANCE; return INSTANCE;
} }
@ -67,4 +46,26 @@ public static LogAppender createAppender(
} }
return new LogAppender(name, filter, layout, true, Property.EMPTY_ARRAY); return new LogAppender(name, filter, layout, true, Property.EMPTY_ARRAY);
} }
@Override
public void append(LogEvent event) {
try {
for (Consumer<LogEvent> consumer : set) {
consumer.accept(event);
}
} catch (Throwable e) {
if (!ignoreExceptions()) {
throw new AppenderLoggingException(e);
}
}
}
public void addListener(Consumer<LogEvent> consumer) {
set.add(consumer);
}
public void removeListener(Consumer<LogEvent> consumer) {
set.remove(consumer);
}
} }

View file

@ -9,7 +9,6 @@
import pro.gravit.launchserver.asm.InjectClassAcceptor; import pro.gravit.launchserver.asm.InjectClassAcceptor;
import pro.gravit.launchserver.binary.tasks.MainBuildTask; import pro.gravit.launchserver.binary.tasks.MainBuildTask;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
@ -124,7 +123,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
Class<? extends LauncherModule> mainClazz = (Class<? extends LauncherModule>) classLoader.loadClass(entity.moduleMainClass); Class<? extends LauncherModule> mainClazz = (Class<? extends LauncherModule>) classLoader.loadClass(entity.moduleMainClass);
entity.checkResult = server.modulesManager.checkModuleClass(mainClazz); entity.checkResult = server.modulesManager.checkModuleClass(mainClazz);
} catch (Throwable e) { } catch (Throwable e) {
if(e instanceof ClassNotFoundException || e instanceof NoClassDefFoundError) { if (e instanceof ClassNotFoundException || e instanceof NoClassDefFoundError) {
logger.error("Module-MainClass in module {} incorrect", file.toString()); logger.error("Module-MainClass in module {} incorrect", file.toString());
} else { } else {
logger.error(e); logger.error(e);

View file

@ -3,7 +3,6 @@
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.utils.command.Command; import pro.gravit.utils.command.Command;
import pro.gravit.utils.helper.LogHelper;
public class SyncLauncherModulesCommand extends Command { public class SyncLauncherModulesCommand extends Command {
private final LauncherModuleLoader mod; private final LauncherModuleLoader mod;

View file

@ -38,6 +38,7 @@ public AuthManager(LaunchServer server) {
/** /**
* Create AuthContext * Create AuthContext
*
* @return AuthContext instance * @return AuthContext instance
*/ */
public AuthResponse.AuthContext makeAuthContext(Client client, AuthResponse.ConnectTypes authType, AuthProviderPair pair, String login, String profileName, String ip) { public AuthResponse.AuthContext makeAuthContext(Client client, AuthResponse.ConnectTypes authType, AuthProviderPair pair, String login, String profileName, String ip) {
@ -49,6 +50,7 @@ public AuthResponse.AuthContext makeAuthContext(Client client, AuthResponse.Conn
/** /**
* Validate auth params ans state * Validate auth params ans state
*
* @param context Auth context * @param context Auth context
* @throws AuthException auth not possible * @throws AuthException auth not possible
*/ */
@ -63,6 +65,187 @@ public void check(AuthResponse.AuthContext context) throws AuthException {
} }
} }
/**
* Full client authorization with password verification
*
* @param context AuthContext
* @param password User password
* @return Access token
*/
public AuthReport auth(AuthResponse.AuthContext context, AuthRequest.AuthPasswordInterface password) throws AuthException {
AuthProviderPair pair = context.pair;
AuthReport report;
if (pair.core == null) {
try {
report = AuthReport.ofMinecraftAccessToken(authWithProviderAndHandler(context, password));
} catch (Exception e) {
if (e instanceof AuthException) throw (AuthException) e;
throw new AuthException("Internal Auth Error. Please contact administrator");
}
} else {
report = authWithCore(context, password);
}
return report;
}
@SuppressWarnings("deprecation")
private String authWithProviderAndHandler(AuthResponse.AuthContext context, AuthRequest.AuthPasswordInterface password) throws Exception {
String accessToken;
context.pair.provider.preAuth(context.login, password, context.ip);
AuthProviderResult aresult = context.pair.provider.auth(context.login, password, context.ip);
UUID uuid;
String username = aresult.username != null ? aresult.username : context.login;
if (aresult instanceof AuthProviderDAOResult) {
context.client.daoObject = ((AuthProviderDAOResult) aresult).daoObject;
}
if (context.authType == AuthResponse.ConnectTypes.CLIENT && server.config.protectHandler.allowGetAccessToken(context)) {
uuid = context.pair.handler.auth(aresult);
accessToken = aresult.accessToken;
} else {
uuid = context.pair.handler.usernameToUUID(aresult.username);
accessToken = null;
}
internalAuth(context.client, context.authType, context.pair, username, uuid, aresult.permissions, false);
return accessToken;
}
private AuthReport authWithCore(AuthResponse.AuthContext context, AuthRequest.AuthPasswordInterface password) throws AuthException {
AuthCoreProvider provider = context.pair.core;
provider.verifyAuth(context);
if (password instanceof AuthOAuthPassword) {
AuthOAuthPassword password1 = (AuthOAuthPassword) password;
UserSession session;
try {
session = provider.getUserSessionByOAuthAccessToken(password1.accessToken);
} catch (AuthCoreProvider.OAuthAccessTokenExpired oAuthAccessTokenExpired) {
throw new AuthException(AuthRequestEvent.OAUTH_TOKEN_EXPIRE);
}
if (session == null) {
throw new AuthException(AuthRequestEvent.OAUTH_TOKEN_INVALID);
}
User user = session.getUser();
context.client.coreObject = user;
context.client.sessionObject = session;
internalAuth(context.client, context.authType, context.pair, user.getUsername(), user.getUUID(), user.getPermissions(), true);
if (context.authType == AuthResponse.ConnectTypes.CLIENT && server.config.protectHandler.allowGetAccessToken(context)) {
return AuthReport.ofMinecraftAccessToken(user.getAccessToken());
}
return AuthReport.ofMinecraftAccessToken(null);
}
User user = provider.getUserByUsername(context.login);
if (user == null) {
throw new AuthException(AuthRequestEvent.USER_NOT_FOUND_ERROR_MESSAGE);
}
AuthCoreProvider.PasswordVerifyReport report = provider.verifyPassword(user, password);
if (report.success) {
UUID uuid = user.getUUID();
AuthReport result;
try {
result = provider.createOAuthSession(user, context, report, context.authType == AuthResponse.ConnectTypes.CLIENT && server.config.protectHandler.allowGetAccessToken(context));
} catch (IOException e) {
logger.error(e);
throw new AuthException("Internal Auth Error");
}
context.client.coreObject = user;
internalAuth(context.client, context.authType, context.pair, user.getUsername(), uuid, user.getPermissions(), result.isUsingOAuth());
return result;
} else {
if (report.needMoreFactor) {
if (report.factors.size() == 1 && report.factors.get(0) == -1) {
throw new AuthException(AuthRequestEvent.TWO_FACTOR_NEED_ERROR_MESSAGE);
}
String message = AuthRequestEvent.ONE_FACTOR_NEED_ERROR_MESSAGE_PREFIX
.concat(report.factors.stream().map(String::valueOf).collect(Collectors.joining(".")));
throw new AuthException(message);
}
throw new AuthException(AuthRequestEvent.WRONG_PASSWORD_ERROR_MESSAGE);
}
}
/**
* Writing authorization information to the Client object
*/
public void internalAuth(Client client, AuthResponse.ConnectTypes authType, AuthProviderPair pair, String username, UUID uuid, ClientPermissions permissions, boolean oauth) {
client.isAuth = true;
client.permissions = permissions;
client.auth_id = pair.name;
client.auth = pair;
client.username = username;
client.type = authType;
client.uuid = uuid;
client.useOAuth = oauth;
if (pair.isUseCore() && client.coreObject == null) {
client.coreObject = pair.core.getUserByUUID(uuid);
}
}
public UUID checkServer(Client client, String username, String serverID) throws IOException {
if (client.auth == null) return null;
if (client.auth.isUseCore()) {
return client.auth.core.checkServer(client, username, serverID);
} else {
return client.auth.handler.checkServer(username, serverID);
}
}
public boolean joinServer(Client client, String username, String accessToken, String serverID) throws IOException {
if (client.auth == null) return false;
if (client.auth.isUseCore()) {
return client.auth.core.joinServer(client, username, accessToken, serverID);
} else {
return client.auth.handler.joinServer(username, accessToken, serverID);
}
}
public AuthRequest.AuthPasswordInterface decryptPassword(AuthRequest.AuthPasswordInterface password) throws AuthException {
if (password instanceof Auth2FAPassword) {
Auth2FAPassword auth2FAPassword = (Auth2FAPassword) password;
auth2FAPassword.firstPassword = tryDecryptPasswordPlain(auth2FAPassword.firstPassword);
auth2FAPassword.secondPassword = tryDecryptPasswordPlain(auth2FAPassword.secondPassword);
} else if (password instanceof AuthMultiPassword) {
AuthMultiPassword multiPassword = (AuthMultiPassword) password;
List<AuthRequest.AuthPasswordInterface> list = new ArrayList<>(multiPassword.list.size());
for (AuthRequest.AuthPasswordInterface p : multiPassword.list) {
list.add(tryDecryptPasswordPlain(p));
}
multiPassword.list = list;
} else {
password = tryDecryptPasswordPlain(password);
}
return password;
}
@SuppressWarnings("deprecation")
private AuthRequest.AuthPasswordInterface tryDecryptPasswordPlain(AuthRequest.AuthPasswordInterface password) throws AuthException {
if (password instanceof AuthECPassword) {
try {
return new AuthPlainPassword(IOHelper.decode(SecurityHelper.decrypt(server.runtime.passwordEncryptKey
, ((AuthECPassword) password).password)));
} catch (Exception ignored) {
throw new AuthException("Password decryption error");
}
}
if (password instanceof AuthAESPassword) {
try {
return new AuthPlainPassword(IOHelper.decode(SecurityHelper.decrypt(server.runtime.passwordEncryptKey
, ((AuthAESPassword) password).password)));
} catch (Exception ignored) {
throw new AuthException("Password decryption error");
}
}
if (password instanceof AuthRSAPassword) {
try {
Cipher cipher = SecurityHelper.newRSADecryptCipher(server.keyAgreementManager.rsaPrivateKey);
return new AuthPlainPassword(
IOHelper.decode(cipher.doFinal(((AuthRSAPassword) password).password))
);
} catch (Exception ignored) {
throw new AuthException("Password decryption error");
}
}
return password;
}
public static class AuthReport { public static class AuthReport {
public final String minecraftAccessToken; public final String minecraftAccessToken;
public final String oauthAccessToken; public final String oauthAccessToken;
@ -92,188 +275,4 @@ public boolean isUsingOAuth() {
return oauthAccessToken != null || oauthRefreshToken != null; return oauthAccessToken != null || oauthRefreshToken != null;
} }
} }
/**
* Full client authorization with password verification
* @param context AuthContext
* @param password User password
* @return Access token
*/
public AuthReport auth(AuthResponse.AuthContext context, AuthRequest.AuthPasswordInterface password) throws AuthException {
AuthProviderPair pair = context.pair;
AuthReport report;
if(pair.core == null) {
try {
report = AuthReport.ofMinecraftAccessToken(authWithProviderAndHandler(context, password));
} catch (Exception e) {
if(e instanceof AuthException) throw (AuthException) e;
throw new AuthException("Internal Auth Error. Please contact administrator");
}
} else {
report = authWithCore(context, password);
}
return report;
}
@SuppressWarnings("deprecation")
private String authWithProviderAndHandler(AuthResponse.AuthContext context, AuthRequest.AuthPasswordInterface password) throws Exception {
String accessToken;
context.pair.provider.preAuth(context.login, password, context.ip);
AuthProviderResult aresult = context.pair.provider.auth(context.login, password, context.ip);
UUID uuid;
String username = aresult.username != null ? aresult.username : context.login;
if (aresult instanceof AuthProviderDAOResult) {
context.client.daoObject = ((AuthProviderDAOResult) aresult).daoObject;
}
if(context.authType == AuthResponse.ConnectTypes.CLIENT && server.config.protectHandler.allowGetAccessToken(context)) {
uuid = context.pair.handler.auth(aresult);
accessToken = aresult.accessToken;
} else {
uuid = context.pair.handler.usernameToUUID(aresult.username);
accessToken = null;
}
internalAuth(context.client, context.authType, context.pair, username, uuid, aresult.permissions, false);
return accessToken;
}
private AuthReport authWithCore(AuthResponse.AuthContext context, AuthRequest.AuthPasswordInterface password) throws AuthException {
AuthCoreProvider provider = context.pair.core;
provider.verifyAuth(context);
if(password instanceof AuthOAuthPassword) {
AuthOAuthPassword password1 = (AuthOAuthPassword) password;
UserSession session;
try {
session = provider.getUserSessionByOAuthAccessToken(password1.accessToken);
} catch (AuthCoreProvider.OAuthAccessTokenExpired oAuthAccessTokenExpired) {
throw new AuthException(AuthRequestEvent.OAUTH_TOKEN_EXPIRE);
}
if(session == null) {
throw new AuthException(AuthRequestEvent.OAUTH_TOKEN_INVALID);
}
User user = session.getUser();
context.client.coreObject = user;
context.client.sessionObject = session;
internalAuth(context.client, context.authType, context.pair, user.getUsername(), user.getUUID(), user.getPermissions(), true);
if(context.authType == AuthResponse.ConnectTypes.CLIENT && server.config.protectHandler.allowGetAccessToken(context)) {
return AuthReport.ofMinecraftAccessToken(user.getAccessToken());
}
return AuthReport.ofMinecraftAccessToken(null);
}
User user = provider.getUserByUsername(context.login);
if(user == null) {
throw new AuthException(AuthRequestEvent.USER_NOT_FOUND_ERROR_MESSAGE);
}
AuthCoreProvider.PasswordVerifyReport report = provider.verifyPassword(user, password);
if(report.success) {
UUID uuid = user.getUUID();
AuthReport result;
try {
result = provider.createOAuthSession(user, context, report, context.authType == AuthResponse.ConnectTypes.CLIENT && server.config.protectHandler.allowGetAccessToken(context));
} catch (IOException e) {
logger.error(e);
throw new AuthException("Internal Auth Error");
}
context.client.coreObject = user;
internalAuth(context.client, context.authType, context.pair, user.getUsername(), uuid, user.getPermissions(), result.isUsingOAuth());
return result;
}
else {
if(report.needMoreFactor) {
if(report.factors.size() == 1 && report.factors.get(0) == -1) {
throw new AuthException(AuthRequestEvent.TWO_FACTOR_NEED_ERROR_MESSAGE);
}
String message = AuthRequestEvent.ONE_FACTOR_NEED_ERROR_MESSAGE_PREFIX
.concat(report.factors.stream().map(String::valueOf).collect(Collectors.joining(".")));
throw new AuthException(message);
}
throw new AuthException(AuthRequestEvent.WRONG_PASSWORD_ERROR_MESSAGE);
}
}
/**
* Writing authorization information to the Client object
*/
public void internalAuth(Client client, AuthResponse.ConnectTypes authType, AuthProviderPair pair, String username, UUID uuid, ClientPermissions permissions, boolean oauth) {
client.isAuth = true;
client.permissions = permissions;
client.auth_id = pair.name;
client.auth = pair;
client.username = username;
client.type = authType;
client.uuid = uuid;
client.useOAuth = oauth;
if(pair.isUseCore() && client.coreObject == null) {
client.coreObject = pair.core.getUserByUUID(uuid);
}
}
public UUID checkServer(Client client, String username, String serverID) throws IOException {
if(client.auth == null) return null;
if(client.auth.isUseCore()) {
return client.auth.core.checkServer(client, username, serverID);
}
else {
return client.auth.handler.checkServer(username, serverID);
}
}
public boolean joinServer(Client client, String username, String accessToken, String serverID) throws IOException {
if(client.auth == null) return false;
if(client.auth.isUseCore()) {
return client.auth.core.joinServer(client, username, accessToken, serverID);
} else {
return client.auth.handler.joinServer(username, accessToken, serverID);
}
}
public AuthRequest.AuthPasswordInterface decryptPassword(AuthRequest.AuthPasswordInterface password) throws AuthException {
if(password instanceof Auth2FAPassword) {
Auth2FAPassword auth2FAPassword = (Auth2FAPassword) password;
auth2FAPassword.firstPassword = tryDecryptPasswordPlain(auth2FAPassword.firstPassword);
auth2FAPassword.secondPassword = tryDecryptPasswordPlain(auth2FAPassword.secondPassword);
}
else if(password instanceof AuthMultiPassword) {
AuthMultiPassword multiPassword = (AuthMultiPassword) password;
List<AuthRequest.AuthPasswordInterface> list = new ArrayList<>(multiPassword.list.size());
for(AuthRequest.AuthPasswordInterface p : multiPassword.list) {
list.add(tryDecryptPasswordPlain(p));
}
multiPassword.list = list;
}
else {
password = tryDecryptPasswordPlain(password);
}
return password;
}
@SuppressWarnings("deprecation")
private AuthRequest.AuthPasswordInterface tryDecryptPasswordPlain(AuthRequest.AuthPasswordInterface password) throws AuthException {
if (password instanceof AuthECPassword) {
try {
return new AuthPlainPassword(IOHelper.decode(SecurityHelper.decrypt(server.runtime.passwordEncryptKey
, ((AuthECPassword) password).password)));
} catch (Exception ignored) {
throw new AuthException("Password decryption error");
}
}
if (password instanceof AuthAESPassword) {
try {
return new AuthPlainPassword(IOHelper.decode(SecurityHelper.decrypt(server.runtime.passwordEncryptKey
, ((AuthAESPassword) password).password)));
} catch (Exception ignored) {
throw new AuthException("Password decryption error");
}
}
if(password instanceof AuthRSAPassword) {
try {
Cipher cipher = SecurityHelper.newRSADecryptCipher(server.keyAgreementManager.rsaPrivateKey);
return new AuthPlainPassword(
IOHelper.decode(cipher.doFinal(((AuthRSAPassword) password).password))
);
} catch (Exception ignored) {
throw new AuthException("Password decryption error");
}
}
return password;
}
} }

View file

@ -25,7 +25,6 @@
import pro.gravit.launcher.LauncherTrustManager; import pro.gravit.launcher.LauncherTrustManager;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.JVMHelper; import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper; import pro.gravit.utils.helper.SecurityHelper;
import java.io.*; import java.io.*;
@ -50,13 +49,13 @@
public class CertificateManager { public class CertificateManager {
public final int validDays = 60; public final int validDays = 60;
public final int minusHours = 6; public final int minusHours = 6;
private transient final Logger logger = LogManager.getLogger();
public X509CertificateHolder ca; public X509CertificateHolder ca;
public AsymmetricKeyParameter caKey; public AsymmetricKeyParameter caKey;
public X509CertificateHolder server; public X509CertificateHolder server;
public AsymmetricKeyParameter serverKey; public AsymmetricKeyParameter serverKey;
public LauncherTrustManager trustManager; public LauncherTrustManager trustManager;
public String orgName; public String orgName;
private transient final Logger logger = LogManager.getLogger();
public X509CertificateHolder generateCertificate(String subjectName, PublicKey subjectPublicKey) throws OperatorCreationException { public X509CertificateHolder generateCertificate(String subjectName, PublicKey subjectPublicKey) throws OperatorCreationException {
SubjectPublicKeyInfo subjectPubKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded()); SubjectPublicKeyInfo subjectPubKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
@ -182,7 +181,7 @@ public void readTrustStore(Path dir) throws IOException, CertificateException {
} }
} else { } else {
if(IOHelper.exists(dir.resolve("GravitCentralRootCA.crt"))) { if (IOHelper.exists(dir.resolve("GravitCentralRootCA.crt"))) {
logger.warn("Found old default certificate - 'GravitCentralRootCA.crt'. Delete..."); logger.warn("Found old default certificate - 'GravitCentralRootCA.crt'. Delete...");
Files.delete(dir.resolve("GravitCentralRootCA.crt")); Files.delete(dir.resolve("GravitCentralRootCA.crt"));
} }

View file

@ -3,12 +3,12 @@
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper; import pro.gravit.utils.helper.SecurityHelper;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
import java.security.*; import java.security.KeyPair;
import java.security.SecureRandom;
import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey; import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateKey;

View file

@ -6,7 +6,6 @@
import pro.gravit.launcher.HTTPRequest; import pro.gravit.launcher.HTTPRequest;
import pro.gravit.utils.HttpDownloader; import pro.gravit.utils.HttpDownloader;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@ -17,8 +16,8 @@
public class MirrorManager { public class MirrorManager {
protected final ArrayList<Mirror> list = new ArrayList<>(); protected final ArrayList<Mirror> list = new ArrayList<>();
private Mirror defaultMirror;
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
private Mirror defaultMirror;
public void addMirror(String mirror) { public void addMirror(String mirror) {
Mirror m = new Mirror(mirror); Mirror m = new Mirror(mirror);

View file

@ -58,7 +58,7 @@ private Client restoreFromString(byte[] data) {
Client result = decompressClient(data); Client result = decompressClient(data);
result.updateAuth(server); result.updateAuth(server);
if (result.auth != null && (result.username != null)) { if (result.auth != null && (result.username != null)) {
if(result.auth.isUseCore()) { if (result.auth.isUseCore()) {
result.coreObject = result.auth.core.getUserByUUID(result.uuid); result.coreObject = result.auth.core.getUserByUUID(result.uuid);
} else { } else {
if (result.auth.handler instanceof RequiredDAO || result.auth.provider instanceof RequiredDAO || result.auth.textureProvider instanceof RequiredDAO) { if (result.auth.handler instanceof RequiredDAO || result.auth.provider instanceof RequiredDAO || result.auth.textureProvider instanceof RequiredDAO) {

View file

@ -85,8 +85,8 @@ public void setSerializableProperty(String name, String value) {
} }
public pro.gravit.launchserver.auth.core.User getUser() { public pro.gravit.launchserver.auth.core.User getUser() {
if(coreObject != null) return coreObject; if (coreObject != null) return coreObject;
if(auth != null && uuid != null && auth.isUseCore()) { if (auth != null && uuid != null && auth.isUseCore()) {
coreObject = auth.core.getUserByUUID(uuid); coreObject = auth.core.getUserByUUID(uuid);
} }
return coreObject; return coreObject;

View file

@ -23,7 +23,6 @@
import pro.gravit.launchserver.socket.handlers.WebSocketFrameHandler; import pro.gravit.launchserver.socket.handlers.WebSocketFrameHandler;
import pro.gravit.launchserver.socket.handlers.fileserver.FileServerHandler; import pro.gravit.launchserver.socket.handlers.fileserver.FileServerHandler;
import pro.gravit.utils.BiHookSet; import pro.gravit.utils.BiHookSet;
import pro.gravit.utils.helper.LogHelper;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;

View file

@ -3,7 +3,6 @@
import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.DefaultThreadFactory;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.utils.helper.LogHelper;
public class NettyThreadFactory extends DefaultThreadFactory { public class NettyThreadFactory extends DefaultThreadFactory {
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
@ -16,7 +15,7 @@ public NettyThreadFactory(String poolName) {
protected Thread newThread(Runnable r, String name) { protected Thread newThread(Runnable r, String name) {
Thread thread = super.newThread(r, name); Thread thread = super.newThread(r, name);
thread.setUncaughtExceptionHandler((th, e) -> { thread.setUncaughtExceptionHandler((th, e) -> {
if(e.getMessage().contains("Connection reset by peer")) { if (e.getMessage().contains("Connection reset by peer")) {
return; return;
} }
logger.error(e); logger.error(e);

View file

@ -38,7 +38,6 @@
import pro.gravit.utils.BiHookSet; import pro.gravit.utils.BiHookSet;
import pro.gravit.utils.ProviderMap; import pro.gravit.utils.ProviderMap;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.UUID; import java.util.UUID;

View file

@ -5,7 +5,6 @@
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.config.LaunchServerConfig; import pro.gravit.launchserver.config.LaunchServerConfig;
import pro.gravit.launchserver.socket.LauncherNettyServer; import pro.gravit.launchserver.socket.LauncherNettyServer;
import pro.gravit.utils.helper.LogHelper;
import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLServerSocketFactory;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
@ -13,10 +12,9 @@
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class NettyServerSocketHandler implements Runnable, AutoCloseable { public final class NettyServerSocketHandler implements Runnable, AutoCloseable {
private transient final LaunchServer server; private transient final LaunchServer server;
private transient final Logger logger = LogManager.getLogger();
@Deprecated @Deprecated
public volatile boolean logConnections = Boolean.getBoolean("launcher.logConnections"); public volatile boolean logConnections = Boolean.getBoolean("launcher.logConnections");
private transient final Logger logger = LogManager.getLogger();
public LauncherNettyServer nettyServer; public LauncherNettyServer nettyServer;
private SSLServerSocketFactory ssf; private SSLServerSocketFactory ssf;

View file

@ -9,7 +9,6 @@
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher; import pro.gravit.launcher.Launcher;
import pro.gravit.launchserver.socket.NettyConnectContext; import pro.gravit.launchserver.socket.NettyConnectContext;
import pro.gravit.utils.helper.LogHelper;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -18,7 +17,6 @@
import java.util.Map; import java.util.Map;
import java.util.TreeSet; import java.util.TreeSet;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
public class NettyWebAPIHandler extends SimpleChannelInboundHandler<FullHttpRequest> { public class NettyWebAPIHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@ -87,7 +85,7 @@ default Map<String, String> getParamsFromUri(String uri) {
continue; continue;
} }
String key = c.substring(0, index); String key = c.substring(0, index);
String value = c.substring(index+1); String value = c.substring(index + 1);
map.put(key, value); map.put(key, value);
} }
return map; return map;

View file

@ -13,7 +13,6 @@
import pro.gravit.launchserver.socket.WebSocketService; import pro.gravit.launchserver.socket.WebSocketService;
import pro.gravit.utils.BiHookSet; import pro.gravit.utils.BiHookSet;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -71,7 +70,7 @@ protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
service.process(ctx, (TextWebSocketFrame) frame, client, context.ip); service.process(ctx, (TextWebSocketFrame) frame, client, context.ip);
} catch (Throwable ex) { } catch (Throwable ex) {
logger.warn("Client {} send invalid request. Connection force closed.", context.ip == null ? IOHelper.getIP(ctx.channel().remoteAddress()) : context.ip); logger.warn("Client {} send invalid request. Connection force closed.", context.ip == null ? IOHelper.getIP(ctx.channel().remoteAddress()) : context.ip);
if(logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
logger.trace("Client message: {}", ((TextWebSocketFrame) frame).text()); logger.trace("Client message: {}", ((TextWebSocketFrame) frame).text());
logger.error(ex); logger.error(ex);
} }
@ -95,7 +94,7 @@ protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
@Override @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception { public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (future != null) future.cancel(true); if (future != null) future.cancel(true);
if(logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
logger.trace("Client {} disconnected", IOHelper.getIP(ctx.channel().remoteAddress())); logger.trace("Client {} disconnected", IOHelper.getIP(ctx.channel().remoteAddress()));
} }
int refCount = client.refCount.decrementAndGet(); int refCount = client.refCount.decrementAndGet();

View file

@ -7,7 +7,6 @@
import io.netty.handler.stream.ChunkedFile; import io.netty.handler.stream.ChunkedFile;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import pro.gravit.launchserver.socket.handlers.ContentType; import pro.gravit.launchserver.socket.handlers.ContentType;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.VerifyHelper; import pro.gravit.utils.helper.VerifyHelper;
import java.io.File; import java.io.File;

View file

@ -5,28 +5,14 @@
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.events.request.AuthRequestEvent; import pro.gravit.launcher.events.request.AuthRequestEvent;
import pro.gravit.launcher.request.auth.AuthRequest; import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.request.auth.password.*;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthException; import pro.gravit.launchserver.auth.AuthException;
import pro.gravit.launchserver.auth.AuthProviderPair; import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.auth.provider.AuthProvider;
import pro.gravit.launchserver.auth.provider.AuthProviderDAOResult;
import pro.gravit.launchserver.auth.provider.AuthProviderResult;
import pro.gravit.launchserver.manangers.AuthManager; import pro.gravit.launchserver.manangers.AuthManager;
import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.response.SimpleResponse; import pro.gravit.launchserver.socket.response.SimpleResponse;
import pro.gravit.launchserver.socket.response.profile.ProfileByUUIDResponse; import pro.gravit.launchserver.socket.response.profile.ProfileByUUIDResponse;
import pro.gravit.utils.HookException; import pro.gravit.utils.HookException;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper;
import pro.gravit.utils.helper.VerifyHelper;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID; import java.util.UUID;
public class AuthResponse extends SimpleResponse { public class AuthResponse extends SimpleResponse {
@ -62,7 +48,7 @@ public void execute(ChannelHandlerContext ctx, Client clientData) throws Excepti
server.authHookManager.preHook.hook(context, clientData); server.authHookManager.preHook.hook(context, clientData);
context.report = server.authManager.auth(context, password); context.report = server.authManager.auth(context, password);
server.authHookManager.postHook.hook(context, clientData); server.authHookManager.postHook.hook(context, clientData);
if(context.report.isUsingOAuth()) { if (context.report.isUsingOAuth()) {
result.oauth = new AuthRequestEvent.OAuthRequestEvent(context.report.oauthAccessToken, context.report.oauthRefreshToken, context.report.oauthExpire); result.oauth = new AuthRequestEvent.OAuthRequestEvent(context.report.oauthAccessToken, context.report.oauthRefreshToken, context.report.oauthExpire);
} else if (getSession) { } else if (getSession) {
if (clientData.session == null) { if (clientData.session == null) {
@ -71,7 +57,7 @@ public void execute(ChannelHandlerContext ctx, Client clientData) throws Excepti
} }
result.session = clientData.session; result.session = clientData.session;
} }
if(context.report.minecraftAccessToken != null) { if (context.report.minecraftAccessToken != null) {
result.accessToken = context.report.minecraftAccessToken; result.accessToken = context.report.minecraftAccessToken;
} }
result.playerProfile = ProfileByUUIDResponse.getProfile(clientData.uuid, clientData.username, client, clientData.auth.textureProvider); result.playerProfile = ProfileByUUIDResponse.getProfile(clientData.uuid, clientData.username, client, clientData.auth.textureProvider);

View file

@ -9,13 +9,12 @@
import pro.gravit.launchserver.socket.response.SimpleResponse; import pro.gravit.launchserver.socket.response.SimpleResponse;
import pro.gravit.launchserver.socket.response.profile.ProfileByUUIDResponse; import pro.gravit.launchserver.socket.response.profile.ProfileByUUIDResponse;
import pro.gravit.utils.HookException; import pro.gravit.utils.HookException;
import pro.gravit.utils.helper.LogHelper;
public class CheckServerResponse extends SimpleResponse { public class CheckServerResponse extends SimpleResponse {
private transient final Logger logger = LogManager.getLogger();
public String serverID; public String serverID;
public String username; public String username;
public String client; public String client;
private transient final Logger logger = LogManager.getLogger();
@Override @Override
public String getType() { public String getType() {

View file

@ -39,7 +39,7 @@ public void execute(ChannelHandlerContext ctx, Client client) {
return; return;
} }
if (username == null) { if (username == null) {
if(client.useOAuth) { if (client.useOAuth) {
WebSocketFrameHandler handler = ctx.pipeline().get(WebSocketFrameHandler.class); WebSocketFrameHandler handler = ctx.pipeline().get(WebSocketFrameHandler.class);
if (handler == null) { if (handler == null) {
sendError("Exit internal error"); sendError("Exit internal error");
@ -48,8 +48,8 @@ public void execute(ChannelHandlerContext ctx, Client client) {
Client newClient = new Client(null); Client newClient = new Client(null);
newClient.checkSign = client.checkSign; newClient.checkSign = client.checkSign;
handler.setClient(newClient); handler.setClient(newClient);
if(exitAll) { if (exitAll) {
if(client.auth instanceof AuthSupportGetSessionsFromUser) { if (client.auth instanceof AuthSupportGetSessionsFromUser) {
AuthSupportGetSessionsFromUser support = (AuthSupportGetSessionsFromUser) client.auth; AuthSupportGetSessionsFromUser support = (AuthSupportGetSessionsFromUser) client.auth;
support.clearSessionsByUser(client.getUser()); support.clearSessionsByUser(client.getUser());
} }

View file

@ -9,13 +9,12 @@
import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.response.SimpleResponse; import pro.gravit.launchserver.socket.response.SimpleResponse;
import pro.gravit.utils.HookException; import pro.gravit.utils.HookException;
import pro.gravit.utils.helper.LogHelper;
public class JoinServerResponse extends SimpleResponse { public class JoinServerResponse extends SimpleResponse {
private transient final Logger logger = LogManager.getLogger();
public String serverID; public String serverID;
public String accessToken; public String accessToken;
public String username; public String username;
private transient final Logger logger = LogManager.getLogger();
@Override @Override
public String getType() { public String getType() {
@ -43,7 +42,7 @@ public void execute(ChannelHandlerContext ctx, Client client) {
} }
} }
success = server.authManager.joinServer(client, username, accessToken, serverID); success = server.authManager.joinServer(client, username, accessToken, serverID);
if(success) { if (success) {
logger.debug("joinServer: {} accessToken: {} serverID: {}", username, accessToken, serverID); logger.debug("joinServer: {} accessToken: {} serverID: {}", username, accessToken, serverID);
} }
} catch (AuthException | HookException | SecurityException e) { } catch (AuthException | HookException | SecurityException e) {

View file

@ -19,13 +19,13 @@ public String getType() {
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception { public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
if(refreshToken == null) { if (refreshToken == null) {
sendError("Invalid request"); sendError("Invalid request");
return; return;
} }
AuthProviderPair pair; AuthProviderPair pair;
if(!client.isAuth) { if (!client.isAuth) {
if(authId == null) { if (authId == null) {
pair = server.config.getAuthProviderPair(); pair = server.config.getAuthProviderPair();
} else { } else {
pair = server.config.getAuthProviderPair(authId); pair = server.config.getAuthProviderPair(authId);
@ -33,12 +33,12 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
} else { } else {
pair = client.auth; pair = client.auth;
} }
if(pair == null || !pair.isUseCore()) { if (pair == null || !pair.isUseCore()) {
sendError("Invalid request"); sendError("Invalid request");
return; return;
} }
AuthManager.AuthReport report = pair.core.refreshAccessToken(refreshToken, new AuthResponse.AuthContext(client, null, null, ip, AuthResponse.ConnectTypes.API, pair)); AuthManager.AuthReport report = pair.core.refreshAccessToken(refreshToken, new AuthResponse.AuthContext(client, null, null, ip, AuthResponse.ConnectTypes.API, pair));
if(report == null || !report.isUsingOAuth()) { if (report == null || !report.isUsingOAuth()) {
sendError("Invalid RefreshToken"); sendError("Invalid RefreshToken");
return; return;
} }

View file

@ -19,23 +19,20 @@
import java.util.Map; import java.util.Map;
public class RestoreResponse extends SimpleResponse { public class RestoreResponse extends SimpleResponse {
@FunctionalInterface
public interface ExtendedTokenProvider {
boolean accept(Client client, AuthProviderPair pair, String extendedToken);
}
public static Map<String, ExtendedTokenProvider> providers = new HashMap<>(); public static Map<String, ExtendedTokenProvider> providers = new HashMap<>();
private static boolean registeredProviders = false; private static boolean registeredProviders = false;
public static void registerProviders(LaunchServer server) {
if(!registeredProviders) {
providers.put(LauncherRequestEvent.LAUNCHER_EXTENDED_TOKEN_NAME, new LauncherResponse.LauncherTokenVerifier(server));
registeredProviders = true;
}
}
public String authId; public String authId;
public String accessToken; public String accessToken;
public Map<String, String> extended; public Map<String, String> extended;
public boolean needUserInfo; public boolean needUserInfo;
public static void registerProviders(LaunchServer server) {
if (!registeredProviders) {
providers.put(LauncherRequestEvent.LAUNCHER_EXTENDED_TOKEN_NAME, new LauncherResponse.LauncherTokenVerifier(server));
registeredProviders = true;
}
}
@Override @Override
public String getType() { public String getType() {
return "restore"; return "restore";
@ -43,13 +40,13 @@ public String getType() {
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception { public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
if(accessToken == null && !client.isAuth && needUserInfo) { if (accessToken == null && !client.isAuth && needUserInfo) {
sendError("Invalid request"); sendError("Invalid request");
return; return;
} }
AuthProviderPair pair; AuthProviderPair pair;
if(!client.isAuth) { if (!client.isAuth) {
if(authId == null) { if (authId == null) {
pair = server.config.getAuthProviderPair(); pair = server.config.getAuthProviderPair();
} else { } else {
pair = server.config.getAuthProviderPair(authId); pair = server.config.getAuthProviderPair(authId);
@ -57,11 +54,11 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
} else { } else {
pair = client.auth; pair = client.auth;
} }
if(pair == null || !pair.isUseCore()) { if (pair == null || !pair.isUseCore()) {
sendError("Invalid authId"); sendError("Invalid authId");
return; return;
} }
if(accessToken != null) { if (accessToken != null) {
UserSession session; UserSession session;
try { try {
session = pair.core.getUserSessionByOAuthAccessToken(accessToken); session = pair.core.getUserSessionByOAuthAccessToken(accessToken);
@ -69,7 +66,7 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
sendError(AuthRequestEvent.OAUTH_TOKEN_EXPIRE); sendError(AuthRequestEvent.OAUTH_TOKEN_EXPIRE);
return; return;
} }
if(session == null) { if (session == null) {
sendError(AuthRequestEvent.OAUTH_TOKEN_INVALID); sendError(AuthRequestEvent.OAUTH_TOKEN_INVALID);
return; return;
} }
@ -79,19 +76,24 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
server.authManager.internalAuth(client, client.type == null ? AuthResponse.ConnectTypes.API : client.type, pair, user.getUsername(), user.getUUID(), user.getPermissions(), true); server.authManager.internalAuth(client, client.type == null ? AuthResponse.ConnectTypes.API : client.type, pair, user.getUsername(), user.getUUID(), user.getPermissions(), true);
} }
List<String> invalidTokens = new ArrayList<>(4); List<String> invalidTokens = new ArrayList<>(4);
if(extended != null) { if (extended != null) {
extended.forEach((k,v) -> { extended.forEach((k, v) -> {
ExtendedTokenProvider provider = providers.get(k); ExtendedTokenProvider provider = providers.get(k);
if(provider == null) return; if (provider == null) return;
if(!provider.accept(client, pair, v)) { if (!provider.accept(client, pair, v)) {
invalidTokens.add(k); invalidTokens.add(k);
} }
}); });
} }
if(needUserInfo && client.isAuth) { if (needUserInfo && client.isAuth) {
sendResult(new RestoreRequestEvent(CurrentUserResponse.collectUserInfoFromClient(client), invalidTokens)); sendResult(new RestoreRequestEvent(CurrentUserResponse.collectUserInfoFromClient(client), invalidTokens));
} else { } else {
sendResult(new RestoreRequestEvent(invalidTokens)); sendResult(new RestoreRequestEvent(invalidTokens));
} }
} }
@FunctionalInterface
public interface ExtendedTokenProvider {
boolean accept(Client client, AuthProviderPair pair, String extendedToken);
}
} }

View file

@ -39,7 +39,7 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
sendError("Session invalid"); sendError("Session invalid");
return; return;
} }
if(rClient[0].useOAuth) { if (rClient[0].useOAuth) {
sendError("This session using OAuth. Session restoration not safety"); sendError("This session using OAuth. Session restoration not safety");
return; return;
} }

View file

@ -32,9 +32,9 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
if (pair == null) { if (pair == null) {
pair = server.config.getAuthProviderPair(); pair = server.config.getAuthProviderPair();
} }
if(pair.isUseCore()) { if (pair.isUseCore()) {
User user = pair.core.getUserByUsername(list[i].username); User user = pair.core.getUserByUsername(list[i].username);
if(user == null) uuid = null; if (user == null) uuid = null;
else uuid = user.getUUID(); else uuid = user.getUUID();
} else { } else {
uuid = pair.handler.usernameToUUID(list[i].username); uuid = pair.handler.usernameToUUID(list[i].username);

View file

@ -56,13 +56,12 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
sendError("ProfileByUUIDResponse: AuthProviderPair is null"); sendError("ProfileByUUIDResponse: AuthProviderPair is null");
return; return;
} }
if(pair.isUseCore()) { if (pair.isUseCore()) {
User user = pair.core.getUserByUUID(uuid); User user = pair.core.getUserByUUID(uuid);
if(user == null) { if (user == null) {
sendError("User not found"); sendError("User not found");
return; return;
} } else username = user.getUsername();
else username = user.getUsername();
} else { } else {
username = pair.handler.uuidToUsername(uuid); username = pair.handler.uuidToUsername(uuid);
if (username == null) { if (username == null) {

View file

@ -23,9 +23,9 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
UUID uuid; UUID uuid;
AuthProviderPair pair = client.auth; AuthProviderPair pair = client.auth;
if (pair == null) pair = server.config.getAuthProviderPair(); if (pair == null) pair = server.config.getAuthProviderPair();
if(pair.isUseCore()) { if (pair.isUseCore()) {
User user = pair.core.getUserByUsername(username); User user = pair.core.getUserByUsername(username);
if(user == null) uuid = null; if (user == null) uuid = null;
else uuid = user.getUUID(); else uuid = user.getUUID();
} else { } else {
uuid = pair.handler.usernameToUUID(username); uuid = pair.handler.usernameToUUID(username);

View file

@ -1,6 +1,8 @@
package pro.gravit.launchserver.socket.response.update; package pro.gravit.launchserver.socket.response.update;
import io.jsonwebtoken.*; import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -74,6 +76,14 @@ public String createLauncherExtendedToken() {
.compact(); .compact();
} }
private boolean checkSecure(String hash, String salt) {
if (hash == null || salt == null) return false;
byte[] normal_hash = SecurityHelper.digest(SecurityHelper.DigestAlgorithm.SHA256,
server.runtime.clientCheckSecret.concat(".").concat(salt));
byte[] launcher_hash = Base64.getDecoder().decode(hash);
return Arrays.equals(normal_hash, launcher_hash);
}
public static class LauncherTokenVerifier implements RestoreResponse.ExtendedTokenProvider { public static class LauncherTokenVerifier implements RestoreResponse.ExtendedTokenProvider {
private final LaunchServer server; private final LaunchServer server;
private final JwtParser parser; private final JwtParser parser;
@ -102,12 +112,4 @@ public boolean accept(Client client, AuthProviderPair pair, String extendedToken
} }
} }
private boolean checkSecure(String hash, String salt) {
if (hash == null || salt == null) return false;
byte[] normal_hash = SecurityHelper.digest(SecurityHelper.DigestAlgorithm.SHA256,
server.runtime.clientCheckSecret.concat(".").concat(salt));
byte[] launcher_hash = Base64.getDecoder().decode(hash);
return Arrays.equals(normal_hash, launcher_hash);
}
} }

View file

@ -2,7 +2,8 @@
<Configuration status="INFO" packages="pro.gravit.launchserver.config.log4j"> <Configuration status="INFO" packages="pro.gravit.launchserver.config.log4j">
<Appenders> <Appenders>
<Console name="Console" target="SYSTEM_OUT"> <Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} %highlight{[%-5level]}{FATAL=red, ERROR=red, WARN=yellow, INFO=default, DEBUG=green, TRACE=blue} %highlight{%msg}{FATAL=red, ERROR=red, WARN=yellow, INFO=default, DEBUG=green, TRACE=blue}%n" /> <PatternLayout
pattern="%d{HH:mm:ss.SSS} %highlight{[%-5level]}{FATAL=red, ERROR=red, WARN=yellow, INFO=default, DEBUG=green, TRACE=blue} %highlight{%msg}{FATAL=red, ERROR=red, WARN=yellow, INFO=default, DEBUG=green, TRACE=blue}%n"/>
<Filters> <Filters>
<MarkerFilter marker="JANSI" onMatch="ACCEPT" onMismatch="NEUTRAL"/> <MarkerFilter marker="JANSI" onMatch="ACCEPT" onMismatch="NEUTRAL"/>
<MarkerFilter marker="NOJANSI" onMatch="DENY" onMismatch="NEUTRAL"/> <MarkerFilter marker="NOJANSI" onMatch="DENY" onMismatch="NEUTRAL"/>
@ -12,7 +13,7 @@
filePattern="logs/%d{yyyy-MM-dd}.log.gz"> filePattern="logs/%d{yyyy-MM-dd}.log.gz">
<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
<Policies> <Policies>
<TimeBasedTriggeringPolicy /> <TimeBasedTriggeringPolicy/>
</Policies> </Policies>
<Filters> <Filters>
<MarkerFilter marker="JANSI" onMatch="DENY" onMismatch="NEUTRAL"/> <MarkerFilter marker="JANSI" onMatch="DENY" onMismatch="NEUTRAL"/>
@ -36,7 +37,7 @@
<AppenderRef ref="DebugFile" level="debug"/> <AppenderRef ref="DebugFile" level="debug"/>
</Root> </Root>
<Logger name="pro.gravit" level="debug" additivity="false"> <Logger name="pro.gravit" level="debug" additivity="false">
<AppenderRef ref="Console" /> <AppenderRef ref="Console"/>
<AppenderRef ref="MainFile"/> <AppenderRef ref="MainFile"/>
<AppenderRef ref="logCollector"/> <AppenderRef ref="logCollector"/>
<AppenderRef ref="DebugFile"/> <AppenderRef ref="DebugFile"/>

View file

@ -25,11 +25,7 @@
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
import java.security.KeyPair;
import java.security.SecureRandom;
import java.security.Security; import java.security.Security;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
public class ConfigurationTest { public class ConfigurationTest {
@TempDir @TempDir
@ -43,7 +39,7 @@ public class ConfigurationTest {
@BeforeAll @BeforeAll
public static void prepare() throws Throwable { public static void prepare() throws Throwable {
if(Security.getProvider("BC") == null) Security.addProvider(new BouncyCastleProvider()); if (Security.getProvider("BC") == null) Security.addProvider(new BouncyCastleProvider());
LaunchServerModulesManager modulesManager = new LaunchServerModulesManager(modulesDir, configDir, null); LaunchServerModulesManager modulesManager = new LaunchServerModulesManager(modulesDir, configDir, null);
LaunchServerConfig config = LaunchServerConfig.getDefault(LaunchServer.LaunchServerEnv.TEST); LaunchServerConfig config = LaunchServerConfig.getDefault(LaunchServer.LaunchServerEnv.TEST);
Launcher.gsonManager = new LaunchServerGsonManager(modulesManager); Launcher.gsonManager = new LaunchServerGsonManager(modulesManager);
@ -61,13 +57,14 @@ public static void prepare() throws Throwable {
.setCommandHandler(new StdCommandHandler(false)); .setCommandHandler(new StdCommandHandler(false));
launchServer = builder.build(); launchServer = builder.build();
} }
@Test @Test
public void reloadTest() throws Exception { public void reloadTest() throws Exception {
AuthProvider provider = new AuthProvider() { AuthProvider provider = new AuthProvider() {
@Override @Override
public AuthProviderResult auth(String login, AuthRequest.AuthPasswordInterface password, String ip) throws Exception { public AuthProviderResult auth(String login, AuthRequest.AuthPasswordInterface password, String ip) throws Exception {
if(!(password instanceof AuthPlainPassword)) throw new UnsupportedOperationException(); if (!(password instanceof AuthPlainPassword)) throw new UnsupportedOperationException();
if(login.equals("test") && ((AuthPlainPassword) password).password.equals("test")) { if (login.equals("test") && ((AuthPlainPassword) password).password.equals("test")) {
return new AuthProviderResult(login, SecurityHelper.randomStringToken(), new ClientPermissions()); return new AuthProviderResult(login, SecurityHelper.randomStringToken(), new ClientPermissions());
} }
throw new AuthException("Incorrect password"); throw new AuthException("Incorrect password");

View file

@ -13,14 +13,9 @@
import pro.gravit.launchserver.manangers.LaunchServerGsonManager; import pro.gravit.launchserver.manangers.LaunchServerGsonManager;
import pro.gravit.launchserver.modules.impl.LaunchServerModulesManager; import pro.gravit.launchserver.modules.impl.LaunchServerModulesManager;
import pro.gravit.utils.command.StdCommandHandler; import pro.gravit.utils.command.StdCommandHandler;
import pro.gravit.utils.helper.SecurityHelper;
import java.nio.file.Path; import java.nio.file.Path;
import java.security.KeyPair;
import java.security.SecureRandom;
import java.security.Security; import java.security.Security;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
public class StartLaunchServerTest { public class StartLaunchServerTest {
@TempDir @TempDir
@ -33,7 +28,7 @@ public class StartLaunchServerTest {
@BeforeAll @BeforeAll
public static void prepare() throws Throwable { public static void prepare() throws Throwable {
if(Security.getProvider("BC") == null) Security.addProvider(new BouncyCastleProvider()); if (Security.getProvider("BC") == null) Security.addProvider(new BouncyCastleProvider());
LaunchServerModulesManager modulesManager = new LaunchServerModulesManager(modulesDir, configDir, null); LaunchServerModulesManager modulesManager = new LaunchServerModulesManager(modulesDir, configDir, null);
LaunchServerConfig config = LaunchServerConfig.getDefault(LaunchServer.LaunchServerEnv.TEST); LaunchServerConfig config = LaunchServerConfig.getDefault(LaunchServer.LaunchServerEnv.TEST);
Launcher.gsonManager = new LaunchServerGsonManager(modulesManager); Launcher.gsonManager = new LaunchServerGsonManager(modulesManager);

View file

@ -9,6 +9,13 @@
public class TestLaunchServerConfigManager implements LaunchServer.LaunchServerConfigManager { public class TestLaunchServerConfigManager implements LaunchServer.LaunchServerConfigManager {
public LaunchServerConfig config; public LaunchServerConfig config;
public LaunchServerRuntimeConfig runtimeConfig; public LaunchServerRuntimeConfig runtimeConfig;
public TestLaunchServerConfigManager() {
config = LaunchServerConfig.getDefault(LaunchServer.LaunchServerEnv.TEST);
runtimeConfig = new LaunchServerRuntimeConfig();
runtimeConfig.reset();
}
@Override @Override
public LaunchServerConfig readConfig() throws IOException { public LaunchServerConfig readConfig() throws IOException {
return config; return config;
@ -28,10 +35,4 @@ public void writeConfig(LaunchServerConfig config) throws IOException {
public void writeRuntimeConfig(LaunchServerRuntimeConfig config) throws IOException { public void writeRuntimeConfig(LaunchServerRuntimeConfig config) throws IOException {
} }
public TestLaunchServerConfigManager() {
config = LaunchServerConfig.getDefault(LaunchServer.LaunchServerEnv.TEST);
runtimeConfig = new LaunchServerRuntimeConfig();
runtimeConfig.reset();
}
} }

View file

@ -2,7 +2,8 @@
<Configuration status="INFO"> <Configuration status="INFO">
<Appenders> <Appenders>
<Console name="Console" target="SYSTEM_OUT"> <Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} %highlight{[%-5level]}{FATAL=red, ERROR=red, WARN=yellow, INFO=default, DEBUG=green, TRACE=blue} %highlight{%msg}{FATAL=red, ERROR=red, WARN=yellow, INFO=default, DEBUG=green, TRACE=blue}%n" /> <PatternLayout
pattern="%d{HH:mm:ss.SSS} %highlight{[%-5level]}{FATAL=red, ERROR=red, WARN=yellow, INFO=default, DEBUG=green, TRACE=blue} %highlight{%msg}{FATAL=red, ERROR=red, WARN=yellow, INFO=default, DEBUG=green, TRACE=blue}%n"/>
</Console> </Console>
</Appenders> </Appenders>
<Loggers> <Loggers>

View file

@ -90,28 +90,28 @@ public static void main(String[] arguments) throws IOException, InterruptedExcep
List<String> args = new ArrayList<>(16); List<String> args = new ArrayList<>(16);
args.add(context.executePath.toAbsolutePath().toString()); args.add(context.executePath.toAbsolutePath().toString());
args.addAll(context.args); args.addAll(context.args);
context.jvmProperties.forEach((key,value) -> args.add(String.format("-D%s=%s", key, value))); context.jvmProperties.forEach((key, value) -> args.add(String.format("-D%s=%s", key, value)));
if(context.javaVersion.version >= 9) { if (context.javaVersion.version >= 9) {
context.javaFXPaths.add(context.javaVersion.jvmDir); context.javaFXPaths.add(context.javaVersion.jvmDir);
context.javaFXPaths.add(context.javaVersion.jvmDir.resolve("jre")); context.javaFXPaths.add(context.javaVersion.jvmDir.resolve("jre"));
Path openjfxPath = tryGetOpenJFXPath(context.javaVersion.jvmDir); Path openjfxPath = tryGetOpenJFXPath(context.javaVersion.jvmDir);
if(openjfxPath != null) { if (openjfxPath != null) {
context.javaFXPaths.add(openjfxPath); context.javaFXPaths.add(openjfxPath);
} }
StringBuilder modulesPath = new StringBuilder(); StringBuilder modulesPath = new StringBuilder();
StringBuilder modulesAdd = new StringBuilder(); StringBuilder modulesAdd = new StringBuilder();
for(String moduleName : context.jvmModules) { for (String moduleName : context.jvmModules) {
boolean success = tryAddModule(context.javaFXPaths, moduleName, modulesPath); boolean success = tryAddModule(context.javaFXPaths, moduleName, modulesPath);
if(success) { if (success) {
if(modulesAdd.length() > 0) modulesAdd.append(","); if (modulesAdd.length() > 0) modulesAdd.append(",");
modulesAdd.append(moduleName); modulesAdd.append(moduleName);
} }
} }
if(modulesAdd.length() > 0) { if (modulesAdd.length() > 0) {
args.add("--add-modules"); args.add("--add-modules");
args.add(modulesAdd.toString()); args.add(modulesAdd.toString());
} }
if(modulesPath.length() > 0) { if (modulesPath.length() > 0) {
args.add("--module-path"); args.add("--module-path");
args.add(modulesPath.toString()); args.add(modulesPath.toString());
} }
@ -145,18 +145,18 @@ public static void main(String[] arguments) throws IOException, InterruptedExcep
public static Path tryGetOpenJFXPath(Path jvmDir) { public static Path tryGetOpenJFXPath(Path jvmDir) {
String dirName = jvmDir.getFileName().toString(); String dirName = jvmDir.getFileName().toString();
Path parent = jvmDir.getParent(); Path parent = jvmDir.getParent();
if(parent == null) return null; if (parent == null) return null;
Path archJFXPath = parent.resolve(dirName.replace("openjdk", "openjfx")); Path archJFXPath = parent.resolve(dirName.replace("openjdk", "openjfx"));
if(Files.isDirectory(archJFXPath)) { if (Files.isDirectory(archJFXPath)) {
return archJFXPath; return archJFXPath;
} }
Path arch2JFXPath = parent.resolve(dirName.replace("jdk", "openjfx")); Path arch2JFXPath = parent.resolve(dirName.replace("jdk", "openjfx"));
if(Files.isDirectory(arch2JFXPath)) { if (Files.isDirectory(arch2JFXPath)) {
return arch2JFXPath; return arch2JFXPath;
} }
if(JVMHelper.OS_TYPE == JVMHelper.OS.LINUX) { if (JVMHelper.OS_TYPE == JVMHelper.OS.LINUX) {
Path debianJfxPath = Paths.get("/usr/share/openjfx"); Path debianJfxPath = Paths.get("/usr/share/openjfx");
if(Files.isDirectory(debianJfxPath)) { if (Files.isDirectory(debianJfxPath)) {
return debianJfxPath; return debianJfxPath;
} }
} }
@ -293,6 +293,7 @@ public static boolean isExistExtJavaLibrary(Path jvmDir, String name) {
return IOHelper.isFile(jrePath) || IOHelper.isFile(jdkPath); return IOHelper.isFile(jrePath) || IOHelper.isFile(jdkPath);
} }
} }
public static class ClientLauncherWrapperContext { public static class ClientLauncherWrapperContext {
public JavaVersion javaVersion; public JavaVersion javaVersion;
public Path executePath; public Path executePath;
@ -305,6 +306,7 @@ public static class ClientLauncherWrapperContext {
public List<String> jvmModules = new ArrayList<>(); public List<String> jvmModules = new ArrayList<>();
public List<String> clientArgs = new ArrayList<>(); public List<String> clientArgs = new ArrayList<>();
public List<Path> javaFXPaths = new ArrayList<>(); public List<Path> javaFXPaths = new ArrayList<>();
public void addSystemProperty(String name) { public void addSystemProperty(String name) {
String property = System.getProperty(name); String property = System.getProperty(name);
if (property != null) if (property != null)

View file

@ -18,7 +18,6 @@
import pro.gravit.launcher.request.RequestException; import pro.gravit.launcher.request.RequestException;
import pro.gravit.launcher.request.auth.AuthRequest; import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.request.auth.GetAvailabilityAuthRequest; import pro.gravit.launcher.request.auth.GetAvailabilityAuthRequest;
import pro.gravit.launcher.request.auth.RestoreSessionRequest;
import pro.gravit.launcher.request.websockets.StdWebSocketService; import pro.gravit.launcher.request.websockets.StdWebSocketService;
import pro.gravit.launcher.utils.NativeJVMHalt; import pro.gravit.launcher.utils.NativeJVMHalt;
import pro.gravit.utils.helper.*; import pro.gravit.utils.helper.*;
@ -40,12 +39,12 @@ public class LauncherEngine {
public static ClientLauncherProcess.ClientParams clientParams; public static ClientLauncherProcess.ClientParams clientParams;
public static LauncherGuardInterface guard; public static LauncherGuardInterface guard;
public static ClientModuleManager modulesManager; public static ClientModuleManager modulesManager;
public final boolean clientInstance;
// Instance // Instance
private final AtomicBoolean started = new AtomicBoolean(false); private final AtomicBoolean started = new AtomicBoolean(false);
public RuntimeProvider runtimeProvider; public RuntimeProvider runtimeProvider;
public ECPublicKey publicKey; public ECPublicKey publicKey;
public ECPrivateKey privateKey; public ECPrivateKey privateKey;
public final boolean clientInstance;
private LauncherEngine(boolean clientInstance) { private LauncherEngine(boolean clientInstance) {

View file

@ -23,7 +23,6 @@
import pro.gravit.launcher.request.RequestException; import pro.gravit.launcher.request.RequestException;
import pro.gravit.launcher.request.auth.AuthRequest; import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.request.auth.GetAvailabilityAuthRequest; import pro.gravit.launcher.request.auth.GetAvailabilityAuthRequest;
import pro.gravit.launcher.request.auth.RestoreSessionRequest;
import pro.gravit.launcher.serialize.HInput; import pro.gravit.launcher.serialize.HInput;
import pro.gravit.launcher.utils.DirWatcher; import pro.gravit.launcher.utils.DirWatcher;
import pro.gravit.utils.helper.*; import pro.gravit.utils.helper.*;
@ -91,17 +90,17 @@ public static void main(String[] args) throws Throwable {
Launcher.profile = profile; Launcher.profile = profile;
AuthService.profile = profile; AuthService.profile = profile;
LauncherEngine.clientParams = params; LauncherEngine.clientParams = params;
if(params.oauth != null) { if (params.oauth != null) {
LogHelper.info("Using OAuth"); LogHelper.info("Using OAuth");
if(params.oauthExpiredTime != 0) { if (params.oauthExpiredTime != 0) {
Request.setOAuth(params.authId, params.oauth, params.oauthExpiredTime); Request.setOAuth(params.authId, params.oauth, params.oauthExpiredTime);
} else { } else {
Request.setOAuth(params.authId, params.oauth); Request.setOAuth(params.authId, params.oauth);
} }
if(params.extendedTokens != null) { if (params.extendedTokens != null) {
Request.addAllExtendedToken(params.extendedTokens); Request.addAllExtendedToken(params.extendedTokens);
} }
} else if(params.session != null) { } else if (params.session != null) {
LogHelper.info("Using Sessions"); LogHelper.info("Using Sessions");
Request.setSession(params.session); Request.setSession(params.session);
} }
@ -160,7 +159,7 @@ public static void main(String[] args) throws Throwable {
ClientService.classLoader = classLoader; ClientService.classLoader = classLoader;
ClientService.baseURLs = classpath.toArray(new URL[0]); ClientService.baseURLs = classpath.toArray(new URL[0]);
} }
if(params.profile.getRuntimeInClientConfig() != ClientProfile.RuntimeInClientConfig.NONE) { if (params.profile.getRuntimeInClientConfig() != ClientProfile.RuntimeInClientConfig.NONE) {
CommonHelper.newThread("Client Launcher Thread", true, () -> { CommonHelper.newThread("Client Launcher Thread", true, () -> {
try { try {
engine.start(args); engine.start(args);

View file

@ -92,7 +92,7 @@ public ClientLauncherProcess(Path clientDir, Path assetDir, Path javaDir, Path r
LogHelper.error(e); LogHelper.error(e);
javaVersion = null; javaVersion = null;
} }
if(javaVersion == null) { if (javaVersion == null) {
javaVersion = ClientLauncherWrapper.JavaVersion.getCurrentJavaVersion(); javaVersion = ClientLauncherWrapper.JavaVersion.getCurrentJavaVersion();
} }
this.bits = JVMHelper.JVM_BITS; this.bits = JVMHelper.JVM_BITS;
@ -120,7 +120,7 @@ private void applyClientProfile() {
this.jvmArgs.add("-Xmx" + params.ram + 'M'); this.jvmArgs.add("-Xmx" + params.ram + 'M');
} }
this.params.oauth = Request.getOAuth(); this.params.oauth = Request.getOAuth();
if(this.params.oauth == null) { if (this.params.oauth == null) {
this.params.session = Request.getSession(); this.params.session = Request.getSession();
} else { } else {
this.params.authId = Request.getAuthId(); this.params.authId = Request.getAuthId();
@ -128,7 +128,7 @@ private void applyClientProfile() {
this.params.extendedTokens = Request.getExtendedTokens(); this.params.extendedTokens = Request.getExtendedTokens();
} }
if(this.params.profile.getRuntimeInClientConfig() != ClientProfile.RuntimeInClientConfig.NONE) { if (this.params.profile.getRuntimeInClientConfig() != ClientProfile.RuntimeInClientConfig.NONE) {
jvmModules.add("javafx.base"); jvmModules.add("javafx.base");
jvmModules.add("javafx.graphics"); jvmModules.add("javafx.graphics");
jvmModules.add("javafx.fxml"); jvmModules.add("javafx.fxml");
@ -145,7 +145,7 @@ public void start(boolean pipeOutput) throws IOException, InterruptedException {
List<String> processArgs = new LinkedList<>(); List<String> processArgs = new LinkedList<>();
processArgs.add(executeFile.toString()); processArgs.add(executeFile.toString());
processArgs.addAll(jvmArgs); processArgs.addAll(jvmArgs);
if(javaVersion.version >= 9) { if (javaVersion.version >= 9) {
applyJava9Params(processArgs); applyJava9Params(processArgs);
} }
//ADD CLASSPATH //ADD CLASSPATH
@ -186,23 +186,23 @@ private void applyJava9Params(List<String> processArgs) {
jvmModulesPaths.add(javaVersion.jvmDir); jvmModulesPaths.add(javaVersion.jvmDir);
jvmModulesPaths.add(javaVersion.jvmDir.resolve("jre")); jvmModulesPaths.add(javaVersion.jvmDir.resolve("jre"));
Path openjfxPath = ClientLauncherWrapper.tryGetOpenJFXPath(javaVersion.jvmDir); Path openjfxPath = ClientLauncherWrapper.tryGetOpenJFXPath(javaVersion.jvmDir);
if(openjfxPath != null) { if (openjfxPath != null) {
jvmModulesPaths.add(openjfxPath); jvmModulesPaths.add(openjfxPath);
} }
StringBuilder modulesPath = new StringBuilder(); StringBuilder modulesPath = new StringBuilder();
StringBuilder modulesAdd = new StringBuilder(); StringBuilder modulesAdd = new StringBuilder();
for(String moduleName : jvmModules) { for (String moduleName : jvmModules) {
boolean success = ClientLauncherWrapper.tryAddModule(jvmModulesPaths, moduleName, modulesPath); boolean success = ClientLauncherWrapper.tryAddModule(jvmModulesPaths, moduleName, modulesPath);
if(success) { if (success) {
if(modulesAdd.length() > 0) modulesAdd.append(","); if (modulesAdd.length() > 0) modulesAdd.append(",");
modulesAdd.append(moduleName); modulesAdd.append(moduleName);
} }
} }
if(modulesAdd.length() > 0) { if (modulesAdd.length() > 0) {
processArgs.add("--add-modules"); processArgs.add("--add-modules");
processArgs.add(modulesAdd.toString()); processArgs.add(modulesAdd.toString());
} }
if(modulesPath.length() > 0) { if (modulesPath.length() > 0) {
processArgs.add("--module-path"); processArgs.add("--module-path");
processArgs.add(modulesPath.toString()); processArgs.add(modulesPath.toString());
} }

View file

@ -7,7 +7,6 @@
import pro.gravit.launcher.modules.impl.SimpleModuleManager; import pro.gravit.launcher.modules.impl.SimpleModuleManager;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Collection;
public final class ClientModuleManager extends SimpleModuleManager { public final class ClientModuleManager extends SimpleModuleManager {
public ClientModuleManager() { public ClientModuleManager() {

View file

@ -2,8 +2,6 @@
import pro.gravit.launcher.ClientLauncherWrapper; import pro.gravit.launcher.ClientLauncherWrapper;
import java.util.Collection;
public interface ClientWrapperModule { public interface ClientWrapperModule {
void wrapperPhase(ClientLauncherWrapper.ClientLauncherWrapperContext context); void wrapperPhase(ClientLauncherWrapper.ClientLauncherWrapperContext context);
} }

View file

@ -29,8 +29,6 @@ public final class LauncherConfig extends StreamObject {
@LauncherInject("launcher.port") @LauncherInject("launcher.port")
public final int clientPort; public final int clientPort;
public final LauncherTrustManager trustManager; public final LauncherTrustManager trustManager;
@Deprecated
public ECPublicKey publicKey = null;
public final ECPublicKey ecdsaPublicKey; public final ECPublicKey ecdsaPublicKey;
public final RSAPublicKey rsaPublicKey; public final RSAPublicKey rsaPublicKey;
public final Map<String, byte[]> runtime; public final Map<String, byte[]> runtime;
@ -48,6 +46,8 @@ public final class LauncherConfig extends StreamObject {
public final String runtimeEncryptKey; public final String runtimeEncryptKey;
@LauncherInject("launcher.address") @LauncherInject("launcher.address")
public final String address; public final String address;
@Deprecated
public ECPublicKey publicKey = null;
@LauncherInject("runtimeconfig.secretKeyClient") @LauncherInject("runtimeconfig.secretKeyClient")
public String secretKeyClient; public String secretKeyClient;
@LauncherInject("runtimeconfig.oemUnlockKey") @LauncherInject("runtimeconfig.oemUnlockKey")

View file

@ -61,6 +61,11 @@ public AuthRequestEvent(ClientPermissions permissions, PlayerProfile playerProfi
this.oauth = oauth; this.oauth = oauth;
} }
@Override
public String getType() {
return "auth";
}
public static class OAuthRequestEvent { public static class OAuthRequestEvent {
public final String accessToken; public final String accessToken;
public final String refreshToken; public final String refreshToken;
@ -72,9 +77,4 @@ public OAuthRequestEvent(String accessToken, String refreshToken, long expire) {
this.expire = expire; this.expire = expire;
} }
} }
@Override
public String getType() {
return "auth";
}
} }

View file

@ -36,7 +36,11 @@ public enum ServerFeature {
} }
} }
public interface AuthAvailabilityDetails extends TypeSerializeInterface {
}
public static class AuthAvailability { public static class AuthAvailability {
public final List<AuthAvailabilityDetails> details;
@LauncherNetworkAPI @LauncherNetworkAPI
public String name; public String name;
@LauncherNetworkAPI @LauncherNetworkAPI
@ -48,8 +52,6 @@ public static class AuthAvailability {
@LauncherNetworkAPI @LauncherNetworkAPI
public AuthType secondType; public AuthType secondType;
public final List<AuthAvailabilityDetails> details;
@Deprecated @Deprecated
public AuthAvailability(String name, String displayName, AuthType firstType, AuthType secondType) { public AuthAvailability(String name, String displayName, AuthType firstType, AuthType secondType) {
this.name = name; this.name = name;
@ -81,6 +83,4 @@ public enum AuthType {
OTHER OTHER
} }
} }
public interface AuthAvailabilityDetails extends TypeSerializeInterface {
}
} }

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