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

View file

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

View file

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

View file

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

View file

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

View file

@ -18,7 +18,6 @@
import pro.gravit.utils.command.Command;
import pro.gravit.utils.command.CommandException;
import pro.gravit.utils.command.SubCommand;
import pro.gravit.utils.helper.SecurityHelper;
import java.io.IOException;
import java.util.Collections;
@ -31,8 +30,9 @@
*/
public abstract class AuthCoreProvider implements AutoCloseable, Reconfigurable {
public static final ProviderMap<AuthCoreProvider> providers = new ProviderMap<>("AuthCoreProvider");
private static boolean registredProviders = false;
private static final Logger logger = LogManager.getLogger();
private static boolean registredProviders = false;
public static void registerProviders() {
if (!registredProviders) {
providers.register("reject", RejectAuthCoreProvider.class);
@ -40,14 +40,23 @@ public static void registerProviders() {
registredProviders = true;
}
}
public abstract User getUserByUsername(String username);
public abstract User getUserByUUID(UUID uuid);
public abstract UserSession getUserSessionByOAuthAccessToken(String accessToken) throws OAuthAccessTokenExpired;
public abstract AuthManager.AuthReport refreshAccessToken(String refreshToken, AuthResponse.AuthContext context /* may be null */);
public abstract void verifyAuth(AuthResponse.AuthContext context) throws AuthException;
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 void init(LaunchServer server);
// Auth Handler methods
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 {
verifyArgs(args, 2);
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;
if(args[1].startsWith("{")) {
if (args[1].startsWith("{")) {
password = Launcher.gsonManager.gson.fromJson(args[1], AuthRequest.AuthPasswordInterface.class);
} else {
password = new AuthPlainPassword(args[1]);
}
PasswordVerifyReport report = verifyPassword(user, password);
if(report.success) {
if (report.success) {
logger.info("Password correct");
} else {
if(report.needMoreFactor) {
if(report.factors.size() == 1 && report.factors.get(0) == -1) {
if (report.needMoreFactor) {
if (report.factors.size() == 1 && report.factors.get(0) == -1) {
logger.info("Password not correct: Required 2FA");
} else {
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;
map.put("getallusers", new SubCommand("(limit)", "print all users information") {
@Override
public void invoke(String... args) throws Exception {
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();
int counter = 0;
for(User u : users) {
for (User u : users) {
logger.info("User {}", u.toString());
counter++;
if(counter == max) break;
if (counter == max) break;
}
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 {
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 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 {
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);
}
@ -125,11 +134,11 @@ public boolean joinServer(Client client, String username, String accessToken, St
public abstract void close() throws IOException;
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 needMoreFactor;
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) {
this.success = success;

View file

@ -75,7 +75,7 @@ public void verifyAuth(AuthResponse.AuthContext context) throws AuthException {
@Override
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);
} else {
return PasswordVerifyReport.FAILED;
@ -84,7 +84,7 @@ public PasswordVerifyReport verifyPassword(User user, AuthRequest.AuthPasswordIn
@Override
public AuthManager.AuthReport createOAuthSession(User user, AuthResponse.AuthContext context, PasswordVerifyReport report, boolean minecraftAccess) throws IOException {
if(minecraftAccess) {
if (minecraftAccess) {
String minecraftAccessToken = SecurityHelper.randomStringToken();
updateAuth(user, minecraftAccessToken);
return AuthManager.AuthReport.ofMinecraftAccessToken(minecraftAccessToken);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -8,7 +8,10 @@
import pro.gravit.launchserver.auth.provider.AuthProviderResult;
import pro.gravit.utils.command.Command;
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.Reader;

View file

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

View file

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

View file

@ -5,13 +5,15 @@
public abstract class PasswordVerifier {
public static final ProviderMap<PasswordVerifier> providers = new ProviderMap<>("PasswordVerifier");
private static boolean registeredProviders = false;
public static void registerProviders() {
if(!registeredProviders) {
if (!registeredProviders) {
providers.register("plain", PlainPasswordVerifier.class);
providers.register("digest", DigestPasswordVerifier.class);
providers.register("doubleDigest", DoubleDigestPasswordVerifier.class);
registeredProviders = true;
}
}
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.secure.HardwareReportResponse;
import pro.gravit.utils.command.Command;
import pro.gravit.utils.helper.LogHelper;
import java.util.HashMap;
import java.util.Map;

View file

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

View file

@ -13,24 +13,21 @@
import java.sql.*;
public class MysqlHWIDProvider extends HWIDProvider {
private transient final Logger logger = LogManager.getLogger();
public MySQLSourceConfig mySQLHolder;
public double warningSpoofingLevel = -1.0;
public double criticalCompareLevel = 1.0;
public String tableHWID = "hwids";
public String tableHWIDLog = "hwidLog";
public String tableUsers;
public String usersNameColumn;
public String usersHWIDColumn;
private String sqlFindByPublicKey;
private String sqlFindByHardware;
private String sqlCreateHardware;
private String sqlCreateHWIDLog;
private String sqlUpdateHardware;
private String sqlUpdateUsers;
private transient final Logger logger = LogManager.getLogger();
@Override
public void init(LaunchServer server) {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,12 +1,10 @@
package pro.gravit.launchserver.binary;
import org.jetbrains.annotations.NotNull;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.serialize.HOutput;
import pro.gravit.launcher.serialize.stream.StreamObject;
import pro.gravit.launchserver.binary.tasks.MainBuildTask;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper;
import javax.crypto.Cipher;
@ -33,7 +31,6 @@
import java.util.function.Predicate;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
@ -234,7 +231,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException 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);
}

View file

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

View file

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

View file

@ -2,7 +2,6 @@
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException;
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) {
if(name.startsWith("META-INF/services")) return false;
if (name.startsWith("META-INF/services")) return false;
return exclusions.stream().anyMatch(name::startsWith);
}

View file

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

View file

@ -17,7 +17,6 @@
import pro.gravit.launchserver.binary.BuildContext;
import pro.gravit.utils.HookException;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper;
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()));
postInitProps();
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()));
};
}
;
context.pushJarFile(inputJar, (e) -> blacklist.contains(e.getName()), (e) -> true);
// map for guard
Map<String, byte[]> runtime = new HashMap<>(256);
// 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);
} else {
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("launcher.memory", server.config.launcher.memoryLimit);
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("launcher.certificatePinning", server.config.launcher.certificatePinning);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -3,7 +3,6 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.hasher.HashedDir;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.profiles.ClientProfileBuilder;
import pro.gravit.launcher.profiles.optional.OptionalFile;
@ -12,7 +11,6 @@
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException;
import java.io.Reader;
@ -28,15 +26,11 @@ public SaveProfilesCommand(LaunchServer server) {
super(server);
}
public enum MakeProfileOption {
LAUNCHWRAPPER, VANILLA, FORGE, FABRIC, LITELOADER
}
public static ClientProfile makeProfile(ClientProfile.Version version, String title, MakeProfileOption... options) {
ClientProfileBuilder builder = new ClientProfileBuilder();
builder.setVersion(version.name);
builder.setDir(title);
builder.setAssetDir("asset"+version.name);
builder.setAssetDir("asset" + version.name);
builder.setAssetIndex(version.name);
builder.setInfo("Информация о сервере");
builder.setTitle(title);
@ -57,16 +51,16 @@ public static ClientProfile makeProfile(ClientProfile.Version version, String ti
jvmArgs.add("-XX:MaxGCPauseMillis=50");
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");
if(optionContains(options, MakeProfileOption.FORGE)) {
if (optionContains(options, MakeProfileOption.FORGE)) {
builder.setClassLoaderConfig(ClientProfile.ClassLoaderConfig.AGENT);
}
OptionalFile optionalMacOs = new OptionalFile();
optionalMacOs.name = "MacOSArgs";
optionalMacOs.actions = new ArrayList<>(1);
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);
}
jvmArgs.add("-Dfml.ignorePatchDiscrepancies=true");
@ -74,14 +68,14 @@ public static ClientProfile makeProfile(ClientProfile.Version version, String ti
builder.setJvmArgs(jvmArgs);
builder.setUpdateOptional(optionals);
List<String> clientArgs = new ArrayList<>();
if(optionContains(options, MakeProfileOption.LAUNCHWRAPPER)) {
if(optionContains(options, MakeProfileOption.LITELOADER)) {
if (optionContains(options, MakeProfileOption.LAUNCHWRAPPER)) {
if (optionContains(options, MakeProfileOption.LITELOADER)) {
clientArgs.add("--tweakClass");
clientArgs.add("com.mumfrey.liteloader.launch.LiteLoaderTweaker");
}
if(optionContains(options, MakeProfileOption.FORGE)) {
if (optionContains(options, MakeProfileOption.FORGE)) {
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");
} else {
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) {
if(optionContains(options, MakeProfileOption.LAUNCHWRAPPER)) {
if (optionContains(options, MakeProfileOption.LAUNCHWRAPPER)) {
return "net.minecraft.launchwrapper.Launch";
}
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) {
List<MakeProfileOption> options = new ArrayList<>(2);
if(Files.exists(dir.resolve("forge.jar"))) {
if (Files.exists(dir.resolve("forge.jar"))) {
options.add(MakeProfileOption.FORGE);
}
if(Files.exists(dir.resolve("liteloader.jar"))) {
if (Files.exists(dir.resolve("liteloader.jar"))) {
options.add(MakeProfileOption.LITELOADER);
}
if(version.compareTo(ClientProfile.Version.MC1122) <= 0) {
if (version.compareTo(ClientProfile.Version.MC1122) <= 0) {
options.add(MakeProfileOption.LAUNCHWRAPPER);
}
return options.toArray(new MakeProfileOption[0]);
@ -191,4 +185,8 @@ public void invoke(String... args) throws Exception {
server.syncProfilesDir();
}
}
public enum MakeProfileOption {
LAUNCHWRAPPER, VANILLA, FORGE, FABRIC, LITELOADER
}
}

View file

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

View file

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

View file

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

View file

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

View file

@ -9,7 +9,6 @@
import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.command.CommandException;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.BufferedReader;
import java.nio.file.Files;
@ -19,7 +18,7 @@
public final class UnindexAssetCommand extends Command {
private transient final Logger logger = LogManager.getLogger();
public UnindexAssetCommand(LaunchServer server) {
super(server);
}

View file

@ -8,13 +8,13 @@
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.launchermodules.LauncherModuleLoader;
import pro.gravit.utils.helper.LogHelper;
import java.security.cert.X509Certificate;
import java.util.Arrays;
public class ModulesCommand extends Command {
private transient final Logger logger = LogManager.getLogger();
public ModulesCommand(LaunchServer 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);
printCheckStatusInfo(checkStatus);
}
for(LauncherModuleLoader.ModuleEntity entity : server.launcherModuleLoader.launcherModules) {
for (LauncherModuleLoader.ModuleEntity entity : server.launcherModuleLoader.launcherModules) {
LauncherTrustManager.CheckClassResult checkStatus = entity.checkResult;
logger.info("[LAUNCHER MODULE] {} sig: {}", entity.path.getFileName().toString(), checkStatus == null ? "null" : checkStatus.type);
printCheckStatusInfo(checkStatus);

View file

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

View file

@ -3,13 +3,11 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.NeedGarbageCollection;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.components.Component;
import pro.gravit.utils.command.SubCommand;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.Reader;
import java.lang.invoke.MethodHandles;
@ -25,6 +23,28 @@ public ComponentCommand(LaunchServer server) {
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 {
public UnloadCommand() {
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");
}
}
private class LoadCommand extends SubCommand {
public LoadCommand() {
super("[componentName] [componentType] (json file)", "Load component");
@ -57,13 +78,13 @@ public void invoke(String... args) throws Exception {
verifyArgs(args, 2);
String componentName = args[0];
Class<? extends Component> componentClass = Component.providers.getClass(args[1]);
if(componentClass == null) {
if (componentClass == null) {
logger.error("Component type {} not registered", componentName);
return;
}
try {
Component component;
if(args.length > 2) {
if (args.length > 2) {
try (Reader reader = IOHelper.newReader(Paths.get(args[2]))) {
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 {
verifyArgs(args, 2);
NotificationEvent event;
if(args.length < 3) {
if (args.length < 3) {
event = new NotificationEvent(args[0], args[1]);
} else {
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.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.LogHelper;
public class PingServersCommand extends Command {
private transient final Logger logger = LogManager.getLogger();

View file

@ -2,7 +2,6 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.fusesource.jansi.Ansi;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.handler.MemoryAuthHandler;
@ -13,14 +12,12 @@
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.components.ProGuardComponent;
import pro.gravit.launchserver.config.LaunchServerConfig;
import pro.gravit.utils.helper.FormatHelper;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
@ -198,38 +195,38 @@ public void invoke(String... args) {
}
//Linux permissions check
if(JVMHelper.OS_TYPE == JVMHelper.OS.LINUX) {
if (JVMHelper.OS_TYPE == JVMHelper.OS.LINUX) {
try {
int uid = 0, gid = 0;
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(":");
if(parts.length == 0) continue;
if(parts[0].trim().equalsIgnoreCase("Uid")) {
if (parts.length == 0) continue;
if (parts[0].trim().equalsIgnoreCase("Uid")) {
String[] words = parts[1].trim().split(" ");
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");
}
}
if(parts[0].trim().equalsIgnoreCase("Gid")) {
if (parts[0].trim().equalsIgnoreCase("Gid")) {
String[] words = parts[1].trim().split(" ");
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");
}
}
}
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'");
}
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'");
}
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'");
}
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'");
}
} catch (IOException e) {
@ -238,10 +235,12 @@ public void invoke(String... args) {
}
logger.info("Check completed");
}
public boolean checkOtherWriteAccess(Path file) throws IOException {
Set<PosixFilePermission> permissionSet = Files.getPosixFilePermissions(file);
return permissionSet.contains(PosixFilePermission.OTHERS_WRITE);
}
public boolean checkOtherReadOrWriteAccess(Path file) throws IOException {
Set<PosixFilePermission> permissionSet = Files.getPosixFilePermissions(file);
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.utils.command.CommandHandler;
import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper;
public class ServerStatusCommand extends Command {
private transient final Logger logger = LogManager.getLogger();

View file

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

View file

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

View file

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

View file

@ -7,7 +7,10 @@
import pro.gravit.launchserver.binary.tasks.LauncherBuildTask;
import pro.gravit.utils.command.Command;
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.ConfigurationParser;
import proguard.ParseException;
@ -20,9 +23,13 @@
import java.nio.file.Path;
import java.nio.file.Paths;
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 {
private transient static final Logger logger = LogManager.getLogger();
public String modeAfter = "MainBuild";
public String dir = "proguard";
public boolean enabled = true;
@ -30,7 +37,40 @@ public class ProGuardComponent extends Component implements AutoCloseable, Recon
public transient ProguardConf proguardConf;
private transient LaunchServer launchServer;
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
public void init(LaunchServer launchServer) {
this.launchServer = launchServer;
@ -41,7 +81,7 @@ public void init(LaunchServer launchServer) {
@Override
public void close() throws Exception {
if(launchServer != null && buildTask != null) {
if (launchServer != null && buildTask != null) {
launchServer.launcherBinary.tasks.remove(buildTask);
}
}
@ -93,15 +133,14 @@ public Path process(Path inputFile) throws IOException {
Path outputJar = server.launcherBinary.nextLowerPath(this);
if (component.enabled) {
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);
}
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");
jfxPath = null;
}
else if(jfxPath != null && checkFXJMods(jfxPath)) {
} else if (jfxPath != null && checkFXJMods(jfxPath)) {
logger.debug("JMods resolved in {}", jfxPath.toString());
} else {
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 final String[] JAVA9_OPTS = new String[]{
"-libraryjars '<java.home>/jmods/'"
@ -205,8 +211,8 @@ public String[] buildConfig(Path inputJar, Path outputJar, Path[] jfxPath) {
confStrs.add("-injar '" + inputJar.toAbsolutePath() + "'");
confStrs.add("-outjar '" + outputJar.toAbsolutePath() + "'");
Collections.addAll(confStrs, JAVA9_OPTS);
if(jfxPath != null) {
for(Path path : jfxPath) {
if (jfxPath != null) {
for (Path path : jfxPath) {
confStrs.add(String.format("-libraryjars '%s'", path.toAbsolutePath()));
}
}

View file

@ -23,7 +23,6 @@
import pro.gravit.launchserver.dao.provider.DaoProvider;
import pro.gravit.utils.Version;
import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.File;
import java.util.Arrays;
@ -31,6 +30,7 @@
import java.util.Map;
public final class LaunchServerConfig {
private transient final Logger logger = LogManager.getLogger();
public String projectName;
public String[] mirrors;
public String binaryName;
@ -40,7 +40,6 @@ public final class LaunchServerConfig {
@Deprecated
public DaoProvider dao;
public SessionStorage sessions;
// Handlers & Providers
public ProtectHandler protectHandler;
public Map<String, Component> components;
@ -51,7 +50,6 @@ public final class LaunchServerConfig {
public String startScript;
private transient LaunchServer server = null;
private transient AuthProviderPair authDefault;
private transient final Logger logger = LogManager.getLogger();
public static LaunchServerConfig getDefault(LaunchServer.LaunchServerEnv env) {
LaunchServerConfig newConfig = new LaunchServerConfig();
@ -157,7 +155,7 @@ public void verify() {
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");
}

View file

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

View file

@ -17,37 +17,16 @@
import java.util.Set;
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 {
private static volatile LogAppender INSTANCE;
private final Set<Consumer<LogEvent>> set = new HashSet<>();
public LogAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions, Property[] properties) {
super(name, filter, layout, ignoreExceptions, properties);
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() {
return INSTANCE;
}
@ -67,4 +46,26 @@ public static LogAppender createAppender(
}
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.binary.tasks.MainBuildTask;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.IOException;
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);
entity.checkResult = server.modulesManager.checkModuleClass(mainClazz);
} 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());
} else {
logger.error(e);

View file

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

View file

@ -38,6 +38,7 @@ public AuthManager(LaunchServer server) {
/**
* Create AuthContext
*
* @return AuthContext instance
*/
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
*
* @param context Auth context
* @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 final String minecraftAccessToken;
public final String oauthAccessToken;
@ -92,188 +275,4 @@ public boolean isUsingOAuth() {
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.utils.helper.IOHelper;
import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper;
import java.io.*;
@ -50,13 +49,13 @@
public class CertificateManager {
public final int validDays = 60;
public final int minusHours = 6;
private transient final Logger logger = LogManager.getLogger();
public X509CertificateHolder ca;
public AsymmetricKeyParameter caKey;
public X509CertificateHolder server;
public AsymmetricKeyParameter serverKey;
public LauncherTrustManager trustManager;
public String orgName;
private transient final Logger logger = LogManager.getLogger();
public X509CertificateHolder generateCertificate(String subjectName, PublicKey subjectPublicKey) throws OperatorCreationException {
SubjectPublicKeyInfo subjectPubKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
@ -182,7 +181,7 @@ public void readTrustStore(Path dir) throws IOException, CertificateException {
}
} else {
if(IOHelper.exists(dir.resolve("GravitCentralRootCA.crt"))) {
if (IOHelper.exists(dir.resolve("GravitCentralRootCA.crt"))) {
logger.warn("Found old default certificate - 'GravitCentralRootCA.crt'. Delete...");
Files.delete(dir.resolve("GravitCentralRootCA.crt"));
}

View file

@ -3,12 +3,12 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper;
import java.io.IOException;
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.ECPublicKey;
import java.security.interfaces.RSAPrivateKey;

View file

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

View file

@ -58,7 +58,7 @@ private Client restoreFromString(byte[] data) {
Client result = decompressClient(data);
result.updateAuth(server);
if (result.auth != null && (result.username != null)) {
if(result.auth.isUseCore()) {
if (result.auth.isUseCore()) {
result.coreObject = result.auth.core.getUserByUUID(result.uuid);
} else {
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() {
if(coreObject != null) return coreObject;
if(auth != null && uuid != null && auth.isUseCore()) {
if (coreObject != null) return coreObject;
if (auth != null && uuid != null && auth.isUseCore()) {
coreObject = auth.core.getUserByUUID(uuid);
}
return coreObject;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -5,28 +5,14 @@
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.events.request.AuthRequestEvent;
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.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.socket.Client;
import pro.gravit.launchserver.socket.response.SimpleResponse;
import pro.gravit.launchserver.socket.response.profile.ProfileByUUIDResponse;
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;
public class AuthResponse extends SimpleResponse {
@ -62,7 +48,7 @@ public void execute(ChannelHandlerContext ctx, Client clientData) throws Excepti
server.authHookManager.preHook.hook(context, clientData);
context.report = server.authManager.auth(context, password);
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);
} else if (getSession) {
if (clientData.session == null) {
@ -71,7 +57,7 @@ public void execute(ChannelHandlerContext ctx, Client clientData) throws Excepti
}
result.session = clientData.session;
}
if(context.report.minecraftAccessToken != null) {
if (context.report.minecraftAccessToken != null) {
result.accessToken = context.report.minecraftAccessToken;
}
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.profile.ProfileByUUIDResponse;
import pro.gravit.utils.HookException;
import pro.gravit.utils.helper.LogHelper;
public class CheckServerResponse extends SimpleResponse {
private transient final Logger logger = LogManager.getLogger();
public String serverID;
public String username;
public String client;
private transient final Logger logger = LogManager.getLogger();
@Override
public String getType() {

View file

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

View file

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

View file

@ -19,13 +19,13 @@ public String getType() {
@Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
if(refreshToken == null) {
if (refreshToken == null) {
sendError("Invalid request");
return;
}
AuthProviderPair pair;
if(!client.isAuth) {
if(authId == null) {
if (!client.isAuth) {
if (authId == null) {
pair = server.config.getAuthProviderPair();
} else {
pair = server.config.getAuthProviderPair(authId);
@ -33,12 +33,12 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
} else {
pair = client.auth;
}
if(pair == null || !pair.isUseCore()) {
if (pair == null || !pair.isUseCore()) {
sendError("Invalid request");
return;
}
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");
return;
}

View file

@ -19,23 +19,20 @@
import java.util.Map;
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<>();
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 accessToken;
public Map<String, String> extended;
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
public String getType() {
return "restore";
@ -43,13 +40,13 @@ public String getType() {
@Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
if(accessToken == null && !client.isAuth && needUserInfo) {
if (accessToken == null && !client.isAuth && needUserInfo) {
sendError("Invalid request");
return;
}
AuthProviderPair pair;
if(!client.isAuth) {
if(authId == null) {
if (!client.isAuth) {
if (authId == null) {
pair = server.config.getAuthProviderPair();
} else {
pair = server.config.getAuthProviderPair(authId);
@ -57,11 +54,11 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
} else {
pair = client.auth;
}
if(pair == null || !pair.isUseCore()) {
if (pair == null || !pair.isUseCore()) {
sendError("Invalid authId");
return;
}
if(accessToken != null) {
if (accessToken != null) {
UserSession session;
try {
session = pair.core.getUserSessionByOAuthAccessToken(accessToken);
@ -69,7 +66,7 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
sendError(AuthRequestEvent.OAUTH_TOKEN_EXPIRE);
return;
}
if(session == null) {
if (session == null) {
sendError(AuthRequestEvent.OAUTH_TOKEN_INVALID);
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);
}
List<String> invalidTokens = new ArrayList<>(4);
if(extended != null) {
extended.forEach((k,v) -> {
if (extended != null) {
extended.forEach((k, v) -> {
ExtendedTokenProvider provider = providers.get(k);
if(provider == null) return;
if(!provider.accept(client, pair, v)) {
if (provider == null) return;
if (!provider.accept(client, pair, v)) {
invalidTokens.add(k);
}
});
}
if(needUserInfo && client.isAuth) {
if (needUserInfo && client.isAuth) {
sendResult(new RestoreRequestEvent(CurrentUserResponse.collectUserInfoFromClient(client), invalidTokens));
} else {
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");
return;
}
if(rClient[0].useOAuth) {
if (rClient[0].useOAuth) {
sendError("This session using OAuth. Session restoration not safety");
return;
}

View file

@ -32,9 +32,9 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
if (pair == null) {
pair = server.config.getAuthProviderPair();
}
if(pair.isUseCore()) {
if (pair.isUseCore()) {
User user = pair.core.getUserByUsername(list[i].username);
if(user == null) uuid = null;
if (user == null) uuid = null;
else uuid = user.getUUID();
} else {
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");
return;
}
if(pair.isUseCore()) {
if (pair.isUseCore()) {
User user = pair.core.getUserByUUID(uuid);
if(user == null) {
if (user == null) {
sendError("User not found");
return;
}
else username = user.getUsername();
} else username = user.getUsername();
} else {
username = pair.handler.uuidToUsername(uuid);
if (username == null) {

View file

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

View file

@ -1,6 +1,8 @@
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 org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@ -74,6 +76,14 @@ public String createLauncherExtendedToken() {
.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 {
private final LaunchServer server;
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">
<Appenders>
<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>
<MarkerFilter marker="JANSI" onMatch="ACCEPT" onMismatch="NEUTRAL"/>
<MarkerFilter marker="NOJANSI" onMatch="DENY" onMismatch="NEUTRAL"/>
@ -12,7 +13,7 @@
filePattern="logs/%d{yyyy-MM-dd}.log.gz">
<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy />
<TimeBasedTriggeringPolicy/>
</Policies>
<Filters>
<MarkerFilter marker="JANSI" onMatch="DENY" onMismatch="NEUTRAL"/>
@ -36,7 +37,7 @@
<AppenderRef ref="DebugFile" level="debug"/>
</Root>
<Logger name="pro.gravit" level="debug" additivity="false">
<AppenderRef ref="Console" />
<AppenderRef ref="Console"/>
<AppenderRef ref="MainFile"/>
<AppenderRef ref="logCollector"/>
<AppenderRef ref="DebugFile"/>

View file

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

View file

@ -13,14 +13,9 @@
import pro.gravit.launchserver.manangers.LaunchServerGsonManager;
import pro.gravit.launchserver.modules.impl.LaunchServerModulesManager;
import pro.gravit.utils.command.StdCommandHandler;
import pro.gravit.utils.helper.SecurityHelper;
import java.nio.file.Path;
import java.security.KeyPair;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
public class StartLaunchServerTest {
@TempDir
@ -33,7 +28,7 @@ public class StartLaunchServerTest {
@BeforeAll
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);
LaunchServerConfig config = LaunchServerConfig.getDefault(LaunchServer.LaunchServerEnv.TEST);
Launcher.gsonManager = new LaunchServerGsonManager(modulesManager);

View file

@ -9,6 +9,13 @@
public class TestLaunchServerConfigManager implements LaunchServer.LaunchServerConfigManager {
public LaunchServerConfig config;
public LaunchServerRuntimeConfig runtimeConfig;
public TestLaunchServerConfigManager() {
config = LaunchServerConfig.getDefault(LaunchServer.LaunchServerEnv.TEST);
runtimeConfig = new LaunchServerRuntimeConfig();
runtimeConfig.reset();
}
@Override
public LaunchServerConfig readConfig() throws IOException {
return config;
@ -28,10 +35,4 @@ public void writeConfig(LaunchServerConfig 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">
<Appenders>
<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>
</Appenders>
<Loggers>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -61,6 +61,11 @@ public AuthRequestEvent(ClientPermissions permissions, PlayerProfile playerProfi
this.oauth = oauth;
}
@Override
public String getType() {
return "auth";
}
public static class OAuthRequestEvent {
public final String accessToken;
public final String refreshToken;
@ -72,9 +77,4 @@ public OAuthRequestEvent(String accessToken, String refreshToken, long 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 final List<AuthAvailabilityDetails> details;
@LauncherNetworkAPI
public String name;
@LauncherNetworkAPI
@ -48,8 +52,6 @@ public static class AuthAvailability {
@LauncherNetworkAPI
public AuthType secondType;
public final List<AuthAvailabilityDetails> details;
@Deprecated
public AuthAvailability(String name, String displayName, AuthType firstType, AuthType secondType) {
this.name = name;
@ -81,6 +83,4 @@ public enum AuthType {
OTHER
}
}
public interface AuthAvailabilityDetails extends TypeSerializeInterface {
}
}

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