Compare commits

...

14 commits

Author SHA1 Message Date
Gravita
60f742b3ef Merge tag 'v5.4.3' into dev
5.4.3 stable
2023-07-16 14:33:42 +07:00
Gravita
7fee478552 Merge branch 'release/5.4.3' 2023-07-16 14:33:33 +07:00
Gravita
7efe7c8611 [ANY] Update modules 2023-07-16 14:32:34 +07:00
Gravita
d4abf27989 [ANY] 5.4.3 stable 2023-07-16 14:12:09 +07:00
Gravita
e887035920 [FIX] Remove experimental warning 2023-07-16 13:59:45 +07:00
Gravita
890591d2d2 [ANY] Update modules 2023-07-16 13:52:22 +07:00
Gravita
82938fe8d4 [FIX] Remove old style assets folder 2023-07-16 13:36:45 +07:00
Gravita
cebe47939a [ANY] Update asm 2023-07-16 13:19:23 +07:00
Gravita
fd24ca0ca7 [ANY] Update depencencides 2023-07-16 13:18:00 +07:00
Gravita
663685934b [ANY] Update gradle wrapper 2023-07-16 13:15:06 +07:00
Gravita
43d944bee1 [ANY] Update modules 2023-07-16 13:13:54 +07:00
microwin7
3a82065889
[FEATURE] JVMHelper class extension (#667) 2023-07-16 13:12:41 +07:00
microwin7
55c0cdfa0d
[FEATURE] Replaced with use TimeUnit (#666) 2023-07-16 13:11:58 +07:00
microwin7
b12c43676b
[FEATURE] Replaced String.format to formatted (#665) 2023-07-16 13:11:45 +07:00
37 changed files with 172 additions and 149 deletions

View file

@ -50,7 +50,6 @@
* Not a singletron
*/
public final class LaunchServer implements Runnable, AutoCloseable, Reconfigurable {
public static final Class<? extends LauncherBinary> defaultLauncherEXEBinaryClass = null;
/**
* Working folder path
*/
@ -512,7 +511,7 @@ public void collect() {
launcherPackDir = getPath(LAUNCHERPACK_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()));
tmpDir = Paths.get(System.getProperty("java.io.tmpdir")).resolve("launchserver-%s".formatted(SecurityHelper.randomStringToken()));
}
private Path getPath(String dirName) {

View file

@ -92,7 +92,7 @@ public void visit(final String name, final Object value) {
if ("value".equals(name)) {
if (value.getClass() != String.class)
throw new IllegalArgumentException(
String.format("Invalid annotation with value class %s", field.getClass().getName()));
"Invalid annotation with value class %s".formatted(field.getClass().getName()));
valueName.set(value.toString());
}
}
@ -126,7 +126,7 @@ public void visit(final String name, final Object value) {
}
} else {
if (initMethod == null) {
throw new IllegalArgumentException(String.format("Not found init in target: %s", classNode.name));
throw new IllegalArgumentException("Not found init in target: %s".formatted(classNode.name));
}
List<FieldInsnNode> putFieldNodes = Arrays.stream(initMethod.instructions.toArray())
.filter(node -> node instanceof FieldInsnNode && node.getOpcode() == Opcodes.PUTFIELD).map(p -> (FieldInsnNode) p)
@ -173,8 +173,7 @@ private static InsnList serializeValue(Object value) {
return ((Serializer) serializerEntry.getValue()).serialize(value);
}
}
throw new UnsupportedOperationException(String.format("Serialization of type %s is not supported",
value.getClass()));
throw new UnsupportedOperationException("Serialization of type %s is not supported".formatted(value.getClass()));
}
public static boolean isSerializableValue(Object value) {

View file

@ -72,11 +72,11 @@ public final void link(LaunchServer srv) {
links.forEach((k, v) -> {
AuthProviderPair pair = srv.config.getAuthProviderPair(v);
if (pair == null) {
throw new NullPointerException(String.format("Auth %s link failed. Pair %s not found", name, v));
throw new NullPointerException("Auth %s link failed. Pair %s not found".formatted(name, v));
}
if ("core".equals(k)) {
if (pair.core == null)
throw new NullPointerException(String.format("Auth %s link failed. %s.core is null", name, v));
throw new NullPointerException("Auth %s link failed. %s.core is null".formatted(name, v));
core = pair.core;
}
});

View file

@ -11,6 +11,8 @@
import java.sql.Connection;
import java.sql.SQLException;
import static java.util.concurrent.TimeUnit.MINUTES;
public final class MySQLSourceConfig implements AutoCloseable, SQLSourceConfig {
public static final int TIMEOUT = VerifyHelper.verifyInt(
@ -33,7 +35,7 @@ public final class MySQLSourceConfig implements AutoCloseable, SQLSourceConfig {
private String password;
private String database;
private String timezone;
private long hikariMaxLifetime = 30*60*1000; // 30 minutes
private long hikariMaxLifetime = MINUTES.toMillis(30);
private boolean useHikari;
// Cache
@ -109,7 +111,6 @@ public synchronized Connection getConnection() throws SQLException {
hikariConfig.setMaximumPoolSize(MAX_POOL_SIZE);
hikariConfig.setConnectionTestQuery("SELECT 1");
hikariConfig.setConnectionTimeout(1000);
hikariConfig.setAutoCommit(true);
hikariConfig.setLeakDetectionThreshold(2000);
hikariConfig.setMaxLifetime(hikariMaxLifetime);
// Set HikariCP pool

View file

@ -10,6 +10,9 @@
import java.sql.Connection;
import java.sql.SQLException;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
public final class PostgreSQLSourceConfig implements AutoCloseable, SQLSourceConfig {
public static final int TIMEOUT = VerifyHelper.verifyInt(
Integer.parseUnsignedInt(System.getProperty("launcher.postgresql.idleTimeout", Integer.toString(5000))),
@ -27,7 +30,7 @@ public final class PostgreSQLSourceConfig implements AutoCloseable, SQLSourceCon
private String password;
private String database;
private long hikariMaxLifetime = 30*60*1000; // 30 minutes
private long hikariMaxLifetime = MINUTES.toMillis(30); // 30 minutes
// Cache
private transient DataSource source;
@ -67,7 +70,7 @@ public synchronized Connection getConnection() throws SQLException {
hikariSource.setPoolName(poolName);
hikariSource.setMinimumIdle(0);
hikariSource.setMaximumPoolSize(MAX_POOL_SIZE);
hikariSource.setIdleTimeout(TIMEOUT * 1000L);
hikariSource.setIdleTimeout(SECONDS.toMillis(TIMEOUT));
hikariSource.setMaxLifetime(hikariMaxLifetime);
// Replace source with hds

View file

@ -28,9 +28,12 @@
import java.util.List;
import java.util.UUID;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.SECONDS;
public abstract class AbstractSQLCoreProvider extends AuthCoreProvider {
public final transient Logger logger = LogManager.getLogger();
public int expireSeconds = 3600;
public long expireSeconds = HOURS.toSeconds(1);
public String uuidColumn;
public String usernameColumn;
public String accessTokenColumn;
@ -129,7 +132,7 @@ public AuthManager.AuthReport refreshAccessToken(String refreshToken, AuthRespon
return null;
}
var accessToken = LegacySessionHelper.makeAccessJwtTokenFromString(user, LocalDateTime.now(Clock.systemUTC()).plusSeconds(expireSeconds), server.keyAgreementManager.ecdsaPrivateKey);
return new AuthManager.AuthReport(null, accessToken, refreshToken, expireSeconds * 1000L, new SQLUserSession(user));
return new AuthManager.AuthReport(null, accessToken, refreshToken, SECONDS.toMillis(expireSeconds), new SQLUserSession(user));
}
@Override
@ -153,9 +156,9 @@ public AuthManager.AuthReport authorize(String login, AuthResponse.AuthContext c
if (minecraftAccess) {
String minecraftAccessToken = SecurityHelper.randomStringToken();
updateAuth(SQLUser, minecraftAccessToken);
return AuthManager.AuthReport.ofOAuthWithMinecraft(minecraftAccessToken, accessToken, refreshToken, expireSeconds * 1000L, session);
return AuthManager.AuthReport.ofOAuthWithMinecraft(minecraftAccessToken, accessToken, refreshToken, SECONDS.toMillis(expireSeconds), session);
} else {
return AuthManager.AuthReport.ofOAuth(accessToken, refreshToken, expireSeconds * 1000L, session);
return AuthManager.AuthReport.ofOAuth(accessToken, refreshToken, SECONDS.toMillis(expireSeconds), session);
}
}
@ -170,20 +173,20 @@ public void init(LaunchServer server) {
if (table == null) logger.error("table cannot be null");
// Prepare SQL queries
String userInfoCols = makeUserCols();
queryByUUIDSQL = customQueryByUUIDSQL != null ? customQueryByUUIDSQL : String.format("SELECT %s FROM %s WHERE %s=? LIMIT 1", userInfoCols,
table, uuidColumn);
queryByUsernameSQL = customQueryByUsernameSQL != null ? customQueryByUsernameSQL : String.format("SELECT %s FROM %s WHERE %s=? LIMIT 1",
userInfoCols, table, usernameColumn);
queryByUUIDSQL = customQueryByUUIDSQL != null ? customQueryByUUIDSQL :
"SELECT %s FROM %s WHERE %s=? LIMIT 1".formatted(userInfoCols, table, uuidColumn);
queryByUsernameSQL = customQueryByUsernameSQL != null ? customQueryByUsernameSQL :
"SELECT %s FROM %s WHERE %s=? LIMIT 1".formatted(userInfoCols, table, usernameColumn);
queryByLoginSQL = customQueryByLoginSQL != null ? customQueryByLoginSQL : queryByUsernameSQL;
updateAuthSQL = customUpdateAuthSQL != null ? customUpdateAuthSQL : String.format("UPDATE %s SET %s=?, %s=NULL WHERE %s=?",
table, accessTokenColumn, serverIDColumn, uuidColumn);
updateServerIDSQL = customUpdateServerIdSQL != null ? customUpdateServerIdSQL : String.format("UPDATE %s SET %s=? WHERE %s=?",
table, serverIDColumn, uuidColumn);
updateAuthSQL = customUpdateAuthSQL != null ? customUpdateAuthSQL :
"UPDATE %s SET %s=?, %s=NULL WHERE %s=?".formatted(table, accessTokenColumn, serverIDColumn, uuidColumn);
updateServerIDSQL = customUpdateServerIdSQL != null ? customUpdateServerIdSQL :
"UPDATE %s SET %s=? WHERE %s=?".formatted(table, serverIDColumn, uuidColumn);
if (isEnabledPermissions()) {
if(isEnabledRoles()) {
queryPermissionsByUUIDSQL = customQueryPermissionsByUUIDSQL != null ? customQueryPermissionsByUUIDSQL :
@ -198,14 +201,14 @@ public void init(LaunchServer server) {
"INNER JOIN " + permissionsTable + " pr ON r." + rolesUUIDColumn + "=substring(pr." + permissionsPermissionColumn + " from 6) or r." + rolesNameColumn + "=substring(pr." + permissionsPermissionColumn + " from 6)\n" +
"WHERE pr." + permissionsUUIDColumn + " = ?";
} else {
queryPermissionsByUUIDSQL = customQueryPermissionsByUUIDSQL != null ? customQueryPermissionsByUUIDSQL : String.format("SELECT (%s) FROM %s WHERE %s=?",
permissionsPermissionColumn, permissionsTable, permissionsUUIDColumn);
queryPermissionsByUUIDSQL = customQueryPermissionsByUUIDSQL != null ? customQueryPermissionsByUUIDSQL :
"SELECT (%s) FROM %s WHERE %s=?".formatted(permissionsPermissionColumn, permissionsTable, permissionsUUIDColumn);
}
}
}
protected String makeUserCols() {
return String.format("%s, %s, %s, %s, %s", uuidColumn, usernameColumn, accessTokenColumn, serverIDColumn, passwordColumn);
return "%s, %s, %s, %s, %s".formatted(uuidColumn, usernameColumn, accessTokenColumn, serverIDColumn, passwordColumn);
}
protected void updateAuth(User user, String accessToken) throws IOException {

View file

@ -46,21 +46,21 @@ public void init(LaunchServer server) {
String userInfoCols = makeUserCols();
String hardwareInfoCols = "id, hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, graphicCard, banned, publicKey";
if (sqlFindHardwareByPublicKey == null)
sqlFindHardwareByPublicKey = String.format("SELECT %s FROM %s WHERE `publicKey` = ?", hardwareInfoCols, tableHWID);
sqlFindHardwareByPublicKey = "SELECT %s FROM %s WHERE `publicKey` = ?".formatted(hardwareInfoCols, tableHWID);
if (sqlFindHardwareById == null)
sqlFindHardwareById = String.format("SELECT %s FROM %s WHERE `id` = ?", hardwareInfoCols, tableHWID);
sqlFindHardwareById = "SELECT %s FROM %s WHERE `id` = ?".formatted(hardwareInfoCols, tableHWID);
if (sqlUsersByHwidId == null)
sqlUsersByHwidId = String.format("SELECT %s FROM %s WHERE `%s` = ?", userInfoCols, table, hardwareIdColumn);
sqlUsersByHwidId = "SELECT %s FROM %s WHERE `%s` = ?".formatted(userInfoCols, table, hardwareIdColumn);
if (sqlFindHardwareByData == null)
sqlFindHardwareByData = String.format("SELECT %s FROM %s", hardwareInfoCols, tableHWID);
sqlFindHardwareByData = "SELECT %s FROM %s".formatted(hardwareInfoCols, tableHWID);
if (sqlCreateHardware == null)
sqlCreateHardware = String.format("INSERT INTO `%s` (`publickey`, `hwDiskId`, `baseboardSerialNumber`, `displayId`, `bitness`, `totalMemory`, `logicalProcessors`, `physicalProcessors`, `processorMaxFreq`, `graphicCard`, `battery`, `banned`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0')", tableHWID);
sqlCreateHardware = "INSERT INTO `%s` (`publickey`, `hwDiskId`, `baseboardSerialNumber`, `displayId`, `bitness`, `totalMemory`, `logicalProcessors`, `physicalProcessors`, `processorMaxFreq`, `graphicCard`, `battery`, `banned`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0')".formatted(tableHWID);
if (sqlCreateHWIDLog == null)
sqlCreateHWIDLog = String.format("INSERT INTO %s (`hwidId`, `newPublicKey`) VALUES (?, ?)", tableHWIDLog);
sqlCreateHWIDLog = "INSERT INTO %s (`hwidId`, `newPublicKey`) VALUES (?, ?)".formatted(tableHWIDLog);
if (sqlUpdateHardwarePublicKey == null)
sqlUpdateHardwarePublicKey = String.format("UPDATE %s SET `publicKey` = ? WHERE `id` = ?", tableHWID);
sqlUpdateHardwareBanned = String.format("UPDATE %s SET `banned` = ? WHERE `id` = ?", tableHWID);
sqlUpdateUsers = String.format("UPDATE %s SET `%s` = ? WHERE `%s` = ?", table, hardwareIdColumn, uuidColumn);
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

View file

@ -21,6 +21,8 @@
import java.util.Base64;
import java.util.Date;
import static java.util.concurrent.TimeUnit.SECONDS;
public class AdvancedProtectHandler extends StdProtectHandler implements SecureProtectHandler, HardwareProtectHandler, JoinServerProtectHandler {
private transient final Logger logger = LogManager.getLogger();
public boolean enableHardwareFeature;
@ -104,7 +106,7 @@ public String createHardwareToken(String username, UserHardware hardware) {
return Jwts.builder()
.setIssuer("LaunchServer")
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + 1000 * server.config.netty.security.hardwareTokenExpire))
.setExpiration(new Date(System.currentTimeMillis() + SECONDS.toMillis(server.config.netty.security.hardwareTokenExpire)))
.claim("hardware", hardware.getId())
.signWith(server.keyAgreementManager.ecdsaPrivateKey)
.compact();
@ -114,7 +116,7 @@ public String createPublicKeyToken(String username, byte[] publicKey) {
return Jwts.builder()
.setIssuer("LaunchServer")
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + 1000 * server.config.netty.security.publicKeyTokenExpire))
.setExpiration(new Date(System.currentTimeMillis() + SECONDS.toMillis(server.config.netty.security.publicKeyTokenExpire)))
.claim("publicKey", Base64.getEncoder().encodeToString(publicKey))
.signWith(server.keyAgreementManager.ecdsaPrivateKey)
.compact();

View file

@ -44,11 +44,11 @@ public boolean canGetUpdates(String updatesDirName, Client client) {
private boolean isWhitelisted(String property, ClientProfile profile, Client client) {
if (client.permissions != null) {
String permByUUID = String.format(property, profile.getUUID());
String permByUUID = property.formatted(profile.getUUID());
if (client.permissions.hasPerm(permByUUID)) {
return true;
}
String permByTitle = String.format(property, profile.getTitle().toLowerCase(Locale.ROOT));
String permByTitle = property.formatted(profile.getTitle().toLowerCase(Locale.ROOT));
if (client.permissions.hasPerm(permByTitle)) {
return true;
}

View file

@ -98,7 +98,7 @@ public void build(Path target, boolean deleteTempFiles) throws IOException {
}
public String nextName(String taskName) {
return String.format(nameFormat, taskName, count.getAndIncrement());
return nameFormat.formatted(taskName, count.getAndIncrement());
}
public Path nextPath(String taskName) {

View file

@ -27,7 +27,7 @@ public Launch4JTask(LaunchServer launchServer) {
}
public static String formatVars(String mask) {
return String.format(mask, VERSION, BUILD);
return mask.formatted(VERSION, BUILD);
}
@Override

View file

@ -59,7 +59,7 @@ protected Downloader downloadWithProgressBar(String taskName, List<AsyncDownload
.setStyle(ProgressBarStyle.COLORFUL_UNICODE_BLOCK)
.setUnit("MB", 1024 * 1024)
.build();
bar.setExtraMessage(String.format(" [0/%d]", totalFiles));
bar.setExtraMessage(" [0/%d]".formatted(totalFiles));
Downloader downloader = Downloader.downloadList(list, baseUrl, targetDir, new Downloader.DownloadCallback() {
@Override
public void apply(long fullDiff) {
@ -69,7 +69,7 @@ public void apply(long fullDiff) {
@Override
public void onComplete(Path path) {
bar.setExtraMessage(String.format(" [%d/%d]", currentFiles.incrementAndGet(), totalFiles));
bar.setExtraMessage(" [%d/%d]".formatted(currentFiles.incrementAndGet(), totalFiles));
}
}, null, 4);
downloader.getFuture().handle((v, e) -> {

View file

@ -86,7 +86,7 @@ public void invoke(String... args) throws IOException, CommandException {
if (version.compareTo(ClientProfileVersions.MINECRAFT_1_7_10) <= 0) {
logger.warn("Minecraft 1.7.9 and below not supported. Use at your own risk");
}
MakeProfileHelper.MakeProfileOption[] options = MakeProfileHelper.getMakeProfileOptionsFromDir(clientDir, version, Files.exists(server.updatesDir.resolve("assets")));
MakeProfileHelper.MakeProfileOption[] options = MakeProfileHelper.getMakeProfileOptionsFromDir(clientDir, version);
for (MakeProfileHelper.MakeProfileOption option : options) {
logger.debug("Detected option {}", option.getClass().getSimpleName());
}

View file

@ -33,7 +33,7 @@ public String getUsageDescription() {
public void invoke(String... args) throws Exception {
verifyArgs(args, 3);
ClientProfile.Version version = parseClientVersion(args[1]);
MakeProfileHelper.MakeProfileOption[] options = MakeProfileHelper.getMakeProfileOptionsFromDir(server.updatesDir.resolve(args[2]), version, Files.exists(server.updatesDir.resolve("assets")));
MakeProfileHelper.MakeProfileOption[] options = MakeProfileHelper.getMakeProfileOptionsFromDir(server.updatesDir.resolve(args[2]), version);
for (MakeProfileHelper.MakeProfileOption option : options) {
logger.info("Detected option {}", option);
}

View file

@ -38,11 +38,11 @@ public SecurityCheckCommand(LaunchServer server) {
public static void printCheckResult(String module, String comment, Boolean status) {
if (status == null) {
logger.warn(String.format("[%s] %s", module, comment));
logger.warn("[%s] %s".formatted(module, comment));
} else if (status) {
logger.info(String.format("[%s] %s OK", module, comment));
logger.info("[%s] %s OK".formatted(module, comment));
} else {
logger.error(String.format("[%s] %s", module, comment));
logger.error("[%s] %s".formatted(module, comment));
}
}
@ -153,11 +153,11 @@ public void invoke(String... args) {
//Profiles
for (ClientProfile profile : server.getProfiles()) {
boolean bad = false;
String profileModuleName = String.format("profiles.%s", profile.getTitle());
String profileModuleName = "profiles.%s".formatted(profile.getTitle());
for (String exc : profile.getUpdateExclusions()) {
StringTokenizer tokenizer = new StringTokenizer(exc, "/");
if (exc.endsWith(".jar")) {
printCheckResult(profileModuleName, String.format("updateExclusions %s not safe. Cheats may be injected very easy!", exc), false);
printCheckResult(profileModuleName, "updateExclusions %s not safe. Cheats may be injected very easy!".formatted(exc), false);
bad = true;
continue;
}
@ -165,12 +165,12 @@ public void invoke(String... args) {
String nextToken = tokenizer.nextToken();
if (!tokenizer.hasMoreTokens()) {
if (!exc.endsWith("/")) {
printCheckResult(profileModuleName, String.format("updateExclusions %s not safe. Cheats may be injected very easy!", exc), false);
printCheckResult(profileModuleName, "updateExclusions %s not safe. Cheats may be injected very easy!".formatted(exc), false);
bad = true;
}
} else {
if (nextToken.equals("memory_repo") || nextToken.equals(profile.getVersion().toString())) {
printCheckResult(profileModuleName, String.format("updateExclusions %s not safe. Cheats may be injected very easy!", exc), false);
printCheckResult(profileModuleName, "updateExclusions %s not safe. Cheats may be injected very easy!".formatted(exc), false);
bad = true;
}
}

View file

@ -34,7 +34,7 @@ public void invoke(String... args) throws Exception {
verifyArgs(args, 1);
Path targetDir = Paths.get(args[0]);
if (!IOHelper.isDir(targetDir))
throw new IllegalArgumentException(String.format("%s not directory", targetDir));
throw new IllegalArgumentException("%s not directory".formatted(targetDir));
Optional<SignJarTask> task = server.launcherBinary.getTaskByClass(SignJarTask.class);
if (task.isEmpty()) throw new IllegalStateException("SignJarTask not found");
IOHelper.walk(targetDir, new SignJarVisitor(task.get()), true);

View file

@ -16,7 +16,7 @@ public abstract class AbstractLimiter<T> extends Component implements Reconfigur
protected final transient Map<T, LimitEntry> map = new HashMap<>();
private transient final Logger logger = LogManager.getLogger();
public int rateLimit;
public int rateLimitMillis;
public long rateLimitMillis;
@Override
public Map<String, Command> getCommands() {

View file

@ -133,7 +133,7 @@ public Path process(Path inputFile) throws IOException {
if (component.enabled) {
Configuration proguard_cfg = new Configuration();
if (!checkJMods(IOHelper.JVM_DIR.resolve("jmods"))) {
throw new RuntimeException(String.format("Java path: %s is not JDK! Please install JDK", IOHelper.JVM_DIR));
throw new RuntimeException("Java path: %s is not JDK! Please install JDK".formatted(IOHelper.JVM_DIR));
}
Path jfxPath = tryFindOpenJFXPath(IOHelper.JVM_DIR);
if (checkFXJMods(IOHelper.JVM_DIR.resolve("jmods"))) {
@ -212,7 +212,7 @@ public String[] buildConfig(Path inputJar, Path outputJar, Path[] jfxPath) {
Collections.addAll(confStrs, JAVA9_OPTS);
if (jfxPath != null) {
for (Path path : jfxPath) {
confStrs.add(String.format("-libraryjars '%s'", path.toAbsolutePath()));
confStrs.add("-libraryjars '%s'".formatted(path.toAbsolutePath()));
}
}
srv.launcherBinary.coreLibs.stream()

View file

@ -23,6 +23,9 @@
import java.io.File;
import java.util.*;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.SECONDS;
public final class LaunchServerConfig {
private final static List<String> oldMirrorList = List.of("https://mirror.gravit.pro/5.2.x/", "https://mirror.gravit.pro/5.3.x/", "https://mirror.gravitlauncher.com/5.2.x/", "https://mirror.gravitlauncher.com/5.3.x/");
private transient final Logger logger = LogManager.getLogger();
@ -94,12 +97,12 @@ public static LaunchServerConfig getDefault(LaunchServer.LaunchServerEnv env) {
newConfig.components = new HashMap<>();
AuthLimiterComponent authLimiterComponent = new AuthLimiterComponent();
authLimiterComponent.rateLimit = 3;
authLimiterComponent.rateLimitMillis = 8000;
authLimiterComponent.rateLimitMillis = SECONDS.toMillis(8);
authLimiterComponent.message = "Превышен лимит авторизаций";
newConfig.components.put("authLimiter", authLimiterComponent);
RegLimiterComponent regLimiterComponent = new RegLimiterComponent();
regLimiterComponent.rateLimit = 3;
regLimiterComponent.rateLimitMillis = 1000 * 60 * 60 * 10; //Блок на 10 часов
regLimiterComponent.rateLimitMillis = HOURS.toMillis(10);
regLimiterComponent.message = "Превышен лимит регистраций";
newConfig.components.put("regLimiter", regLimiterComponent);
ProGuardComponent proGuardComponent = new ProGuardComponent();
@ -310,9 +313,9 @@ public NettyBindAddress(String address, int port) {
}
public static class NettySecurityConfig {
public long hardwareTokenExpire = 60 * 60 * 8;
public long publicKeyTokenExpire = 60 * 60 * 8;
public long hardwareTokenExpire = HOURS.toSeconds(8);
public long publicKeyTokenExpire = HOURS.toSeconds(8);
public long launcherTokenExpire = 60 * 60 * 8;
public long launcherTokenExpire = HOURS.toSeconds(8);
}
}

View file

@ -108,7 +108,7 @@ public T getOrThrow() throws RequestException {
if (isSuccessful()) {
return result;
} else {
throw new RequestException(error == null ? String.format("statusCode %d", statusCode) : error.toString());
throw new RequestException(error == null ? "statusCode %d".formatted(statusCode) : error.toString());
}
}
}

View file

@ -41,7 +41,7 @@ public static String makeRefreshTokenFromPassword(String username, String rawPas
rawPassword = "";
}
return SecurityHelper.toHex(SecurityHelper.digest(SecurityHelper.DigestAlgorithm.SHA256,
String.format("%s.%s.%s.%s", secretSalt, username, rawPassword, secretSalt)));
"%s.%s.%s.%s".formatted(secretSalt, username, rawPassword, secretSalt)));
}
public record JwtTokenInfo(String username, UUID uuid) {

View file

@ -19,11 +19,7 @@ public static ClientProfile makeProfile(ClientProfile.Version version, String ti
ClientProfileBuilder builder = new ClientProfileBuilder();
builder.setVersion(version);
builder.setDir(title);
if (findOption(options, MakeProfileOptionGlobalAssets.class).isPresent()) {
builder.setAssetDir("assets");
} else {
builder.setAssetDir("asset" + version.toCleanString());
}
builder.setAssetDir("assets");
builder.setAssetIndex(version.toString());
builder.setInfo("Server description");
builder.setTitle(title);
@ -209,7 +205,7 @@ private static String getLog4jVersion(Path dir) throws IOException {
return null;
}
public static MakeProfileOption[] getMakeProfileOptionsFromDir(Path dir, ClientProfile.Version version, boolean globalAssets) throws IOException {
public static MakeProfileOption[] getMakeProfileOptionsFromDir(Path dir, ClientProfile.Version version) throws IOException {
List<MakeProfileOption> options = new ArrayList<>(2);
if (Files.exists(dir.resolve("forge.jar"))) {
options.add(new MakeProfileOptionForge());
@ -247,9 +243,6 @@ public static MakeProfileOption[] getMakeProfileOptionsFromDir(Path dir, ClientP
if (Files.exists(dir.resolve("libraries/forge/launchwrapper-1.12-launcherfixed.jar.jar")) || Files.exists(dir.resolve("libraries/net/minecraft/launchwrapper"))) {
options.add(new MakeProfileOptionLaunchWrapper());
}
if (globalAssets) {
options.add(new MakeProfileOptionGlobalAssets());
}
return options.toArray(new MakeProfileOption[0]);
}
@ -325,10 +318,6 @@ public static class MakeProfileOptionLaunchWrapper implements MakeProfileOption
}
public static class MakeProfileOptionGlobalAssets implements MakeProfileOption {
}
public static class MakeProfileOptionFabric implements MakeProfileOption {
public String jimfsPath;
public String guavaPath;

View file

@ -313,7 +313,7 @@ public boolean accept(Client client, AuthProviderPair pair, String extendedToken
client.auth = server.config.getAuthProviderPair(info.authId);
if (client.permissions == null) client.permissions = new ClientPermissions();
client.permissions.addPerm("launchserver.checkserver");
client.permissions.addPerm(String.format("launchserver.profile.%s.show", info.serverName));
client.permissions.addPerm("launchserver.profile.%s.show".formatted(info.serverName));
client.setProperty("launchserver.serverName", info.serverName);
return true;
}

View file

@ -75,7 +75,7 @@ public void downloadZip(Path path, String mask, Object... args) throws IOExcepti
if (downloadZip(mirror, path, mask, args)) return;
}
}
throw new IOException(String.format("Error download %s. All mirrors return error", path.toString()));
throw new IOException("Error download %s. All mirrors return error".formatted(path.toString()));
}
public JsonElement jsonRequest(Mirror mirror, JsonElement request, String method, String mask, Object... args) throws IOException {
@ -111,7 +111,7 @@ public static class Mirror {
private URL formatArgs(String mask, Object... args) throws MalformedURLException {
Object[] data = Arrays.stream(args).map(e -> IOHelper.urlEncode(e.toString())).toArray();
return new URL(baseUrl.concat(String.format(mask, data)));
return new URL(baseUrl.concat(mask.formatted(data)));
}
public URL getURL(String mask, Object... args) throws MalformedURLException {

View file

@ -14,7 +14,7 @@ public class ReconfigurableManager {
public void registerReconfigurable(String name, Reconfigurable reconfigurable) {
VerifyHelper.putIfAbsent(RECONFIGURABLE, name.toLowerCase(), new ReconfigurableVirtualCommand(reconfigurable.getCommands()),
String.format("Reconfigurable has been already registered: '%s'", name));
"Reconfigurable has been already registered: '%s'".formatted(name));
}
public void unregisterReconfigurable(String name) {
@ -23,15 +23,15 @@ public void unregisterReconfigurable(String name) {
public void call(String name, String action, String[] args) throws Exception {
Command commands = RECONFIGURABLE.get(name);
if (commands == null) throw new CommandException(String.format("Reconfigurable %s not found", name));
if (commands == null) throw new CommandException("Reconfigurable %s not found".formatted(name));
Command command = commands.childCommands.get(action);
if (command == null) throw new CommandException(String.format("Action %s.%s not found", name, action));
if (command == null) throw new CommandException("Action %s.%s not found".formatted(name, action));
command.invoke(args);
}
public void printHelp(String name) throws CommandException {
Command commands = RECONFIGURABLE.get(name);
if (commands == null) throw new CommandException(String.format("Reconfigurable %s not found", name));
if (commands == null) throw new CommandException("Reconfigurable %s not found".formatted(name));
HelpCommand.printSubCommandsHelp(name, commands);
}

View file

@ -29,7 +29,7 @@ public void execute(ChannelHandlerContext ctx, Client client) {
}
HashedDir dir = server.updatesManager.getUpdate(dirName);
if (dir == null) {
sendError(String.format("Directory %s not found", dirName));
sendError("Directory %s not found".formatted(dirName));
return;
}
String url = server.config.netty.downloadURL.replace("%dirname%", IOHelper.urlEncode(dirName));

View file

@ -1,4 +1,4 @@
{
"features": ["sha1-hash"],
"features": [],
"info": []
}

View file

@ -77,25 +77,7 @@ protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundE
@Override
public String findLibrary(String name) {
return nativePath.concat(IOHelper.PLATFORM_SEPARATOR).concat(getNativePrefix()).concat(name).concat(getNativeEx());
}
public String getNativeEx() {
if (JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE)
return ".dll";
else if (JVMHelper.OS_TYPE == JVMHelper.OS.LINUX)
return ".so";
else if (JVMHelper.OS_TYPE == JVMHelper.OS.MACOSX)
return ".dylib";
return "";
}
public String getNativePrefix() {
if (JVMHelper.OS_TYPE == JVMHelper.OS.LINUX)
return "lib";
else if (JVMHelper.OS_TYPE == JVMHelper.OS.MACOSX)
return "lib";
return "";
return nativePath.concat(IOHelper.PLATFORM_SEPARATOR).concat(JVMHelper.NATIVE_PREFIX).concat(name).concat(JVMHelper.NATIVE_EXTENSION);
}
public void addAllowedPackage(String pkg) {

View file

@ -6,9 +6,9 @@ public final class Version implements Comparable<Version> {
public static final int MAJOR = 5;
public static final int MINOR = 4;
public static final int PATCH = 2;
public static final int PATCH = 3;
public static final int BUILD = 1;
public static final Version.Type RELEASE = Type.EXPERIMENTAL;
public static final Version.Type RELEASE = Type.STABLE;
public final int major;
public final int minor;
public final int patch;

View file

@ -24,6 +24,8 @@ public final class JVMHelper {
// System properties
public static final String OS_VERSION = OPERATING_SYSTEM_MXBEAN.getVersion();
public static final ARCH ARCH_TYPE = getArch(System.getProperty("os.arch"));
public static final String NATIVE_EXTENSION = getNativeExtension(OS_TYPE);
public static final String NATIVE_PREFIX = getNativePrefix(OS_TYPE);
public static final int JVM_BITS = Integer.parseInt(System.getProperty("sun.arch.data.model"));
// Public static fields
public static final Runtime RUNTIME = Runtime.getRuntime();
@ -82,6 +84,29 @@ public static int getBuild() {
}
public static String getNativeExtension(JVMHelper.OS OS_TYPE) {
switch (OS_TYPE) {
case MUSTDIE:
return ".dll";
case LINUX:
return ".so";
case MACOSX:
return ".dylib";
default:
throw new InternalError(String.format("Unsupported OS TYPE '%s'", OS_TYPE));
}
}
public static String getNativePrefix(JVMHelper.OS OS_TYPE) {
switch (OS_TYPE) {
case LINUX:
case MACOSX:
return "lib";
default:
return "";
}
}
public static void appendVars(ProcessBuilder builder, Map<String, String> vars) {
builder.environment().putAll(vars);
}
@ -179,7 +204,6 @@ public static void verifySystemProperties(Class<?> mainClass, boolean requireSys
LogHelper.debug("Verifying JVM architecture");
}
public enum ARCH {
X86("x86"), X86_64("x86-64"), ARM64("arm64"), ARM32("arm32");

View file

@ -20,13 +20,12 @@ public final class JVMHelper {
public static final OperatingSystemMXBean OPERATING_SYSTEM_MXBEAN =
ManagementFactory.getOperatingSystemMXBean();
public static final OS OS_TYPE = OS.byName(OPERATING_SYSTEM_MXBEAN.getName());
public static final int OS_BITS = getCorrectOSArch();
// System properties
public static final String OS_VERSION = OPERATING_SYSTEM_MXBEAN.getVersion();
public static final int OS_BITS = getCorrectOSArch();
public static final ARCH ARCH_TYPE = getArch(System.getProperty("os.arch"));
public static final String NATIVE_EXTENSION = getNativeExtension(OS_TYPE);
public static final String NATIVE_PREFIX = getNativePrefix(OS_TYPE);
public static final int JVM_BITS = Integer.parseInt(System.getProperty("sun.arch.data.model"));
// Public static fields
public static final Runtime RUNTIME = Runtime.getRuntime();
@ -45,21 +44,11 @@ public final class JVMHelper {
private JVMHelper() {
}
public enum ARCH {
X86("x86"), X86_64("x86-64"), ARM64("arm64"), ARM32("arm32");
public final String name;
ARCH(String name) {
this.name = name;
}
}
public static ARCH getArch(String arch) {
if(arch.equals("amd64") || arch.equals("x86-64") || arch.equals("x86_64")) return ARCH.X86_64;
if(arch.equals("i386") || arch.equals("i686") || arch.equals("x86")) return ARCH.X86;
if(arch.startsWith("armv8") || arch.startsWith("aarch64")) return ARCH.ARM64;
if(arch.startsWith("arm") || arch.startsWith("aarch32")) return ARCH.ARM32;
if (arch.equals("amd64") || arch.equals("x86-64") || arch.equals("x86_64")) return ARCH.X86_64;
if (arch.equals("i386") || arch.equals("i686") || arch.equals("x86")) return ARCH.X86;
if (arch.startsWith("armv8") || arch.startsWith("aarch64")) return ARCH.ARM64;
if (arch.startsWith("arm") || arch.startsWith("aarch32")) return ARCH.ARM32;
throw new InternalError(String.format("Unsupported arch '%s'", arch));
}
@ -72,6 +61,29 @@ public static int getBuild() {
return Runtime.version().update();
}
public static String getNativeExtension(JVMHelper.OS OS_TYPE) {
switch (OS_TYPE) {
case MUSTDIE:
return ".dll";
case LINUX:
return ".so";
case MACOSX:
return ".dylib";
default:
throw new InternalError(String.format("Unsupported OS TYPE '%s'", OS_TYPE));
}
}
public static String getNativePrefix(JVMHelper.OS OS_TYPE) {
switch (OS_TYPE) {
case LINUX:
case MACOSX:
return "lib";
default:
return "";
}
}
public static void appendVars(ProcessBuilder builder, Map<String, String> vars) {
builder.environment().putAll(vars);
}
@ -86,19 +98,16 @@ public static Class<?> firstClass(String... names) throws ClassNotFoundException
throw new ClassNotFoundException(Arrays.toString(names));
}
public static void fullGC() {
RUNTIME.gc();
RUNTIME.runFinalization();
LogHelper.debug("Used heap: %d MiB", RUNTIME.totalMemory() - RUNTIME.freeMemory() >> 20);
}
public static String[] getClassPath() {
return System.getProperty("java.class.path").split(File.pathSeparator);
}
public static URL[] getClassPathURL() {
String[] cp = System.getProperty("java.class.path").split(File.pathSeparator);
URL[] list = new URL[cp.length];
@ -139,34 +148,28 @@ private static int getCorrectOSArch() {
return System.getProperty("os.arch").contains("64") ? 64 : 32;
}
public static String getEnvPropertyCaseSensitive(String name) {
return System.getenv().get(name);
}
public static boolean isJVMMatchesSystemArch() {
return JVM_BITS == OS_BITS;
}
public static String jvmProperty(String name, String value) {
return String.format("-D%s=%s", name, value);
}
public static String systemToJvmProperty(String name) {
return String.format("-D%s=%s", name, System.getProperties().getProperty(name));
}
public static void addSystemPropertyToArgs(Collection<String> args, String name) {
String property = System.getProperty(name);
if (property != null)
args.add(String.format("-D%s=%s", name, property));
}
public static void verifySystemProperties(Class<?> mainClass, boolean requireSystem) {
Locale.setDefault(Locale.US);
// Verify class loader
@ -178,6 +181,16 @@ public static void verifySystemProperties(Class<?> mainClass, boolean requireSys
LogHelper.debug("Verifying JVM architecture");
}
public enum ARCH {
X86("x86"), X86_64("x86-64"), ARM64("arm64"), ARM32("arm32");
public final String name;
ARCH(String name) {
this.name = name;
}
}
public enum OS {
MUSTDIE("mustdie"), LINUX("linux"), MACOSX("macosx");

View file

@ -5,7 +5,7 @@
id 'org.openjfx.javafxplugin' version '0.0.10' apply false
}
group = 'pro.gravit.launcher'
version = '5.4.3-SNAPSHOT'
version = '5.4.3'
apply from: 'props.gradle'

Binary file not shown.

View file

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

12
gradlew vendored
View file

@ -85,9 +85,6 @@ done
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@ -133,10 +130,13 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
@ -197,6 +197,10 @@ if "$cygwin" || "$msys" ; then
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in

@ -1 +1 @@
Subproject commit bbf0ef5c67b161a570946d8c6e8c0b3655efd4bb
Subproject commit d20723ae0e41c7580560a4f9f402699dbce2ae4c

View file

@ -1,11 +1,11 @@
project.ext {
verAsm = '9.4'
verNetty = '4.1.87.Final'
verOshiCore = '6.4.0'
verJunit = '5.9.2'
verAsm = '9.5'
verNetty = '4.1.94.Final'
verOshiCore = '6.4.4'
verJunit = '5.9.3'
verGuavaC = '30.1.1-jre'
verJansi = '2.4.0'
verJline = '3.22.0'
verJline = '3.23.0'
verJwt = '0.11.5'
verBcprov = '1.70'
verGson = '2.10.1'
@ -13,8 +13,8 @@
verSlf4j = '1.7.36'
verLog4j = '2.19.0'
verMySQLConn = '8.0.33'
verPostgreSQLConn = '42.5.1'
verProguard = '7.3.1'
verPostgreSQLConn = '42.6.0'
verProguard = '7.3.2'
verLaunch4j = '3.50'
verHibernate = '5.5.6.Final'
}