Compare commits

..

No commits in common. "master" and "v5.6.6" have entirely different histories.

73 changed files with 224 additions and 807 deletions

View file

@ -13,24 +13,20 @@
maven { maven {
url "https://jitpack.io/" url "https://jitpack.io/"
} }
maven {
url 'https://maven.gravit-support.ru/repository/jitpack'
credentials {
username = 'gravitlauncher'
password = 'gravitlauncher'
}
}
} }
sourceCompatibility = '21' sourceCompatibility = '21'
targetCompatibility = '21' targetCompatibility = '21'
configurations { configurations {
compileOnlyA
bundleOnly bundleOnly
bundle bundle
hikari
pack pack
launch4j
bundleOnly.extendsFrom bundle bundleOnly.extendsFrom bundle
api.extendsFrom bundle, pack api.extendsFrom bundle, hikari, pack, launch4j
} }
jar { jar {
@ -85,13 +81,6 @@ pack project(':LauncherAPI')
bundle group: 'io.netty', name: 'netty-transport-classes-epoll', version: rootProject['verNetty'] bundle group: 'io.netty', name: 'netty-transport-classes-epoll', version: rootProject['verNetty']
bundle group: 'io.netty', name: 'netty-transport-native-epoll', version: rootProject['verNetty'], classifier: 'linux-x86_64' bundle group: 'io.netty', name: 'netty-transport-native-epoll', version: rootProject['verNetty'], classifier: 'linux-x86_64'
bundle group: 'io.netty', name: 'netty-transport-native-epoll', version: rootProject['verNetty'], classifier: 'linux-aarch_64' bundle group: 'io.netty', name: 'netty-transport-native-epoll', version: rootProject['verNetty'], classifier: 'linux-aarch_64'
bundle group: 'io.netty', name: 'netty-transport-classes-io_uring', version: rootProject['verNetty']
bundle group: 'io.netty', name: 'netty-transport-native-io_uring', version: rootProject['verNetty'], classifier: 'linux-x86_64'
bundle group: 'io.netty', name: 'netty-transport-native-io_uring', version: rootProject['verNetty'], classifier: 'linux-aarch_64'
// Netty
bundle 'org.jboss.marshalling:jboss-marshalling:1.4.11.Final'
bundle 'com.google.protobuf.nano:protobuf-javanano:3.1.0'
//
bundle group: 'org.slf4j', name: 'slf4j-api', version: rootProject['verSlf4j'] bundle group: 'org.slf4j', name: 'slf4j-api', version: rootProject['verSlf4j']
bundle group: 'com.mysql', name: 'mysql-connector-j', version: rootProject['verMySQLConn'] bundle group: 'com.mysql', name: 'mysql-connector-j', version: rootProject['verMySQLConn']
bundle group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: rootProject['verMariaDBConn'] bundle group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: rootProject['verMariaDBConn']
@ -107,26 +96,40 @@ pack project(':LauncherAPI')
annotationProcessor(group: 'org.apache.logging.log4j', name: 'log4j-core', version: rootProject['verLog4j']) annotationProcessor(group: 'org.apache.logging.log4j', name: 'log4j-core', version: rootProject['verLog4j'])
testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter', version: rootProject['verJunit'] testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter', version: rootProject['verJunit']
bundle 'io.micrometer:micrometer-core:1.14.4' hikari 'io.micrometer:micrometer-core:1.13.1'
bundle('com.zaxxer:HikariCP:6.2.1') { hikari('com.zaxxer:HikariCP:5.1.0') {
exclude group: 'javassist' exclude group: 'javassist'
exclude group: 'io.micrometer' exclude group: 'io.micrometer'
exclude group: 'org.slf4j' exclude group: 'org.slf4j'
} }
} }
tasks.register('hikari', Copy) {
duplicatesStrategy = 'EXCLUDE'
into "$buildDir/libs/libraries/hikaricp"
from configurations.hikari
}
tasks.register('dumpLibs', Copy) { tasks.register('dumpLibs', Copy) {
duplicatesStrategy = 'EXCLUDE' duplicatesStrategy = 'EXCLUDE'
dependsOn tasks.hikari
into "$buildDir/libs/libraries" into "$buildDir/libs/libraries"
from configurations.bundleOnly from configurations.bundleOnly
} }
tasks.register('dumpCompileOnlyLibs', Copy) {
duplicatesStrategy = 'EXCLUDE'
into "$buildDir/libs/launcher-libraries-compile"
from configurations.compileOnlyA
}
tasks.register('bundle', Zip) { tasks.register('bundle', Zip) {
duplicatesStrategy = 'EXCLUDE' duplicatesStrategy = 'EXCLUDE'
dependsOn parent.childProjects.Launcher.tasks.build, tasks.dumpLibs, tasks.jar dependsOn parent.childProjects.Launcher.tasks.build, tasks.dumpLibs, tasks.dumpCompileOnlyLibs, tasks.jar
archiveFileName = 'LaunchServer.zip' archiveFileName = 'LaunchServer.zip'
destinationDirectory = file("$buildDir") destinationDirectory = file("$buildDir")
from(tasks.dumpLibs.destinationDir) { into 'libraries' } from(tasks.dumpLibs.destinationDir) { into 'libraries' }
from(tasks.dumpCompileOnlyLibs.destinationDir) { into 'launcher-libraries-compile' }
from(tasks.jar) from(tasks.jar)
from(parent.childProjects.Launcher.tasks.dumpLibs) { into 'launcher-libraries' } from(parent.childProjects.Launcher.tasks.dumpLibs) { into 'launcher-libraries' }
} }
@ -137,7 +140,7 @@ pack project(':LauncherAPI')
from parent.childProjects.Launcher.tasks.dumpLibs from parent.childProjects.Launcher.tasks.dumpLibs
} }
assemble.dependsOn tasks.dumpLibs, tasks.dumpClientLibs, tasks.bundle, tasks.cleanjar assemble.dependsOn tasks.dumpLibs, tasks.dumpCompileOnlyLibs, tasks.dumpClientLibs, tasks.bundle, tasks.cleanjar
publishing { publishing {

View file

@ -2,6 +2,7 @@
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.events.RequestEvent; import pro.gravit.launcher.base.events.RequestEvent;
import pro.gravit.launcher.base.events.request.ProfilesRequestEvent; import pro.gravit.launcher.base.events.request.ProfilesRequestEvent;
import pro.gravit.launcher.base.modules.events.ClosePhase; import pro.gravit.launcher.base.modules.events.ClosePhase;
@ -20,18 +21,21 @@
import pro.gravit.launchserver.modules.events.*; import pro.gravit.launchserver.modules.events.*;
import pro.gravit.launchserver.modules.impl.LaunchServerModulesManager; import pro.gravit.launchserver.modules.impl.LaunchServerModulesManager;
import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.SocketCommandServer;
import pro.gravit.launchserver.socket.handlers.NettyServerSocketHandler; import pro.gravit.launchserver.socket.handlers.NettyServerSocketHandler;
import pro.gravit.launchserver.socket.response.auth.ProfilesResponse;
import pro.gravit.launchserver.socket.response.auth.RestoreResponse; import pro.gravit.launchserver.socket.response.auth.RestoreResponse;
import pro.gravit.utils.command.Command; import pro.gravit.utils.command.Command;
import pro.gravit.utils.command.CommandHandler; import pro.gravit.utils.command.CommandHandler;
import pro.gravit.utils.command.SubCommand; import pro.gravit.utils.command.SubCommand;
import pro.gravit.utils.helper.CommonHelper; import pro.gravit.utils.helper.CommonHelper;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.JVMHelper; import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.SecurityHelper; import pro.gravit.utils.helper.SecurityHelper;
import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.nio.file.*; import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.KeyStore; import java.security.KeyStore;
import java.time.Duration; import java.time.Duration;
import java.time.Instant; import java.time.Instant;
@ -81,7 +85,6 @@ public final class LaunchServer implements Runnable, AutoCloseable, Reconfigurab
public final Path modulesDir; public final Path modulesDir;
public final Path launcherModulesDir; public final Path launcherModulesDir;
public final Path librariesDir; public final Path librariesDir;
public final Path controlFile;
/** /**
* This object contains runtime configuration * This object contains runtime configuration
*/ */
@ -110,7 +113,6 @@ public final class LaunchServer implements Runnable, AutoCloseable, Reconfigurab
// Server // Server
public final CommandHandler commandHandler; public final CommandHandler commandHandler;
public final NettyServerSocketHandler nettyServerSocketHandler; public final NettyServerSocketHandler nettyServerSocketHandler;
public final SocketCommandServer socketCommandServer;
public final ScheduledExecutorService service; public final ScheduledExecutorService service;
public final AtomicBoolean started = new AtomicBoolean(false); public final AtomicBoolean started = new AtomicBoolean(false);
public final LauncherModuleLoader launcherModuleLoader; public final LauncherModuleLoader launcherModuleLoader;
@ -137,7 +139,6 @@ public LaunchServer(LaunchServerDirectories directories, LaunchServerEnv env, La
modulesDir = directories.modules; modulesDir = directories.modules;
launcherModulesDir = directories.launcherModules; launcherModulesDir = directories.launcherModules;
librariesDir = directories.librariesDir; librariesDir = directories.librariesDir;
controlFile = directories.controlFile;
this.shardId = shardId; this.shardId = shardId;
if(!Files.isDirectory(launcherPack)) { if(!Files.isDirectory(launcherPack)) {
Files.createDirectories(launcherPack); Files.createDirectories(launcherPack);
@ -189,7 +190,6 @@ public LaunchServer(LaunchServerDirectories directories, LaunchServerEnv env, La
} }
launcherModuleLoader.init(); launcherModuleLoader.init();
nettyServerSocketHandler = new NettyServerSocketHandler(this); nettyServerSocketHandler = new NettyServerSocketHandler(this);
socketCommandServer = new SocketCommandServer(commandHandler, controlFile);
if(config.sign.checkCertificateExpired) { if(config.sign.checkCertificateExpired) {
checkCertificateExpired(); checkCertificateExpired();
service.scheduleAtFixedRate(this::checkCertificateExpired, 24, 24, TimeUnit.HOURS); service.scheduleAtFixedRate(this::checkCertificateExpired, 24, 24, TimeUnit.HOURS);
@ -353,7 +353,6 @@ public void run() {
} }
})); }));
CommonHelper.newThread("Command Thread", true, commandHandler).start(); CommonHelper.newThread("Command Thread", true, commandHandler).start();
CommonHelper.newThread("Socket Command Thread", true, socketCommandServer).start();
// Sync updates dir // Sync updates dir
CommonHelper.newThread("Profiles and updates sync", true, () -> { CommonHelper.newThread("Profiles and updates sync", true, () -> {
try { try {
@ -462,7 +461,7 @@ public interface LaunchServerConfigManager {
public static class LaunchServerDirectories { public static class LaunchServerDirectories {
public static final String UPDATES_NAME = "updates", public static final String UPDATES_NAME = "updates",
TRUSTSTORE_NAME = "truststore", LAUNCHERLIBRARIES_NAME = "launcher-libraries", TRUSTSTORE_NAME = "truststore", LAUNCHERLIBRARIES_NAME = "launcher-libraries",
LAUNCHERLIBRARIESCOMPILE_NAME = "launcher-libraries-compile", LAUNCHERPACK_NAME = "launcher-pack", KEY_NAME = ".keys", MODULES = "modules", LAUNCHER_MODULES = "launcher-modules", LIBRARIES = "libraries", CONTROL_FILE = "control-file"; LAUNCHERLIBRARIESCOMPILE_NAME = "launcher-libraries-compile", LAUNCHERPACK_NAME = "launcher-pack", KEY_NAME = ".keys", MODULES = "modules", LAUNCHER_MODULES = "launcher-modules", LIBRARIES = "libraries";
public Path updatesDir; public Path updatesDir;
public Path librariesDir; public Path librariesDir;
public Path launcherLibrariesDir; public Path launcherLibrariesDir;
@ -474,7 +473,6 @@ public static class LaunchServerDirectories {
public Path tmpDir; public Path tmpDir;
public Path modules; public Path modules;
public Path launcherModules; public Path launcherModules;
public Path controlFile;
public void collect() { public void collect() {
if (updatesDir == null) updatesDir = getPath(UPDATES_NAME); if (updatesDir == null) updatesDir = getPath(UPDATES_NAME);
@ -488,7 +486,6 @@ public void collect() {
if (modules == null) modules = getPath(MODULES); if (modules == null) modules = getPath(MODULES);
if (launcherModules == null) launcherModules = getPath(LAUNCHER_MODULES); if (launcherModules == null) launcherModules = getPath(LAUNCHER_MODULES);
if (librariesDir == null) librariesDir = getPath(LIBRARIES); if (librariesDir == null) librariesDir = getPath(LIBRARIES);
if (controlFile == null) controlFile = getPath(CONTROL_FILE);
if (tmpDir == null) if (tmpDir == null)
tmpDir = Paths.get(System.getProperty("java.io.tmpdir")).resolve("launchserver-%s".formatted(SecurityHelper.randomStringToken())); tmpDir = Paths.get(System.getProperty("java.io.tmpdir")).resolve("launchserver-%s".formatted(SecurityHelper.randomStringToken()));
} }

View file

@ -36,6 +36,7 @@
import java.nio.file.Path; import java.nio.file.Path;
import java.security.Security; import java.security.Security;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class LaunchServerStarter { public class LaunchServerStarter {
@ -62,7 +63,7 @@ public static void main(String[] args) throws Exception {
directories.collect(); directories.collect();
CertificateManager certificateManager = new CertificateManager(); CertificateManager certificateManager = new CertificateManager();
try { try {
certificateManager.readTrustStore(directories.trustStore); certificateManager.readTrustStore(dir.resolve("truststore"));
} catch (CertificateException e) { } catch (CertificateException e) {
throw new IOException(e); throw new IOException(e);
} }

View file

@ -18,7 +18,7 @@
import java.util.stream.Stream; import java.util.stream.Stream;
public class Main { public class Main {
private static final List<String> classpathOnly = List.of("proguard", "jline", "progressbar", "kotlin"); private static final List<String> classpathOnly = List.of("proguard", "jline", "progressbar", "kotlin", "epoll");
private static final String LOG4J_PROPERTY = "log4j2.configurationFile"; private static final String LOG4J_PROPERTY = "log4j2.configurationFile";
private static final String DEBUG_PROPERTY = "launchserver.main.debug"; private static final String DEBUG_PROPERTY = "launchserver.main.debug";
private static final String LIBRARIES_PROPERTY = "launchserver.dir.libraries"; private static final String LIBRARIES_PROPERTY = "launchserver.dir.libraries";

View file

@ -9,22 +9,15 @@
import java.util.function.Consumer; import java.util.function.Consumer;
public class HikariSQLSourceConfig implements SQLSourceConfig { public class HikariSQLSourceConfig implements SQLSourceConfig {
private transient volatile HikariDataSource dataSource; private transient HikariDataSource dataSource;
private String dsClass; private String dsClass;
private Properties dsProps; private Properties dsProps;
private String driverClass; private String driverClass;
private String jdbcUrl; private String jdbcUrl;
private String username; private String username;
private String password; private String password;
private boolean initializeAtStart;
public void init() { public void init() {
if(initializeAtStart) {
initializeConnection();
}
}
private void initializeConnection() {
if (dataSource != null) { if (dataSource != null) {
return; return;
} }
@ -41,11 +34,6 @@ private void initializeConnection() {
@Override @Override
public Connection getConnection() throws SQLException { public Connection getConnection() throws SQLException {
if(dataSource == null && !initializeAtStart) {
synchronized (this) {
initializeConnection();
}
}
return dataSource.getConnection(); return dataSource.getConnection();
} }

View file

@ -174,7 +174,7 @@ public AuthManager.AuthReport sudo(User user, boolean shadow) throws IOException
} }
@Override @Override
public User checkServer(Client client, String username, String serverID) { public User checkServer(Client client, String username, String serverID) throws IOException {
SQLUser user = (SQLUser) getUserByUsername(username); SQLUser user = (SQLUser) getUserByUsername(username);
if (user == null) { if (user == null) {
return null; return null;
@ -295,9 +295,7 @@ private SQLUser queryUser(String sql, String value) throws SQLException {
user = constructUser(set); user = constructUser(set);
} }
} }
if(user != null) {
user.permissions = requestPermissions(user.uuid.toString()); user.permissions = requestPermissions(user.uuid.toString());
}
return user; return user;
} }

View file

@ -1,5 +1,6 @@
package pro.gravit.launchserver.auth.core; package pro.gravit.launchserver.auth.core;
import pro.gravit.launcher.base.ClientPermissions;
import pro.gravit.launcher.base.request.secure.HardwareReportRequest; import pro.gravit.launcher.base.request.secure.HardwareReportRequest;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthProviderPair; import pro.gravit.launchserver.auth.AuthProviderPair;
@ -43,7 +44,6 @@ public SQLSourceConfig getSQLConfig() {
@Override @Override
public void init(LaunchServer server, AuthProviderPair pair) { public void init(LaunchServer server, AuthProviderPair pair) {
super.init(server, pair); super.init(server, pair);
logger.warn("Method 'mysql' deprecated and may be removed in future release. Please use new 'sql' method: https://gravitlauncher.com/auth");
String userInfoCols = makeUserCols(); String userInfoCols = makeUserCols();
String hardwareInfoCols = "id, hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, graphicCard, banned, publicKey"; String hardwareInfoCols = "id, hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, graphicCard, banned, publicKey";
if (sqlFindHardwareByPublicKey == null) if (sqlFindHardwareByPublicKey == null)

View file

@ -1,7 +1,5 @@
package pro.gravit.launchserver.auth.core; package pro.gravit.launchserver.auth.core;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.auth.PostgreSQLSourceConfig; import pro.gravit.launchserver.auth.PostgreSQLSourceConfig;
import pro.gravit.launchserver.auth.SQLSourceConfig; import pro.gravit.launchserver.auth.SQLSourceConfig;
@ -12,10 +10,4 @@ public class PostgresSQLCoreProvider extends AbstractSQLCoreProvider {
public SQLSourceConfig getSQLConfig() { public SQLSourceConfig getSQLConfig() {
return postgresSQLHolder; return postgresSQLHolder;
} }
@Override
public void init(LaunchServer server, AuthProviderPair pair) {
super.init(server, pair);
logger.warn("Method 'postgresql' deprecated and may be removed in future release. Please use new 'sql' method: https://gravitlauncher.com/auth");
}
} }

View file

@ -41,12 +41,12 @@ public AuthManager.AuthReport authorize(String login, AuthResponse.AuthContext c
} }
@Override @Override
public User checkServer(Client client, String username, String serverID) { public User checkServer(Client client, String username, String serverID) throws IOException {
return null; return null;
} }
@Override @Override
public boolean joinServer(Client client, String username, UUID uuid, String accessToken, String serverID) { public boolean joinServer(Client client, String username, UUID uuid, String accessToken, String serverID) throws IOException {
return false; return false;
} }

View file

@ -1,25 +1,11 @@
package pro.gravit.launchserver.auth.core; package pro.gravit.launchserver.auth.core;
import pro.gravit.launcher.base.request.secure.HardwareReportRequest;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthProviderPair; import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.auth.HikariSQLSourceConfig; import pro.gravit.launchserver.auth.HikariSQLSourceConfig;
import pro.gravit.launchserver.auth.MySQLSourceConfig;
import pro.gravit.launchserver.auth.SQLSourceConfig; import pro.gravit.launchserver.auth.SQLSourceConfig;
import pro.gravit.launchserver.auth.core.interfaces.UserHardware;
import pro.gravit.launchserver.auth.core.interfaces.provider.AuthSupportExtendedCheckServer;
import pro.gravit.launchserver.auth.core.interfaces.provider.AuthSupportHardware;
import pro.gravit.launchserver.auth.core.interfaces.session.UserSessionSupportHardware;
import pro.gravit.launchserver.socket.Client;
import java.io.IOException; public class SQLCoreProvider extends AbstractSQLCoreProvider {
import java.sql.*;
import java.util.Base64;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
public class SQLCoreProvider extends AbstractSQLCoreProvider implements AuthSupportHardware, AuthSupportExtendedCheckServer {
public HikariSQLSourceConfig holder; public HikariSQLSourceConfig holder;
@Override @Override
@ -28,364 +14,14 @@ public void close() {
holder.close(); holder.close();
} }
@Override
public SQLSourceConfig getSQLConfig() {
return holder;
}
public String hardwareIdColumn;
public String tableHWID = "hwids";
public String tableHWIDLog = "hwidLog";
public double criticalCompareLevel = 1.0;
private transient String sqlFindHardwareByPublicKey;
private transient String sqlFindHardwareByData;
private transient String sqlFindHardwareById;
private transient String sqlCreateHardware;
private transient String sqlCreateHWIDLog;
private transient String sqlUpdateHardwarePublicKey;
private transient String sqlUpdateHardwareBanned;
private transient String sqlUpdateUsers;
private transient String sqlUsersByHwidId;
@Override @Override
public void init(LaunchServer server, AuthProviderPair pair) { public void init(LaunchServer server, AuthProviderPair pair) {
holder.init(); holder.init();
super.init(server, pair); super.init(server, pair);
String userInfoCols = makeUserCols();
String hardwareInfoCols = "id, hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, graphicCard, banned, publicKey";
if (sqlFindHardwareByPublicKey == null)
sqlFindHardwareByPublicKey = "SELECT %s FROM %s WHERE publicKey = ?".formatted(hardwareInfoCols, tableHWID);
if (sqlFindHardwareById == null)
sqlFindHardwareById = "SELECT %s FROM %s WHERE id = ?".formatted(hardwareInfoCols, tableHWID);
if (sqlUsersByHwidId == null)
sqlUsersByHwidId = "SELECT %s FROM %s WHERE %s = ?".formatted(userInfoCols, table, hardwareIdColumn);
if (sqlFindHardwareByData == null)
sqlFindHardwareByData = "SELECT %s FROM %s".formatted(hardwareInfoCols, tableHWID);
if (sqlCreateHardware == null)
sqlCreateHardware = "INSERT INTO %s (publickey, hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, graphicCard, battery, banned) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0')".formatted(tableHWID);
if (sqlCreateHWIDLog == null)
sqlCreateHWIDLog = "INSERT INTO %s (hwidId, newPublicKey) VALUES (?, ?)".formatted(tableHWIDLog);
if (sqlUpdateHardwarePublicKey == null)
sqlUpdateHardwarePublicKey = "UPDATE %s SET publicKey = ? WHERE id = ?".formatted(tableHWID);
sqlUpdateHardwareBanned = "UPDATE %s SET banned = ? WHERE id = ?".formatted(tableHWID);
sqlUpdateUsers = "UPDATE %s SET %s = ? WHERE %s = ?".formatted(table, hardwareIdColumn, uuidColumn);
} }
@Override @Override
protected String makeUserCols() { public SQLSourceConfig getSQLConfig() {
return super.makeUserCols().concat(", ").concat(hardwareIdColumn); return holder;
}
@Override
protected SQLUser constructUser(ResultSet set) throws SQLException {
return set.next() ? new SQLUser(UUID.fromString(set.getString(uuidColumn)), set.getString(usernameColumn),
set.getString(accessTokenColumn), set.getString(serverIDColumn), set.getString(passwordColumn), set.getLong(hardwareIdColumn)) : null;
}
private SQLUserHardware fetchHardwareInfo(ResultSet set) throws SQLException {
HardwareReportRequest.HardwareInfo hardwareInfo = new HardwareReportRequest.HardwareInfo();
hardwareInfo.hwDiskId = set.getString("hwDiskId");
hardwareInfo.baseboardSerialNumber = set.getString("baseboardSerialNumber");
byte[] displayId = set.getBytes("displayId");
hardwareInfo.displayId = displayId == null ? null : displayId;
hardwareInfo.bitness = set.getInt("bitness");
hardwareInfo.totalMemory = set.getLong("totalMemory");
hardwareInfo.logicalProcessors = set.getInt("logicalProcessors");
hardwareInfo.physicalProcessors = set.getInt("physicalProcessors");
hardwareInfo.processorMaxFreq = set.getLong("processorMaxFreq");
hardwareInfo.battery = set.getBoolean("battery");
hardwareInfo.graphicCard = set.getString("graphicCard");
byte[] publicKey = set.getBytes("publicKey");
long id = set.getLong("id");
boolean banned = set.getBoolean("banned");
return new SQLUserHardware(hardwareInfo, publicKey, id, banned);
}
private void setUserHardwareId(Connection connection, UUID uuid, long hwidId) throws SQLException {
PreparedStatement s = connection.prepareStatement(sqlUpdateUsers);
s.setLong(1, hwidId);
s.setString(2, uuid.toString());
s.executeUpdate();
}
@Override
public UserHardware getHardwareInfoByPublicKey(byte[] publicKey) {
try (Connection connection = holder.getConnection()) {
connection.setAutoCommit(false);
PreparedStatement s = connection.prepareStatement(sqlFindHardwareByPublicKey);
s.setBytes(1, publicKey);
try (ResultSet set = s.executeQuery()) {
if (set.next()) {
connection.commit();
return fetchHardwareInfo(set);
} else {
connection.commit();
return null;
}
}
} catch (SQLException throwables) {
logger.error("SQL Error", throwables);
return null;
}
}
@Override
public UserHardware getHardwareInfoByData(HardwareReportRequest.HardwareInfo info) {
try (Connection connection = holder.getConnection()) {
connection.setAutoCommit(false);
PreparedStatement s = connection.prepareStatement(sqlFindHardwareByData);
try (ResultSet set = s.executeQuery()) {
while (set.next()) {
SQLUserHardware hw = fetchHardwareInfo(set);
AuthSupportHardware.HardwareInfoCompareResult result = compareHardwareInfo(hw.getHardwareInfo(), info);
if (result.compareLevel > criticalCompareLevel) {
connection.commit();
return hw;
} else {
connection.commit();
}
}
}
} catch (SQLException throwables) {
logger.error("SQL Error", throwables);
}
return null;
}
@Override
public UserHardware getHardwareInfoById(String id) {
try (Connection connection = holder.getConnection()) {
connection.setAutoCommit(false);
PreparedStatement s = connection.prepareStatement(sqlFindHardwareById);
s.setLong(1, Long.parseLong(id));
try (ResultSet set = s.executeQuery()) {
if (set.next()) {
connection.commit();
return fetchHardwareInfo(set);
} else {
connection.commit();
return null;
}
}
} catch (SQLException throwables) {
logger.error("SQL Error", throwables);
return null;
}
}
@Override
public UserHardware createHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey) {
try (Connection connection = holder.getConnection()) {
connection.setAutoCommit(false);
PreparedStatement s = connection.prepareStatement(sqlCreateHardware, Statement.RETURN_GENERATED_KEYS);
s.setBytes(1, publicKey);
s.setString(2, hardwareInfo.hwDiskId);
s.setString(3, hardwareInfo.baseboardSerialNumber);
s.setBytes(4, hardwareInfo.displayId == null ? null : hardwareInfo.displayId);
s.setInt(5, hardwareInfo.bitness);
s.setLong(6, hardwareInfo.totalMemory);
s.setInt(7, hardwareInfo.logicalProcessors);
s.setInt(8, hardwareInfo.physicalProcessors);
s.setLong(9, hardwareInfo.processorMaxFreq);
s.setString(10, hardwareInfo.graphicCard);
s.setBoolean(11, hardwareInfo.battery);
s.executeUpdate();
try (ResultSet generatedKeys = s.getGeneratedKeys()) {
if (generatedKeys.next()) {
//writeHwidLog(connection, generatedKeys.getLong(1), publicKey);
long id = generatedKeys.getLong(1);
connection.commit();
return new SQLUserHardware(hardwareInfo, publicKey, id, false);
}
}
connection.commit();
return null;
} catch (SQLException throwables) {
logger.error("SQL Error", throwables);
return null;
}
}
@Override
public void connectUserAndHardware(UserSession userSession, UserHardware hardware) {
AbstractSQLCoreProvider.SQLUserSession SQLUserSession = (AbstractSQLCoreProvider.SQLUserSession) userSession;
SQLUser SQLUser = (SQLUser) SQLUserSession.getUser();
SQLUserHardware SQLUserHardware = (SQLUserHardware) hardware;
if (SQLUser.hwidId == SQLUserHardware.id) return;
SQLUser.hwidId = SQLUserHardware.id;
try (Connection connection = holder.getConnection()) {
setUserHardwareId(connection, SQLUser.getUUID(), SQLUserHardware.id);
} catch (SQLException throwables) {
logger.error("SQL Error", throwables);
}
}
@Override
public void addPublicKeyToHardwareInfo(UserHardware hardware, byte[] publicKey) {
SQLUserHardware SQLUserHardware = (SQLUserHardware) hardware;
SQLUserHardware.publicKey = publicKey;
try (Connection connection = holder.getConnection()) {
connection.setAutoCommit(false);
PreparedStatement s = connection.prepareStatement(sqlUpdateHardwarePublicKey);
s.setBytes(1, publicKey);
s.setLong(2, SQLUserHardware.id);
s.executeUpdate();
connection.commit();
} catch (SQLException e) {
logger.error("SQL error", e);
}
}
@Override
public Iterable<User> getUsersByHardwareInfo(UserHardware hardware) {
List<User> users = new LinkedList<>();
try (Connection c = holder.getConnection()) {
c.setAutoCommit(false);
PreparedStatement s = c.prepareStatement(sqlUsersByHwidId);
s.setLong(1, Long.parseLong(hardware.getId()));
s.setQueryTimeout(MySQLSourceConfig.TIMEOUT);
try (ResultSet set = s.executeQuery()) {
while (!set.isLast()) {
users.add(constructUser(set));
}
}
c.commit();
} catch (SQLException e) {
logger.error("SQL error", e);
return null;
}
return users;
}
@Override
public void banHardware(UserHardware hardware) {
SQLUserHardware SQLUserHardware = (SQLUserHardware) hardware;
SQLUserHardware.banned = true;
try (Connection connection = holder.getConnection()) {
PreparedStatement s = connection.prepareStatement(sqlUpdateHardwareBanned);
s.setBoolean(1, true);
s.setLong(2, SQLUserHardware.id);
s.executeUpdate();
} catch (SQLException e) {
logger.error("SQL Error", e);
}
}
@Override
public void unbanHardware(UserHardware hardware) {
SQLUserHardware SQLUserHardware = (SQLUserHardware) hardware;
SQLUserHardware.banned = false;
try (Connection connection = holder.getConnection()) {
PreparedStatement s = connection.prepareStatement(sqlUpdateHardwareBanned);
s.setBoolean(1, false);
s.setLong(2, SQLUserHardware.id);
s.executeUpdate();
} catch (SQLException e) {
logger.error("SQL error", e);
}
}
@Override
protected AbstractSQLCoreProvider.SQLUserSession createSession(AbstractSQLCoreProvider.SQLUser user) {
return new SQLUserSession(user);
}
@Override
public UserSession extendedCheckServer(Client client, String username, String serverID) {
AbstractSQLCoreProvider.SQLUser user = (AbstractSQLCoreProvider.SQLUser) getUserByUsername(username);
if (user == null) {
return null;
}
if (user.getUsername().equals(username) && user.getServerId().equals(serverID)) {
return createSession(user);
}
return null;
}
public class SQLUserSession extends AbstractSQLCoreProvider.SQLUserSession implements UserSessionSupportHardware {
private transient SQLUser SQLUser;
protected transient SQLUserHardware hardware;
public SQLUserSession(AbstractSQLCoreProvider.SQLUser user) {
super(user);
SQLUser = (SQLUser) user;
}
@Override
public String getHardwareId() {
return SQLUser.hwidId == 0 ? null : String.valueOf(SQLUser.hwidId);
}
@Override
public UserHardware getHardware() {
if(hardware == null) {
hardware = (SQLUserHardware) getHardwareInfoById(String.valueOf(SQLUser.hwidId));
}
return hardware;
}
}
public static class SQLUserHardware implements UserHardware {
private final HardwareReportRequest.HardwareInfo hardwareInfo;
private final long id;
private byte[] publicKey;
private boolean banned;
public SQLUserHardware(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, long id, boolean banned) {
this.hardwareInfo = hardwareInfo;
this.publicKey = publicKey;
this.id = id;
this.banned = banned;
}
@Override
public HardwareReportRequest.HardwareInfo getHardwareInfo() {
return hardwareInfo;
}
@Override
public byte[] getPublicKey() {
return publicKey;
}
@Override
public String getId() {
return String.valueOf(id);
}
@Override
public boolean isBanned() {
return banned;
}
@Override
public String toString() {
return "SQLUserHardware{" +
"hardwareInfo=" + hardwareInfo +
", publicKey=" + (publicKey == null ? null : new String(Base64.getEncoder().encode(publicKey))) +
", id=" + id +
", banned=" + banned +
'}';
}
}
public static class SQLUser extends AbstractSQLCoreProvider.SQLUser {
protected long hwidId;
public SQLUser(UUID uuid, String username, String accessToken, String serverId, String password, long hwidId) {
super(uuid, username, accessToken, serverId, password);
this.hwidId = hwidId;
}
@Override
public String toString() {
return "SQLUser{" +
"uuid=" + uuid +
", username='" + username + '\'' +
", permissions=" + permissions +
", hwidId=" + hwidId +
'}';
}
} }
} }

View file

@ -6,5 +6,5 @@
import java.io.IOException; import java.io.IOException;
public interface AuthSupportExtendedCheckServer { public interface AuthSupportExtendedCheckServer {
UserSession extendedCheckServer(Client client, String username, String serverID); UserSession extendedCheckServer(Client client, String username, String serverID) throws IOException;
} }

View file

@ -143,7 +143,7 @@ public void init(LaunchServer server, AuthProviderPair pair) {
} }
@Override @Override
public User checkServer(Client client, String username, String serverID) { public User checkServer(Client client, String username, String serverID) throws IOException {
var savedServerId = sqlSessionStore.getServerIdByUsername(username); var savedServerId = sqlSessionStore.getServerIdByUsername(username);
if (!serverID.equals(savedServerId)) { if (!serverID.equals(savedServerId)) {
return null; return null;
@ -153,7 +153,7 @@ public User checkServer(Client client, String username, String serverID) {
} }
@Override @Override
public boolean joinServer(Client client, String username, UUID uuid, String accessToken, String serverID) { public boolean joinServer(Client client, String username, UUID uuid, String accessToken, String serverID) throws IOException {
User user; User user;
try { try {
user = createUserFromMinecraftToken(accessToken); user = createUserFromMinecraftToken(accessToken);

View file

@ -3,6 +3,8 @@
import pro.gravit.launchserver.auth.SQLSourceConfig; import pro.gravit.launchserver.auth.SQLSourceConfig;
import pro.gravit.utils.helper.LogHelper; import pro.gravit.utils.helper.LogHelper;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.UUID; import java.util.UUID;

View file

@ -4,7 +4,9 @@
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launchserver.binary.tasks.LauncherBuildTask; import pro.gravit.launchserver.binary.tasks.LauncherBuildTask;
import pro.gravit.utils.helper.CommonHelper; import pro.gravit.utils.helper.CommonHelper;
import pro.gravit.utils.helper.IOHelper;
import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View file

@ -56,7 +56,7 @@ public final byte[] getDigest() {
public void init() { public void init() {
} }
public final boolean sync() { public final boolean sync() throws IOException {
try { try {
var target = syncBinaryFile.toString(); var target = syncBinaryFile.toString();
var path = server.config.updatesProvider.download(null, List.of(target)).get(target); var path = server.config.updatesProvider.download(null, List.of(target)).get(target);

View file

@ -32,7 +32,6 @@ public void invoke(String... args) throws Exception {
boolean value = Boolean.parseBoolean(args[0]); boolean value = Boolean.parseBoolean(args[0]);
LoggerContext ctx = (LoggerContext) LogManager.getContext(false); LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration(); Configuration config = ctx.getConfiguration();
config.getWatchManager().setIntervalSeconds(-1);
LoggerConfig loggerConfig = config.getLoggerConfig("pro.gravit"); LoggerConfig loggerConfig = config.getLoggerConfig("pro.gravit");
loggerConfig.setLevel(value ? Level.TRACE : Level.DEBUG); loggerConfig.setLevel(value ? Level.TRACE : Level.DEBUG);
ctx.updateLoggers(); ctx.updateLoggers();

View file

@ -13,6 +13,7 @@
import pro.gravit.utils.command.CommandException; import pro.gravit.utils.command.CommandException;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import java.io.BufferedWriter;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Collections; import java.util.Collections;

View file

@ -2,13 +2,17 @@
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.profiles.ClientProfile; import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launcher.base.profiles.ClientProfileBuilder; import pro.gravit.launcher.base.profiles.ClientProfileBuilder;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.CommonHelper;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import java.io.IOException; import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;

View file

@ -5,7 +5,9 @@
import pro.gravit.launcher.base.profiles.ClientProfile; import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.IOHelper;
import java.nio.file.Files;
import java.util.UUID; import java.util.UUID;
public class DeleteProfileCommand extends Command { public class DeleteProfileCommand extends Command {

View file

@ -22,7 +22,7 @@ public String getUsageDescription() {
} }
@Override @Override
public void invoke(String... args) { public void invoke(String... args) throws Exception {
for(var profile : server.getProfiles()) { for(var profile : server.getProfiles()) {
logger.info("{} ({}) {}", profile.getTitle(), profile.getVersion().toString(), profile.isLimited() ? "limited" : ""); logger.info("{} ({}) {}", profile.getTitle(), profile.getVersion().toString(), profile.isLimited() ? "limited" : "");
} }

View file

@ -2,10 +2,14 @@
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.profiles.ClientProfile; import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.helper.MakeProfileHelper; import pro.gravit.launchserver.helper.MakeProfileHelper;
import pro.gravit.utils.helper.IOHelper;
import java.io.Writer;
public class MakeProfileCommand extends Command { public class MakeProfileCommand extends Command {
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();

View file

@ -2,10 +2,17 @@
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.profiles.ClientProfile; import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.IOHelper;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID; import java.util.UUID;
public class SaveProfilesCommand extends Command { public class SaveProfilesCommand extends Command {

View file

@ -117,7 +117,7 @@ public void invoke(String... args) throws Exception {
Files.deleteIfExists(proguardConf.mappings); Files.deleteIfExists(proguardConf.mappings);
} }
}); });
return commands; return null;
} }
public static class ProGuardMultiReleaseFixer implements LauncherBuildTask { public static class ProGuardMultiReleaseFixer implements LauncherBuildTask {

View file

@ -1,5 +1,6 @@
package pro.gravit.launchserver.config; package pro.gravit.launchserver.config;
import io.netty.channel.epoll.Epoll;
import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LogLevel;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -18,7 +19,6 @@
import pro.gravit.launchserver.components.AuthLimiterComponent; import pro.gravit.launchserver.components.AuthLimiterComponent;
import pro.gravit.launchserver.components.Component; import pro.gravit.launchserver.components.Component;
import pro.gravit.launchserver.components.ProGuardComponent; import pro.gravit.launchserver.components.ProGuardComponent;
import pro.gravit.launchserver.socket.NettyObjectFactory;
import java.util.*; import java.util.*;
@ -64,7 +64,12 @@ public static LaunchServerConfig getDefault(LaunchServer.LaunchServerEnv env) {
newConfig.netty.fileServerEnabled = true; newConfig.netty.fileServerEnabled = true;
newConfig.netty.binds = new NettyBindAddress[]{new NettyBindAddress("0.0.0.0", 9274)}; newConfig.netty.binds = new NettyBindAddress[]{new NettyBindAddress("0.0.0.0", 9274)};
newConfig.netty.performance = new NettyPerformanceConfig(); newConfig.netty.performance = new NettyPerformanceConfig();
newConfig.netty.performance.mode = NettyObjectFactory.NettyFactoryMode.AUTO; try {
newConfig.netty.performance.usingEpoll = Epoll.isAvailable();
} catch (Throwable e) {
// Epoll class line 51+ catch (Exception) but Error will be thrown by System.load
newConfig.netty.performance.usingEpoll = false;
} // such as on ARM
newConfig.netty.performance.bossThread = 2; newConfig.netty.performance.bossThread = 2;
newConfig.netty.performance.workerThread = 8; newConfig.netty.performance.workerThread = 8;
newConfig.netty.performance.schedulerThread = 2; newConfig.netty.performance.schedulerThread = 2;
@ -272,7 +277,7 @@ public static class NettyConfig {
} }
public static class NettyPerformanceConfig { public static class NettyPerformanceConfig {
public NettyObjectFactory.NettyFactoryMode mode = NettyObjectFactory.NettyFactoryMode.AUTO; public boolean usingEpoll;
public int bossThread; public int bossThread;
public int workerThread; public int workerThread;
public int schedulerThread; public int schedulerThread;

View file

@ -49,6 +49,7 @@ public static ClientProfile makeProfile(ClientProfile.Version version, String ti
// Official Mojang launcher java arguments // Official Mojang launcher java arguments
if (version.compareTo(ClientProfileVersions.MINECRAFT_1_12_2) <= 0) { if (version.compareTo(ClientProfileVersions.MINECRAFT_1_12_2) <= 0) {
// lwjgl3ify arguments https://github.com/GTNewHorizons/lwjgl3ify // lwjgl3ify arguments https://github.com/GTNewHorizons/lwjgl3ify
jvmArgs.add("-Djava.security.manager=allow");
jvmArgs.add("--add-opens"); jvmArgs.add("--add-opens");
jvmArgs.add("java.base/jdk.internal.loader=ALL-UNNAMED"); jvmArgs.add("java.base/jdk.internal.loader=ALL-UNNAMED");
jvmArgs.add("--add-opens"); jvmArgs.add("--add-opens");

View file

@ -29,7 +29,6 @@
public class CertificateManager { public class CertificateManager {
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
public LauncherTrustManager trustManager; public LauncherTrustManager trustManager;
private Path truststorePath;
public void writePrivateKey(Path file, PrivateKey privateKey) throws IOException { public void writePrivateKey(Path file, PrivateKey privateKey) throws IOException {
writePrivateKey(IOHelper.newWriter(file), privateKey); writePrivateKey(IOHelper.newWriter(file), privateKey);
@ -92,7 +91,6 @@ public X509CertificateHolder readCertificate(Reader reader) throws IOException {
} }
public void readTrustStore(Path dir) throws IOException, CertificateException { public void readTrustStore(Path dir) throws IOException, CertificateException {
this.truststorePath = dir;
if (!IOHelper.isDir(dir)) { if (!IOHelper.isDir(dir)) {
Files.createDirectories(dir); Files.createDirectories(dir);
try { try {
@ -133,8 +131,4 @@ public LauncherTrustManager.CheckClassResult checkClass(Class<?> clazz) {
X509Certificate[] certificates = JVMHelper.getCertificates(clazz); X509Certificate[] certificates = JVMHelper.getCertificates(clazz);
return trustManager.checkCertificates(certificates, trustManager::stdCertificateChecker); return trustManager.checkCertificates(certificates, trustManager::stdCertificateChecker);
} }
public Path getTruststorePath() {
return truststorePath;
}
} }

View file

@ -1,10 +1,20 @@
package pro.gravit.launchserver.manangers; package pro.gravit.launchserver.manangers;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.core.hasher.HashedDir; import pro.gravit.launcher.core.hasher.HashedDir;
import pro.gravit.launcher.core.serialize.HInput;
import pro.gravit.launcher.core.serialize.HOutput;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.modules.events.LaunchServerUpdatesSyncEvent;
import pro.gravit.utils.helper.IOHelper;
import java.io.IOException; import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.stream.Stream;
public class UpdatesManager { public class UpdatesManager {
private final LaunchServer server; private final LaunchServer server;
@ -14,12 +24,12 @@ public UpdatesManager(LaunchServer server) {
} }
@Deprecated @Deprecated
public void readUpdatesFromCache() { public void readUpdatesFromCache() throws IOException {
} }
@Deprecated @Deprecated
public void readUpdatesDir() { public void readUpdatesDir() throws IOException {
} }

View file

@ -4,6 +4,7 @@
import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup; import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpObjectAggregator;
@ -35,9 +36,14 @@ public class LauncherNettyServer implements AutoCloseable {
public LauncherNettyServer(LaunchServer server) { public LauncherNettyServer(LaunchServer server) {
LaunchServerConfig.NettyConfig config = server.config.netty; LaunchServerConfig.NettyConfig config = server.config.netty;
NettyObjectFactory.setMode(config.performance.mode); NettyObjectFactory.setUsingEpoll(config.performance.usingEpoll);
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
logger.info("Netty usage {} transport mode", NettyObjectFactory.getMode()); if (config.performance.usingEpoll) {
logger.debug("Netty: Epoll enabled");
}
if (config.performance.usingEpoll && !Epoll.isAvailable()) {
logger.error("Epoll is not available: (netty,perfomance.usingEpoll configured wrongly)", Epoll.unavailabilityCause());
}
bossGroup = NettyObjectFactory.newEventLoopGroup(config.performance.bossThread, "LauncherNettyServer.bossGroup"); bossGroup = NettyObjectFactory.newEventLoopGroup(config.performance.bossThread, "LauncherNettyServer.bossGroup");
workerGroup = NettyObjectFactory.newEventLoopGroup(config.performance.workerThread, "LauncherNettyServer.workerGroup"); workerGroup = NettyObjectFactory.newEventLoopGroup(config.performance.workerThread, "LauncherNettyServer.workerGroup");
serverBootstrap = new ServerBootstrap(); serverBootstrap = new ServerBootstrap();

View file

@ -2,58 +2,30 @@
import io.netty.channel.ChannelFactory; import io.netty.channel.ChannelFactory;
import io.netty.channel.EventLoopGroup; import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.ServerChannel; import io.netty.channel.ServerChannel;
import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollIoHandler;
import io.netty.channel.epoll.EpollServerSocketChannel; import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioIoHandler; import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.uring.IoUring;
import io.netty.channel.uring.IoUringIoHandler;
import io.netty.channel.uring.IoUringServerSocketChannel;
public class NettyObjectFactory { public class NettyObjectFactory {
private static NettyFactoryMode mode; private static boolean epoll = false;
public static void setMode(NettyFactoryMode mode) { public static void setUsingEpoll(boolean value) {
NettyObjectFactory.mode = mode; epoll = value;
if(mode == NettyFactoryMode.AUTO) {
if(IoUring.isAvailable()) {
NettyObjectFactory.mode = NettyFactoryMode.IO_URING;
return;
}
if(Epoll.isAvailable()) {
NettyObjectFactory.mode = NettyFactoryMode.EPOLL;
return;
}
NettyObjectFactory.mode = NettyFactoryMode.NIO;
}
}
public static NettyFactoryMode getMode() {
return mode;
} }
public static EventLoopGroup newEventLoopGroup(int threads, String poolName) { public static EventLoopGroup newEventLoopGroup(int threads, String poolName) {
return switch (mode) { if (epoll)
case AUTO -> null; return new EpollEventLoopGroup(threads);
case NIO -> new MultiThreadIoEventLoopGroup(threads, NioIoHandler.newFactory()); else
case EPOLL -> new MultiThreadIoEventLoopGroup(threads, EpollIoHandler.newFactory()); return new NioEventLoopGroup(threads);
case IO_URING -> new MultiThreadIoEventLoopGroup(threads, IoUringIoHandler.newFactory());
};
} }
public static ChannelFactory<? extends ServerChannel> getServerSocketChannelFactory() { public static ChannelFactory<? extends ServerChannel> getServerSocketChannelFactory() {
return switch (mode) { if (epoll)
case AUTO -> null; return EpollServerSocketChannel::new;
case NIO -> NioServerSocketChannel::new; else
case EPOLL -> EpollServerSocketChannel::new; return NioServerSocketChannel::new;
case IO_URING -> IoUringServerSocketChannel::new;
};
}
public enum NettyFactoryMode {
AUTO, NIO, EPOLL, IO_URING
} }
} }

View file

@ -1,94 +0,0 @@
package pro.gravit.launchserver.socket;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launchserver.config.log4j.LogAppender;
import pro.gravit.utils.command.CommandHandler;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class SocketCommandServer implements Runnable {
private final Logger logger = LogManager.getLogger(SocketCommandServer.class);
private ServerSocketChannel channel;
private Path path;
private UnixDomainSocketAddress address;
private ServerSocketChannel serverChannel;
private CommandHandler commandHandler;
private transient SocketChannel clientChannel;
public SocketCommandServer(CommandHandler commandHandler, Path path) {
this.commandHandler = commandHandler;
this.path = path;
}
private void runCommand(SocketChannel channel, String command) {
logger.info("Command '{}' from socket", command);
clientChannel = channel;
try {
commandHandler.evalNative(command, false);
} catch (Throwable e) {
logger.error("Error when execute command", e);
} finally {
clientChannel = null;
}
}
@Override
public void run() {
try {
Files.deleteIfExists(path);
this.address = UnixDomainSocketAddress.of(path);
serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
serverChannel.configureBlocking(true);
serverChannel.bind(address);
LogAppender.getInstance().addListener((logEvent -> {
if(clientChannel != null && clientChannel.isOpen()) {
try {
String s = logEvent.getMessage().getFormattedMessage()+"\n";
byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
clientChannel.write(buffer);
} catch (Throwable ignored) {
}
}
}));
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
SocketChannel channel = serverChannel.accept();
try (channel) {
channel.configureBlocking(true);
String command = null;
mark:
while (true) {
int bytesRead = channel.read(buffer);
if (bytesRead < 0) {
break;
}
for (var i = 0; i < buffer.limit(); i++) {
if (buffer.get(i) == '\n') {
command = new String(buffer.array(), 0, i);
break mark;
}
}
}
if (command != null) {
runCommand(channel, command);
}
} finally {
buffer.clear();
}
}
} catch (Throwable e) {
logger.error("Unix command socket server error", e);
}
}
}

View file

@ -22,6 +22,7 @@
import java.time.ZoneId; import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField; import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalAccessor;
import java.time.temporal.UnsupportedTemporalTypeException; import java.time.temporal.UnsupportedTemporalTypeException;
import java.util.Arrays; import java.util.Arrays;

View file

@ -7,7 +7,7 @@
public interface WebSocketServerResponse extends WebSocketRequest { public interface WebSocketServerResponse extends WebSocketRequest {
String getType(); String getType();
void execute(ChannelHandlerContext ctx, Client client); void execute(ChannelHandlerContext ctx, Client client) throws Exception;
default ThreadSafeStatus getThreadSafeStatus() { default ThreadSafeStatus getThreadSafeStatus() {
return ThreadSafeStatus.READ; return ThreadSafeStatus.READ;

View file

@ -23,7 +23,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) { public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
sendResult(new CurrentUserRequestEvent(collectUserInfoFromClient(server, client))); sendResult(new CurrentUserRequestEvent(collectUserInfoFromClient(server, client)));
} }
} }

View file

@ -44,7 +44,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) { public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
if (accessToken == null && !client.isAuth && needUserInfo) { if (accessToken == null && !client.isAuth && needUserInfo) {
sendError("Invalid request"); sendError("Invalid request");
return; return;

View file

@ -12,7 +12,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) { public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
if(!client.isAuth || client.auth == null || client.getUser() == null) { if(!client.isAuth || client.auth == null || client.getUser() == null) {
sendError("Access denied"); sendError("Access denied");
return; return;

View file

@ -14,7 +14,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) { public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
if(!client.isAuth || client.auth == null || client.getUser() == null) { if(!client.isAuth || client.auth == null || client.getUser() == null) {
sendError("Access denied"); sendError("Access denied");
return; return;

View file

@ -12,7 +12,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) { public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
sendResult(new GetConnectUUIDRequestEvent(connectUUID, server.shardId)); sendResult(new GetConnectUUIDRequestEvent(connectUUID, server.shardId));
} }
} }

View file

@ -28,6 +28,7 @@
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
public class ClientLauncherProcess { public class ClientLauncherProcess {
public final List<String> pre = new LinkedList<>(); public final List<String> pre = new LinkedList<>();

View file

@ -141,6 +141,7 @@ public void cancel() {
} }
} }
tasks.clear(); tasks.clear();
executor.shutdownNow();
} }
public boolean isCanceled() { public boolean isCanceled() {

View file

@ -12,6 +12,7 @@
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.util.*; import java.util.*;
public final class ClientProfile implements Comparable<ClientProfile> { public final class ClientProfile implements Comparable<ClientProfile> {

View file

@ -154,7 +154,7 @@ public static String getRefreshToken() {
public static void reconnect() throws Exception { public static void reconnect() throws Exception {
getRequestService().connect(); getRequestService().open();
restore(); restore();
} }

View file

@ -3,6 +3,7 @@
import java.io.IOException; import java.io.IOException;
public final class RequestException extends IOException { public final class RequestException extends IOException {
private static final long serialVersionUID = 7558237657082664821L;
public RequestException(String message) { public RequestException(String message) {

View file

@ -6,7 +6,7 @@
public interface RequestService { public interface RequestService {
<T extends WebSocketEvent> CompletableFuture<T> request(Request<T> request) throws IOException; <T extends WebSocketEvent> CompletableFuture<T> request(Request<T> request) throws IOException;
void connect() throws Exception; void open() throws Exception;
void registerEventHandler(EventHandler handler); void registerEventHandler(EventHandler handler);

View file

@ -9,7 +9,6 @@
import java.net.URI; import java.net.URI;
import java.net.http.HttpClient; import java.net.http.HttpClient;
import java.net.http.WebSocket; import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -34,7 +33,7 @@ public abstract class ClientJSONPoint implements WebSocket.Listener {
private final Object sendSyncObject = new Object(); private final Object sendSyncObject = new Object();
private volatile StringBuilder builder = new StringBuilder(); private volatile StringBuilder builder = new StringBuilder();
public ClientJSONPoint(final String uri) { public ClientJSONPoint(final String uri) throws SSLException {
this(URI.create(uri)); this(URI.create(uri));
} }
@ -64,7 +63,7 @@ public ClientJSONPoint(URI uri) {
} }
} }
public void connect() throws Exception { public void open() throws Exception {
webSocket = webSocketBuilder.buildAsync(uri, this).get(); webSocket = webSocketBuilder.buildAsync(uri, this).get();
} }
@ -98,17 +97,6 @@ public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String re
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason); return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
} }
@Override
public void onOpen(WebSocket webSocket) {
onOpen();
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onBinary(WebSocket webSocket, ByteBuffer data, boolean last) {
return WebSocket.Listener.super.onBinary(webSocket, data, last);
}
@Override @Override
public void onError(WebSocket webSocket, Throwable error) { public void onError(WebSocket webSocket, Throwable error) {
LogHelper.error(error); LogHelper.error(error);
@ -126,7 +114,7 @@ public void send(String text) {
abstract void onOpen(); abstract void onOpen();
public void close() { public void close() throws InterruptedException {
webSocket.abort(); webSocket.abort();
} }

View file

@ -33,7 +33,7 @@ public abstract class ClientWebSocketService extends ClientJSONPoint {
public OnCloseCallback onCloseCallback; public OnCloseCallback onCloseCallback;
public ReconnectCallback reconnectCallback; public ReconnectCallback reconnectCallback;
public ClientWebSocketService(String address) { public ClientWebSocketService(String address) throws SSLException {
super(createURL(address)); super(createURL(address));
this.gson = Launcher.gsonManager.gson; this.gson = Launcher.gsonManager.gson;
this.onConnect = true; this.onConnect = true;

View file

@ -45,7 +45,7 @@ public <T extends WebSocketEvent> CompletableFuture<T> request(Request<T> reques
} }
@Override @Override
public void connect() { public void open() {
} }

View file

@ -11,12 +11,9 @@
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
import java.io.IOException; import java.io.IOException;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.HashSet; import java.util.HashSet;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
@ -43,7 +40,11 @@ public static CompletableFuture<StdWebSocketService> initWebSockets(String addre
service.openAsync(() -> { service.openAsync(() -> {
future.complete(service); future.complete(service);
JVMHelper.RUNTIME.addShutdownHook(new Thread(() -> { JVMHelper.RUNTIME.addShutdownHook(new Thread(() -> {
try {
service.close(); service.close();
} catch (InterruptedException e) {
LogHelper.error(e);
}
})); }));
}, future::completeExceptionally); }, future::completeExceptionally);
return future; return future;

View file

@ -26,7 +26,7 @@ public <T extends WebSocketEvent> CompletableFuture<T> request(Request<T> reques
} }
@Override @Override
public void connect() { public void open() {
} }

View file

@ -7,9 +7,9 @@
public class ClientVersionTest { public class ClientVersionTest {
@Test @Test
public void parseTest() { public void parseTest() {
Assertions.assertEquals("1.0.0", ClientProfile.Version.of("1.0.0").toCleanString()); Assertions.assertEquals(ClientProfile.Version.of("1.0.0").toCleanString(), "1.0.0");
Assertions.assertEquals("1.0.0.1", ClientProfile.Version.of("1.0.0-1").toCleanString()); Assertions.assertEquals(ClientProfile.Version.of("1.0.0-1").toCleanString(), "1.0.0.1");
Assertions.assertEquals("1.0.0", ClientProfile.Version.of("-----1.0.0").toCleanString()); Assertions.assertEquals(ClientProfile.Version.of("-----1.0.0").toCleanString(), "1.0.0");
} }
@Test @Test

View file

@ -49,12 +49,12 @@ public void dependenciesTest() {
moduleManager.loadModule(new Depend3Module()); moduleManager.loadModule(new Depend3Module());
moduleManager.loadModule(new MainModule()); moduleManager.loadModule(new MainModule());
moduleManager.initModules(null); moduleManager.initModules(null);
Assertions.assertEquals(LauncherModule.InitStatus.FINISH, moduleManager.getModule("depend1").getInitStatus()); Assertions.assertEquals(moduleManager.getModule("depend1").getInitStatus(), LauncherModule.InitStatus.FINISH);
Assertions.assertEquals(LauncherModule.InitStatus.FINISH, moduleManager.getModule("depend2").getInitStatus()); Assertions.assertEquals(moduleManager.getModule("depend2").getInitStatus(), LauncherModule.InitStatus.FINISH);
Assertions.assertEquals(LauncherModule.InitStatus.FINISH, moduleManager.getModule("depend3").getInitStatus()); Assertions.assertEquals(moduleManager.getModule("depend3").getInitStatus(), LauncherModule.InitStatus.FINISH);
Assertions.assertEquals(LauncherModule.InitStatus.FINISH, moduleManager.getModule("internal").getInitStatus()); Assertions.assertEquals(moduleManager.getModule("internal").getInitStatus(), LauncherModule.InitStatus.FINISH);
Assertions.assertEquals(LauncherModule.InitStatus.FINISH, moduleManager.getModule("virtual").getInitStatus()); Assertions.assertEquals(moduleManager.getModule("virtual").getInitStatus(), LauncherModule.InitStatus.FINISH);
Assertions.assertEquals(LauncherModule.InitStatus.FINISH, moduleManager.getModule("main").getInitStatus()); Assertions.assertEquals(moduleManager.getModule("main").getInitStatus(), LauncherModule.InitStatus.FINISH);
} }
@Test @Test
@ -62,7 +62,7 @@ public void cyclicTest() {
moduleManager.loadModule(new CyclicDependModule()); moduleManager.loadModule(new CyclicDependModule());
moduleManager.loadModule(new Cyclic2DependModule()); moduleManager.loadModule(new Cyclic2DependModule());
moduleManager.initModules(null); moduleManager.initModules(null);
Assertions.assertEquals(LauncherModule.InitStatus.FINISH, moduleManager.getModule("cyclic1").getInitStatus()); Assertions.assertEquals(moduleManager.getModule("cyclic1").getInitStatus(), LauncherModule.InitStatus.FINISH);
Assertions.assertEquals(LauncherModule.InitStatus.FINISH, moduleManager.getModule("cyclic2").getInitStatus()); Assertions.assertEquals(moduleManager.getModule("cyclic2").getInitStatus(), LauncherModule.InitStatus.FINISH);
} }
} }

View file

@ -16,10 +16,10 @@ public Depend1Module() {
@Override @Override
public void init(LauncherInitContext initContext) { public void init(LauncherInitContext initContext) {
InternalModule module = modulesManager.getModule(InternalModule.class); InternalModule module = modulesManager.getModule(InternalModule.class);
Assertions.assertEquals(InitStatus.FINISH, module.getInitStatus()); Assertions.assertEquals(module.getInitStatus(), InitStatus.FINISH);
Depend3Module module1 = modulesManager.getModule(Depend3Module.class); Depend3Module module1 = modulesManager.getModule(Depend3Module.class);
Assertions.assertEquals(InitStatus.FINISH, module1.getInitStatus()); Assertions.assertEquals(module1.getInitStatus(), InitStatus.FINISH);
VirtualInterface virtualInterface = modulesManager.getModuleByInterface(VirtualInterface.class); VirtualInterface virtualInterface = modulesManager.getModuleByInterface(VirtualInterface.class);
Assertions.assertEquals(InitStatus.FINISH, ((LauncherModule) virtualInterface).getInitStatus()); Assertions.assertEquals(((LauncherModule) virtualInterface).getInitStatus(), InitStatus.FINISH);
} }
} }

View file

@ -17,8 +17,8 @@ public MainModule() {
@Override @Override
public void init(LauncherInitContext initContext) { public void init(LauncherInitContext initContext) {
Depend1Module module = modulesManager.getModule(Depend1Module.class); Depend1Module module = modulesManager.getModule(Depend1Module.class);
Assertions.assertEquals(InitStatus.FINISH, module.getInitStatus()); Assertions.assertEquals(module.getInitStatus(), InitStatus.FINISH);
Depend2Module module2 = modulesManager.getModule(Depend2Module.class); Depend2Module module2 = modulesManager.getModule(Depend2Module.class);
Assertions.assertEquals(InitStatus.FINISH, module2.getInitStatus()); Assertions.assertEquals(module2.getInitStatus(), InitStatus.FINISH);
} }
} }

View file

@ -88,7 +88,7 @@ private static void realMain(String[] args) throws Throwable {
ClientParams params = readParams(new InetSocketAddress("127.0.0.1", Launcher.getConfig().clientPort)); ClientParams params = readParams(new InetSocketAddress("127.0.0.1", Launcher.getConfig().clientPort));
ClientLauncherMethods.verifyNoAgent(); ClientLauncherMethods.verifyNoAgent();
if(params.timestamp > System.currentTimeMillis() || params.timestamp + 30*1000 < System.currentTimeMillis() ) { if(params.timestamp > System.currentTimeMillis() || params.timestamp + 30*1000 < System.currentTimeMillis() ) {
LogHelper.error("Timestamp failed: current %d | params %d | diff %d", System.currentTimeMillis(), params.timestamp, System.currentTimeMillis() - params.timestamp); LogHelper.error("Timestamp failed. Exit");
ClientLauncherMethods.exitLauncher(-662); ClientLauncherMethods.exitLauncher(-662);
return; return;
} }
@ -124,7 +124,7 @@ private static void realMain(String[] args) throws Throwable {
LogHelper.dev("Classpath entry %s", e); LogHelper.dev("Classpath entry %s", e);
} }
} }
List<URL> classpathURLs = classpath.stream().map(IOHelper::toURL).toList(); List<URL> classpathURLs = classpath.stream().map(IOHelper::toURL).collect(Collectors.toList());
// Start client with WatchService monitoring // Start client with WatchService monitoring
RequestService service; RequestService service;
if (params.offlineMode) { if (params.offlineMode) {

View file

@ -282,7 +282,7 @@ public enum WalkAction {
@FunctionalInterface @FunctionalInterface
public interface WalkCallback { public interface WalkCallback {
WalkAction walked(String path, String name, HashedEntry entry); WalkAction walked(String path, String name, HashedEntry entry) throws IOException;
} }
public static class FindRecursiveResult { public static class FindRecursiveResult {

View file

@ -1,6 +1,7 @@
package pro.gravit.utils; package pro.gravit.utils;
public class HookException extends RuntimeException { public class HookException extends RuntimeException {
private static final long serialVersionUID = -529141998961943161L;
public HookException(String message) { public HookException(String message) {
super(message); super(message);

View file

@ -6,7 +6,7 @@ public final class Version implements Comparable<Version> {
public static final int MAJOR = 5; public static final int MAJOR = 5;
public static final int MINOR = 6; public static final int MINOR = 6;
public static final int PATCH = 11; public static final int PATCH = 6;
public static final int BUILD = 1; public static final int BUILD = 1;
public static final Version.Type RELEASE = Type.STABLE; public static final Version.Type RELEASE = Type.STABLE;
public final int major; public final int major;

View file

@ -1,6 +1,7 @@
package pro.gravit.utils.command; package pro.gravit.utils.command;
public final class CommandException extends Exception { public final class CommandException extends Exception {
private static final long serialVersionUID = -6588814993972117772L;
public CommandException(String message) { public CommandException(String message) {

View file

@ -10,18 +10,8 @@
import java.util.Map; import java.util.Map;
public abstract class CommandHandler implements Runnable { public abstract class CommandHandler implements Runnable {
protected final List<Category> categories; private final List<Category> categories = new ArrayList<>();
protected final CommandCategory baseCategory; private final CommandCategory baseCategory = new BaseCommandCategory();
public CommandHandler() {
this.categories = new ArrayList<>();
this.baseCategory = new BaseCommandCategory();
}
protected CommandHandler(List<Category> categories, CommandCategory baseCategory) {
this.categories = categories;
this.baseCategory = baseCategory;
}
public void eval(String line, boolean bell) { public void eval(String line, boolean bell) {
LogHelper.info("Command '%s'", line); LogHelper.info("Command '%s'", line);

View file

@ -5,8 +5,6 @@
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class StdCommandHandler extends CommandHandler { public class StdCommandHandler extends CommandHandler {
private final BufferedReader reader; private final BufferedReader reader;
@ -16,31 +14,6 @@ public StdCommandHandler(boolean readCommands) {
reader = readCommands ? IOHelper.newReader(System.in) : null; reader = readCommands ? IOHelper.newReader(System.in) : null;
} }
public StdCommandHandler(InputStream stream) {
super();
this.reader = IOHelper.newReader(stream);
}
public StdCommandHandler(BufferedReader reader) {
super();
this.reader = reader;
}
protected StdCommandHandler(List<Category> categories, CommandCategory baseCategory, boolean readCommands) {
super(categories, baseCategory);
this.reader = readCommands ? IOHelper.newReader(System.in) : null;
}
protected StdCommandHandler(List<Category> categories, CommandCategory baseCategory, InputStream stream) {
super(categories, baseCategory);
this.reader = IOHelper.newReader(stream);
}
protected StdCommandHandler(List<Category> categories, CommandCategory baseCategory, BufferedReader reader) {
super(categories, baseCategory);
this.reader = reader;
}
@Override @Override
public void bell() { public void bell() {
} }
@ -64,16 +37,4 @@ public void clear() throws IOException {
public String readLine() throws IOException { public String readLine() throws IOException {
return reader == null ? null : reader.readLine(); return reader == null ? null : reader.readLine();
} }
public StdCommandHandler ofHandler(CommandHandler commandHandler, boolean readCommands) {
return new StdCommandHandler(commandHandler.categories, commandHandler.baseCategory, readCommands);
}
public StdCommandHandler ofHandler(CommandHandler commandHandler, InputStream stream) {
return new StdCommandHandler(commandHandler.categories, commandHandler.baseCategory, stream);
}
public StdCommandHandler ofHandler(CommandHandler commandHandler, BufferedReader reader) {
return new StdCommandHandler(commandHandler.categories, commandHandler.baseCategory, reader);
}
} }

View file

@ -221,40 +221,38 @@ public static ArgsParseResult parseJavaArgs(List<String> args) {
continue; continue;
} }
} }
switch (arg) { if(arg.equals("--module-path") || arg.equals("-p")) {
case "--module-path", "-p" -> {
prevArgType = PrevArgType.MODULE_PATH; prevArgType = PrevArgType.MODULE_PATH;
continue; continue;
} }
case "--classpath", "-cp" -> { if(arg.equals("--classpath") || arg.equals("-cp")) {
prevArgType = PrevArgType.CLASSPATH; prevArgType = PrevArgType.CLASSPATH;
continue; continue;
} }
case "--add-modules" -> { if(arg.equals("--add-modules")) {
prevArgType = PrevArgType.ADD_MODULES; prevArgType = PrevArgType.ADD_MODULES;
continue; continue;
} }
case "--add-opens" -> { if(arg.equals("--add-opens")) {
prevArgType = PrevArgType.ADD_OPENS; prevArgType = PrevArgType.ADD_OPENS;
continue; continue;
} }
case "--add-exports" -> { if(arg.equals("--add-exports")) {
prevArgType = PrevArgType.ADD_EXPORTS; prevArgType = PrevArgType.ADD_EXPORTS;
continue; continue;
} }
case "--add-reads" -> { if(arg.equals("--add-reads")) {
prevArgType = PrevArgType.ADD_READS; prevArgType = PrevArgType.ADD_READS;
continue; continue;
} }
case "--module", "-m" -> { if(arg.equals("--module") || arg.equals("-m")) {
prevArgType = PrevArgType.MODULE; prevArgType = PrevArgType.MODULE;
continue; continue;
} }
case "-jar" -> { if(arg.equals("-jar")) {
prevArgType = PrevArgType.JAR; prevArgType = PrevArgType.JAR;
continue; continue;
} }
}
jvmArgs.add(arg); jvmArgs.add(arg);
} }
return new ArgsParseResult(conf, classpath, jvmArgs, mainClass, mainModule, jarFile, args); return new ArgsParseResult(conf, classpath, jvmArgs, mainClass, mainModule, jarFile, args);

View file

@ -83,7 +83,7 @@ public static byte[] getClassBytes(Class<?> clazz, ClassLoader classLoader) thro
return IOHelper.read(classLoader.getResourceAsStream(getClassFile(clazz))); return IOHelper.read(classLoader.getResourceAsStream(getClassFile(clazz)));
} }
public static InputStream getClassBytesStream(Class<?> clazz) { public static InputStream getClassBytesStream(Class<?> clazz) throws IOException {
return getClassBytesStream(clazz, clazz.getClassLoader()); return getClassBytesStream(clazz, clazz.getClassLoader());
} }

View file

@ -68,7 +68,7 @@ public void addTransformer(ClassTransformer transformer) {
} }
instrumentation.addTransformer(new ClassFileTransformer() { instrumentation.addTransformer(new ClassFileTransformer() {
@Override @Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) { public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
if(transformer.filter(null, className)) { if(transformer.filter(null, className)) {
return transformer.transform(null, className, protectionDomain, classfileBuffer); return transformer.transform(null, className, protectionDomain, classfileBuffer);
} }

View file

@ -123,9 +123,6 @@ protected Class<?> findClass(String name) throws ClassNotFoundException {
@Override @Override
public String findLibrary(String name) { public String findLibrary(String name) {
if(nativePath == null) {
return null;
}
return nativePath.concat(IOHelper.PLATFORM_SEPARATOR).concat(JVMHelper.NATIVE_PREFIX).concat(name).concat(JVMHelper.NATIVE_EXTENSION); return nativePath.concat(IOHelper.PLATFORM_SEPARATOR).concat(JVMHelper.NATIVE_PREFIX).concat(name).concat(JVMHelper.NATIVE_EXTENSION);
} }

View file

@ -262,9 +262,6 @@ protected Class<?> findClass(String moduleName, String name) {
@Override @Override
public String findLibrary(String name) { public String findLibrary(String name) {
if(nativePath == null) {
return null;
}
return nativePath.concat(IOHelper.PLATFORM_SEPARATOR).concat(JVMHelper.NATIVE_PREFIX).concat(name).concat(JVMHelper.NATIVE_EXTENSION); return nativePath.concat(IOHelper.PLATFORM_SEPARATOR).concat(JVMHelper.NATIVE_PREFIX).concat(name).concat(JVMHelper.NATIVE_EXTENSION);
} }

View file

@ -30,8 +30,8 @@ public void main() {
String json2 = gson.toJson(new MyTestClass2("BBBB"), TestInterface.class); String json2 = gson.toJson(new MyTestClass2("BBBB"), TestInterface.class);
TestInterface test1 = gson.fromJson(json, TestInterface.class); TestInterface test1 = gson.fromJson(json, TestInterface.class);
TestInterface test2 = gson.fromJson(json2, TestInterface.class); TestInterface test2 = gson.fromJson(json2, TestInterface.class);
Assertions.assertEquals("AAAA", test1.get()); Assertions.assertEquals(test1.get(), "AAAA");
Assertions.assertEquals("BBBB", test2.get()); Assertions.assertEquals(test2.get(), "BBBB");
} }
public interface TestInterface { public interface TestInterface {

View file

@ -32,7 +32,6 @@
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.*; import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ServerWrapper extends JsonConfigurable<ServerWrapper.Config> { public class ServerWrapper extends JsonConfigurable<ServerWrapper.Config> {
@ -122,7 +121,6 @@ public void run(String... args) throws Throwable {
} }
LogHelper.debug("Read ServerWrapperConfig.json"); LogHelper.debug("Read ServerWrapperConfig.json");
loadConfig(); loadConfig();
config.applyEnv();
updateLauncherConfig(); updateLauncherConfig();
Launcher.applyLauncherEnv(Objects.requireNonNullElse(config.env, LauncherConfig.LauncherEnvironment.STD)); Launcher.applyLauncherEnv(Objects.requireNonNullElse(config.env, LauncherConfig.LauncherEnvironment.STD));
StdWebSocketService service = StdWebSocketService.initWebSockets(config.address).get(); StdWebSocketService service = StdWebSocketService.initWebSockets(config.address).get();
@ -306,38 +304,5 @@ public void apply() {
ConfigService.checkServerConfig.needProperties = checkServerNeedProperties; ConfigService.checkServerConfig.needProperties = checkServerNeedProperties;
} }
} }
public void applyEnv() {
this.authId = applyEnvOrDefault("SERVERWRAPPER_AUTH_ID", this.authId);
this.address = applyEnvOrDefault("SERVERWRAPPER_ADDRESS", this.address);
this.serverName = applyEnvOrDefault("SERVERWRAPPER_SERVER_NAME", this.serverName);
this.encodedServerEcPublicKey = applyEnvOrDefault("SERVERWRAPPER_EC_PUBLIC_KEY", Base64.getUrlDecoder()::decode, null);
this.encodedServerRsaPublicKey = applyEnvOrDefault("SERVERWRAPPER_RSA_PUBLIC_KEY", Base64.getUrlDecoder()::decode, null);
{
String token = System.getenv("SERVERWRAPPER_CHECK_SERVER_TOKEN");
if(token != null) {
if(extendedTokens == null) {
extendedTokens = new HashMap<>();
}
extendedTokens.put("checkServer", new Request.ExtendedToken(token, 0L));
}
}
}
private static String applyEnvOrDefault(String envName, String def) {
String value = System.getenv(envName);
if(value == null) {
return def;
}
return value;
}
private static<T> T applyEnvOrDefault(String envName, Function<String, T> mappingFunction, T def) {
String value = System.getenv(envName);
if(value == null) {
return def;
}
return mappingFunction.apply(value);
}
} }
} }

View file

@ -30,11 +30,8 @@ public ServerWrapperSetup() throws IOException {
public void run() throws Exception { public void run() throws Exception {
ServerWrapper wrapper = ServerWrapper.wrapper; ServerWrapper wrapper = ServerWrapper.wrapper;
String jarName = System.getenv("SERVERWRAPPER_JAR_NAME");
if(jarName == null) {
System.out.println("Print server jar filename:"); System.out.println("Print server jar filename:");
jarName = commands.commandHandler.readLine(); String jarName = commands.commandHandler.readLine();
}
Path jarPath = Paths.get(jarName); Path jarPath = Paths.get(jarName);
String mainClassName; String mainClassName;
String agentClassName; String agentClassName;
@ -59,18 +56,14 @@ public void run() throws Exception {
if (agentClassName != null) { if (agentClassName != null) {
LogHelper.info("Found PremainClass %s", agentClassName); LogHelper.info("Found PremainClass %s", agentClassName);
} }
if(wrapper.config.serverName == null || wrapper.config.serverName.isEmpty()) {
System.out.println("Print your server name:"); System.out.println("Print your server name:");
wrapper.config.serverName = commands.commandHandler.readLine(); wrapper.config.serverName = commands.commandHandler.readLine();
}
wrapper.config.mainclass = mainClassName; wrapper.config.mainclass = mainClassName;
boolean altMode = false; boolean altMode = false;
for (int i = 0; i < 10; ++i) { for (int i = 0; i < 10; ++i) {
if(!Request.isAvailable() || Request.getRequestService().isClosed()) { if(!Request.isAvailable() || Request.getRequestService().isClosed()) {
if(wrapper.config.address == null || wrapper.config.address.isEmpty()) {
System.out.println("Print launchserver websocket host( ws://host:port/api ):"); System.out.println("Print launchserver websocket host( ws://host:port/api ):");
wrapper.config.address = commands.commandHandler.readLine(); wrapper.config.address = commands.commandHandler.readLine();
}
StdWebSocketService service; StdWebSocketService service;
try { try {
service = StdWebSocketService.initWebSockets(wrapper.config.address).get(); service = StdWebSocketService.initWebSockets(wrapper.config.address).get();
@ -80,11 +73,9 @@ public void run() throws Exception {
} }
Request.setRequestService(service); Request.setRequestService(service);
} }
if(wrapper.config.extendedTokens == null || wrapper.config.extendedTokens.get("checkServer") == null) {
System.out.println("Print server token:"); System.out.println("Print server token:");
String checkServerToken = commands.commandHandler.readLine(); String checkServerToken = commands.commandHandler.readLine();
wrapper.config.extendedTokens.put("checkServer", new Request.ExtendedToken(checkServerToken, 0)); wrapper.config.extendedTokens.put("checkServer", new Request.ExtendedToken(checkServerToken, 0));
}
wrapper.updateLauncherConfig(); wrapper.updateLauncherConfig();
try { try {
wrapper.restore(); wrapper.restore();
@ -102,9 +93,7 @@ public void run() throws Exception {
} }
if(wrapper.profile != null && wrapper.profile.getVersion().compareTo(ClientProfileVersions.MINECRAFT_1_18) >= 0) { if(wrapper.profile != null && wrapper.profile.getVersion().compareTo(ClientProfileVersions.MINECRAFT_1_18) >= 0) {
LogHelper.info("Switch to alternative start mode (1.18)"); LogHelper.info("Switch to alternative start mode (1.18)");
if(!wrapper.config.classpath.contains(jarName)) {
wrapper.config.classpath.add(jarName); wrapper.config.classpath.add(jarName);
}
wrapper.config.classLoaderConfig = ClientProfile.ClassLoaderConfig.LAUNCHER; wrapper.config.classLoaderConfig = ClientProfile.ClassLoaderConfig.LAUNCHER;
altMode = true; altMode = true;
} }

View file

@ -1,11 +1,11 @@
plugins { plugins {
id 'com.github.johnrengelman.shadow' version '8.1.1' apply false id 'com.github.johnrengelman.shadow' version '7.1.2' apply false
id 'maven-publish' id 'maven-publish'
id 'signing' id 'signing'
id 'org.openjfx.javafxplugin' version '0.1.0' apply false id 'org.openjfx.javafxplugin' version '0.1.0' apply false
} }
group = 'pro.gravit.launcher' group = 'pro.gravit.launcher'
version = '5.6.11' version = '5.6.6'
apply from: 'props.gradle' apply from: 'props.gradle'
@ -30,13 +30,6 @@
maven { maven {
url "https://jitpack.io/" url "https://jitpack.io/"
} }
maven {
url 'https://maven.gravit-support.ru/repository/jitpack'
credentials {
username = 'gravitlauncher'
password = 'gravitlauncher'
}
}
} }
jar { jar {

Binary file not shown.

View file

@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-all.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

3
gradlew vendored
View file

@ -86,7 +86,8 @@ done
# shellcheck disable=SC2034 # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum

@ -1 +1 @@
Subproject commit eeea07098281c5cc98feffaae9b5a01677ca2eb7 Subproject commit 65f882bd90623aa1581ad24cfa4f52563ea95bc0

View file

@ -1,18 +1,18 @@
project.ext { project.ext {
verAsm = '9.7.1' verAsm = '9.7'
verNetty = '4.2.0.RC4' verNetty = '4.1.111.Final'
verOshiCore = '6.8.0' verOshiCore = '6.6.2'
verJunit = '5.11.4' verJunit = '5.10.2'
verJansi = '2.4.1' verJansi = '2.4.1'
verJline = '3.29.0' verJline = '3.26.1'
verJwt = '0.12.6' verJwt = '0.12.5'
verGson = '2.12.1' verGson = '2.11.0'
verBcpkix = '1.80' verBcpkix = '1.78.1'
verSlf4j = '2.0.17' verSlf4j = '2.0.13'
verLog4j = '2.24.3' verLog4j = '2.23.1'
verMySQLConn = '9.2.0' verMySQLConn = '9.0.0'
verMariaDBConn = '3.5.1' verMariaDBConn = '3.4.0'
verPostgreSQLConn = '42.7.5' verPostgreSQLConn = '42.7.3'
verH2Conn = '2.3.232' verH2Conn = '2.2.224'
verProguard = '7.7.0' verProguard = '7.5.0'
} }