From 9766cd69e5422faaf06f7a314938b841af6e9cdc Mon Sep 17 00:00:00 2001 From: Gravit Date: Fri, 25 Sep 2020 22:48:33 +0700 Subject: [PATCH] [ANY] IDEA Reformat --- .../pro/gravit/launchserver/LaunchServer.java | 2 +- .../launchserver/asm/InjectClassAcceptor.java | 5 +- .../auth/handler/JsonAuthHandler.java | 1 + .../auth/protect/AdvancedProtectHandler.java | 27 ++---- .../auth/protect/ProtectHandler.java | 6 +- .../auth/protect/hwid/HWIDProvider.java | 96 +++++++++---------- .../auth/protect/hwid/JsonHWIDProvider.java | 15 ++- .../auth/protect/hwid/MemoryHWIDProvider.java | 30 +++--- .../auth/protect/hwid/MysqlHWIDProvider.java | 39 ++++---- .../interfaces/JoinServerProtectHandler.java | 3 +- .../interfaces/SecureProtectHandler.java | 4 +- .../binary/tasks/ProGuardBuildTask.java | 19 ++-- .../command/basic/TestCommand.java | 15 +-- .../command/hash/DownloadClientCommand.java | 8 +- .../command/hash/SaveProfilesCommand.java | 16 ++-- .../command/hash/SyncUPCommand.java | 2 +- .../launchermodules/LauncherModuleLoader.java | 11 +-- .../manangers/PingServerManager.java | 28 +++--- .../gravit/launchserver/socket/Client.java | 11 +-- .../socket/LauncherNettyServer.java | 2 +- .../launchserver/socket/WebSocketService.java | 19 ++-- .../socket/handlers/NettyWebAPIHandler.java | 30 +++--- .../handlers/WebSocketFrameHandler.java | 4 +- .../socket/response/auth/AuthResponse.java | 7 +- .../response/auth/CurrentUserResponse.java | 8 +- .../socket/response/auth/ExitResponse.java | 7 +- .../response/auth/JoinServerResponse.java | 6 +- .../response/auth/RestoreSessionResponse.java | 7 +- .../management/PingServerReportResponse.java | 4 +- .../management/PingServerResponse.java | 17 ++-- .../management/ServerStatusResponse.java | 10 +- .../response/profile/ProfileByUsername.java | 7 +- .../secure/HardwareReportResponse.java | 10 +- .../secure/VerifySecureLevelKeyResponse.java | 3 +- .../launcher/ClientLauncherWrapper.java | 67 ++++++------- .../client/ClientLauncherEntryPoint.java | 16 ++-- .../client/ClientLauncherProcess.java | 20 ++-- .../gravit/launcher/client/ServerPinger.java | 7 +- .../request/CurrentUserRequestEvent.java | 1 + .../launcher/profiles/ClientProfile.java | 24 +++-- .../profiles/optional/OptionalView.java | 59 +++++------- .../optional/actions/OptionalAction.java | 7 +- .../optional/actions/OptionalActionFile.java | 16 ++-- .../auth/password/Auth2FAPassword.java | 1 + .../auth/password/AuthSignaturePassword.java | 1 + .../auth/password/AuthTOTPPassword.java | 1 + .../management/PingServerReportRequest.java | 9 +- .../pro/gravit/launcher/hasher/HashedDir.java | 20 ++-- .../gravit/utils/UniversalJsonAdapter.java | 3 +- modules | 2 +- 50 files changed, 322 insertions(+), 411 deletions(-) diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServer.java b/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServer.java index 8ad75c78..eaa40fb1 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServer.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/LaunchServer.java @@ -388,7 +388,7 @@ public void syncProfilesDir() throws IOException { // Sort and set new profiles newProfies.sort(Comparator.comparing(a -> a)); profilesList = Collections.unmodifiableList(newProfies); - if(pingServerManager != null) + if (pingServerManager != null) pingServerManager.syncServers(); } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/asm/InjectClassAcceptor.java b/LaunchServer/src/main/java/pro/gravit/launchserver/asm/InjectClassAcceptor.java index 46914d91..3e7a5db0 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/asm/InjectClassAcceptor.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/asm/InjectClassAcceptor.java @@ -171,9 +171,8 @@ private static InsnList serializeValue(Object value) { value.getClass())); } - public static boolean isSerializableValue(Object value) - { - if(value == null) return true; + public static boolean isSerializableValue(Object value) { + if (value == null) return true; if (primitiveLDCClasses.contains(value.getClass())) return true; for (Map.Entry, Serializer> serializerEntry : serializers.entrySet()) { if (serializerEntry.getKey().isInstance(value)) { diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/JsonAuthHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/JsonAuthHandler.java index d113a47d..e9da08a7 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/JsonAuthHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/handler/JsonAuthHandler.java @@ -51,6 +51,7 @@ public EntryRequestByUsername(String username, String apiKey) { public static class EntryRequestByUUID { public final UUID uuid; public final String apiKey; + public EntryRequestByUUID(UUID uuid, String apiKey) { this.uuid = uuid; this.apiKey = apiKey; diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java index 201f9003..de6ec57c 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/AdvancedProtectHandler.java @@ -46,14 +46,12 @@ public boolean allowGetSecureLevelInfo(Client client) { @Override public void onHardwareReport(HardwareReportResponse response, Client client) { - if(!enableHardwareFeature) - { + if (!enableHardwareFeature) { response.sendResult(new HardwareReportRequestEvent()); return; } try { - if(!client.isAuth || client.trustLevel == null || client.trustLevel.publicKey == null) - { + if (!client.isAuth || client.trustLevel == null || client.trustLevel.publicKey == null) { response.sendError("Access denied"); return; } @@ -61,7 +59,7 @@ public void onHardwareReport(HardwareReportResponse response, Client client) { LogHelper.debug("[HardwareInfo] HardwareInfo received"); boolean needCreate = !provider.addPublicKeyToHardwareInfo(response.hardware, client.trustLevel.publicKey, client); LogHelper.debug("[HardwareInfo] HardwareInfo needCreate: %s", needCreate ? "true" : "false"); - if(needCreate) + if (needCreate) provider.createHardwareInfo(response.hardware, client.trustLevel.publicKey, client); client.trustLevel.hardwareInfo = response.hardware; } catch (HWIDException e) { @@ -72,17 +70,13 @@ public void onHardwareReport(HardwareReportResponse response, Client client) { @Override public VerifySecureLevelKeyRequestEvent onSuccessVerify(Client client) { - if(enableHardwareFeature) - { - if(provider == null) - { + if (enableHardwareFeature) { + if (provider == null) { LogHelper.warning("HWIDProvider null. HardwareInfo not checked!"); - } - else - { + } else { try { client.trustLevel.hardwareInfo = provider.findHardwareInfoByPublicKey(client.trustLevel.publicKey, client); - if(client.trustLevel.hardwareInfo == null) //HWID not found? + if (client.trustLevel.hardwareInfo == null) //HWID not found? return new VerifySecureLevelKeyRequestEvent(true); } catch (HWIDException e) { throw new SecurityException(e.getMessage()); //Show banned message @@ -96,8 +90,7 @@ public VerifySecureLevelKeyRequestEvent onSuccessVerify(Client client) { @Override public Map getCommands() { Map commands = new HashMap<>(); - if(provider instanceof Reconfigurable) - { + if (provider instanceof Reconfigurable) { commands.putAll(((Reconfigurable) provider).getCommands()); } return commands; @@ -110,13 +103,13 @@ public boolean onJoinServer(String serverID, String username, Client client) { @Override public void init(LaunchServer server) { - if(provider != null) + if (provider != null) provider.init(server); } @Override public void close() { - if(provider != null) + if (provider != null) provider.close(); } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/ProtectHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/ProtectHandler.java index 98e4ffe1..bead3fd2 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/ProtectHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/ProtectHandler.java @@ -22,13 +22,11 @@ public static void registerHandlers() { public abstract void checkLaunchServerLicense(); //Выдает SecurityException при ошибке проверки лицензии - public void init(LaunchServer server) - { + public void init(LaunchServer server) { } - public void close() - { + public void close() { } //public abstract diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/HWIDProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/HWIDProvider.java index 138b1546..a702b29d 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/HWIDProvider.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/HWIDProvider.java @@ -13,108 +13,102 @@ public abstract class HWIDProvider { public static final ProviderMap providers = new ProviderMap<>("HWIDProvider"); private static boolean registredProv = false; + public static void registerProviders() { - if(!registredProv) - { + if (!registredProv) { providers.register("memory", MemoryHWIDProvider.class); providers.register("mysql", MysqlHWIDProvider.class); providers.register("json", JsonHWIDProvider.class); registredProv = true; } } + public abstract HardwareReportRequest.HardwareInfo findHardwareInfoByPublicKey(byte[] publicKey, Client client) throws HWIDException; + public abstract void createHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException; + public abstract boolean addPublicKeyToHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException; - public void normalizeHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo) - { - if(hardwareInfo.baseboardSerialNumber != null) hardwareInfo.baseboardSerialNumber = hardwareInfo.baseboardSerialNumber.trim(); - if(hardwareInfo.hwDiskId != null) hardwareInfo.hwDiskId = hardwareInfo.hwDiskId.trim(); + public void normalizeHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo) { + if (hardwareInfo.baseboardSerialNumber != null) + hardwareInfo.baseboardSerialNumber = hardwareInfo.baseboardSerialNumber.trim(); + if (hardwareInfo.hwDiskId != null) hardwareInfo.hwDiskId = hardwareInfo.hwDiskId.trim(); } - public static class HardwareInfoCompareResult - { + + public static class HardwareInfoCompareResult { public double firstSpoofingLevel = 0.0; public double secondSpoofingLevel = 0.0; public double compareLevel; } + //Required normalize HardwareInfo - public HardwareInfoCompareResult compareHardwareInfo(HardwareReportRequest.HardwareInfo first, HardwareReportRequest.HardwareInfo second) - { + public HardwareInfoCompareResult compareHardwareInfo(HardwareReportRequest.HardwareInfo first, HardwareReportRequest.HardwareInfo second) { HardwareInfoCompareResult result = new HardwareInfoCompareResult(); - if(first.hwDiskId == null || first.hwDiskId.isEmpty()) result.firstSpoofingLevel += 0.9; - if(first.displayId == null || first.displayId.length < 4) result.firstSpoofingLevel += 0.3; - if(first.baseboardSerialNumber == null || first.baseboardSerialNumber.trim().isEmpty()) result.firstSpoofingLevel += 0.2; - if(second.hwDiskId == null || second.hwDiskId.trim().isEmpty()) result.secondSpoofingLevel += 0.9; - if(second.displayId == null || second.displayId.length < 4) result.secondSpoofingLevel += 0.3; - if(second.baseboardSerialNumber == null || second.baseboardSerialNumber.trim().isEmpty()) result.secondSpoofingLevel += 0.2; - if(first.hwDiskId != null && second.hwDiskId != null) - { + if (first.hwDiskId == null || first.hwDiskId.isEmpty()) result.firstSpoofingLevel += 0.9; + if (first.displayId == null || first.displayId.length < 4) result.firstSpoofingLevel += 0.3; + if (first.baseboardSerialNumber == null || first.baseboardSerialNumber.trim().isEmpty()) + result.firstSpoofingLevel += 0.2; + if (second.hwDiskId == null || second.hwDiskId.trim().isEmpty()) result.secondSpoofingLevel += 0.9; + if (second.displayId == null || second.displayId.length < 4) result.secondSpoofingLevel += 0.3; + if (second.baseboardSerialNumber == null || second.baseboardSerialNumber.trim().isEmpty()) + result.secondSpoofingLevel += 0.2; + if (first.hwDiskId != null && second.hwDiskId != null) { int hwDIskIdRate = DamerauHelper.calculateDistance(first.hwDiskId.toLowerCase(), second.hwDiskId.toLowerCase()); - if(hwDIskIdRate == 0) // 100% compare + if (hwDIskIdRate == 0) // 100% compare { result.compareLevel += 0.99; - } - else if(hwDIskIdRate < 3) //Very small change + } else if (hwDIskIdRate < 3) //Very small change { result.compareLevel += 0.85; - } - else if(hwDIskIdRate < (first.hwDiskId.length()+second.hwDiskId.length()) / 4) - { - double addLevel = hwDIskIdRate / ( (double)(first.hwDiskId.length()+second.hwDiskId.length()) / 2.0 ); - if(addLevel > 0.0 && addLevel < 0.85) result.compareLevel += addLevel; + } else if (hwDIskIdRate < (first.hwDiskId.length() + second.hwDiskId.length()) / 4) { + double addLevel = hwDIskIdRate / ((double) (first.hwDiskId.length() + second.hwDiskId.length()) / 2.0); + if (addLevel > 0.0 && addLevel < 0.85) result.compareLevel += addLevel; } } - if(first.baseboardSerialNumber != null && second.baseboardSerialNumber != null) - { + if (first.baseboardSerialNumber != null && second.baseboardSerialNumber != null) { int baseboardSerialRate = DamerauHelper.calculateDistance(first.baseboardSerialNumber.toLowerCase(), second.baseboardSerialNumber.toLowerCase()); - if(baseboardSerialRate == 0) // 100% compare + if (baseboardSerialRate == 0) // 100% compare { result.compareLevel += 0.3; - } - else if(baseboardSerialRate < 3) //Very small change + } else if (baseboardSerialRate < 3) //Very small change { result.compareLevel += 0.15; } } - if(first.displayId != null && second.displayId != null) - { - if(Arrays.equals(first.displayId, second.displayId)) - { + if (first.displayId != null && second.displayId != null) { + if (Arrays.equals(first.displayId, second.displayId)) { result.compareLevel += 0.75; } } //Check statistic info - if(first.logicalProcessors == 0 || first.physicalProcessors == 0 || first.logicalProcessors < first.physicalProcessors) //WTF + if (first.logicalProcessors == 0 || first.physicalProcessors == 0 || first.logicalProcessors < first.physicalProcessors) //WTF result.firstSpoofingLevel += 0.9; - if(second.logicalProcessors == 0 || second.physicalProcessors == 0 || second.logicalProcessors < second.physicalProcessors) //WTF + if (second.logicalProcessors == 0 || second.physicalProcessors == 0 || second.logicalProcessors < second.physicalProcessors) //WTF result.secondSpoofingLevel += 0.9; - if(first.physicalProcessors == second.physicalProcessors && first.logicalProcessors == second.logicalProcessors) + if (first.physicalProcessors == second.physicalProcessors && first.logicalProcessors == second.logicalProcessors) result.compareLevel += 0.05; - if(first.battery != second.battery) + if (first.battery != second.battery) result.compareLevel -= 0.05; - if(first.processorMaxFreq == second.processorMaxFreq) + if (first.processorMaxFreq == second.processorMaxFreq) result.compareLevel += 0.1; - if(first.totalMemory == second.totalMemory) + if (first.totalMemory == second.totalMemory) result.compareLevel += 0.1; - if(Math.abs(first.totalMemory - second.totalMemory) < 32*1024) + if (Math.abs(first.totalMemory - second.totalMemory) < 32 * 1024) result.compareLevel += 0.05; return result; } - protected void printHardwareInfo(LogHelper.Level logLevel, HardwareReportRequest.HardwareInfo info) - { - LogHelper.log(logLevel, String.format("[HardwareInfo] Processor: logical %d | physical %d | freq %d | bitness %d", info.logicalProcessors, info.physicalProcessors, info.processorMaxFreq, info.bitness) , false); - LogHelper.log(logLevel, String.format("[HardwareInfo] Memory max: %d | battery %s", info.totalMemory, info.battery ? "true" : "false") , false); - LogHelper.log(logLevel, String.format("[HardwareInfo] HWDiskID %s | baseboardSerialNumber %s | displayId hash: %s", info.hwDiskId, info.baseboardSerialNumber, SecurityHelper.toHex(SecurityHelper.digest(SecurityHelper.DigestAlgorithm.MD5, info.displayId))) , false); + protected void printHardwareInfo(LogHelper.Level logLevel, HardwareReportRequest.HardwareInfo info) { + LogHelper.log(logLevel, String.format("[HardwareInfo] Processor: logical %d | physical %d | freq %d | bitness %d", info.logicalProcessors, info.physicalProcessors, info.processorMaxFreq, info.bitness), false); + LogHelper.log(logLevel, String.format("[HardwareInfo] Memory max: %d | battery %s", info.totalMemory, info.battery ? "true" : "false"), false); + LogHelper.log(logLevel, String.format("[HardwareInfo] HWDiskID %s | baseboardSerialNumber %s | displayId hash: %s", info.hwDiskId, info.baseboardSerialNumber, SecurityHelper.toHex(SecurityHelper.digest(SecurityHelper.DigestAlgorithm.MD5, info.displayId))), false); } - public void init(LaunchServer server) - { + public void init(LaunchServer server) { } - public void close() - { + public void close() { } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/JsonHWIDProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/JsonHWIDProvider.java index 54ff0231..863adef2 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/JsonHWIDProvider.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/JsonHWIDProvider.java @@ -12,15 +12,18 @@ public class JsonHWIDProvider extends HWIDProvider { public URL createHardwareInfoRequest; public URL addPublicKeyToHardwareInfoRequest; public String apiKey; + public static class RequestFind { public byte[] publicKey; public Client client; public String apiKey; } + public static class ResultFind { public String error; public HardwareReportRequest.HardwareInfo info; } + @Override public HardwareReportRequest.HardwareInfo findHardwareInfoByPublicKey(byte[] publicKey, Client client) throws HWIDException { try { @@ -33,19 +36,22 @@ public HardwareReportRequest.HardwareInfo findHardwareInfoByPublicKey(byte[] pub return r.info; } catch (HWIDException t) { throw t; - } catch (Throwable t) { + } catch (Throwable t) { throw new HWIDException(t); } } + public static class RequestCreate { public byte[] publicKey; public Client client; public HardwareReportRequest.HardwareInfo hardwareInfo; public String apiKey; } + public static class ResultCreate { public String error; } + @Override public void createHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException { try { @@ -58,20 +64,23 @@ public void createHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, if (r.error != null) throw new HWIDException(r.error); } catch (HWIDException t) { throw t; - } catch (Throwable t) { + } catch (Throwable t) { throw new HWIDException(t); } } + public static class RequestAddKey { public byte[] publicKey; public Client client; public HardwareReportRequest.HardwareInfo hardwareInfo; public String apiKey; } + public static class ResultAddKey { public String error; public boolean success; } + @Override public boolean addPublicKeyToHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException { try { @@ -85,7 +94,7 @@ public boolean addPublicKeyToHardwareInfo(HardwareReportRequest.HardwareInfo har return r.success; } catch (HWIDException t) { throw t; - } catch (Throwable t) { + } catch (Throwable t) { throw new HWIDException(t); } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MemoryHWIDProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MemoryHWIDProvider.java index 54e0aec7..a4d679c7 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MemoryHWIDProvider.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MemoryHWIDProvider.java @@ -24,8 +24,7 @@ public Map getCommands() { commands.put("hardwarelist", new SubCommand() { @Override public void invoke(String... args) throws Exception { - for(MemoryHWIDEntity e : db) - { + for (MemoryHWIDEntity e : db) { printHardwareInfo(LogHelper.Level.INFO, e.hardware); LogHelper.info("ID %d banned %s", e.id, e.banned ? "true" : "false"); LogHelper.info("PublicKey Hash: %s", SecurityHelper.toHex(SecurityHelper.digest(SecurityHelper.DigestAlgorithm.SHA1, e.publicKey))); @@ -37,10 +36,8 @@ public void invoke(String... args) throws Exception { public void invoke(String... args) throws Exception { verifyArgs(args, 1); long id = Long.parseLong(args[0]); - for(MemoryHWIDEntity e : db) - { - if(e.id == id) - { + for (MemoryHWIDEntity e : db) { + if (e.id == id) { e.banned = true; LogHelper.info("HardwareID %d banned", e.id); } @@ -50,8 +47,7 @@ public void invoke(String... args) throws Exception { return commands; } - static class MemoryHWIDEntity - { + static class MemoryHWIDEntity { public HardwareReportRequest.HardwareInfo hardware; public byte[] publicKey; public boolean banned; @@ -63,14 +59,14 @@ public MemoryHWIDEntity(HardwareReportRequest.HardwareInfo hardware, byte[] publ this.id = SecurityHelper.newRandom().nextLong(); } } + public Set db = ConcurrentHashMap.newKeySet(); @Override public HardwareReportRequest.HardwareInfo findHardwareInfoByPublicKey(byte[] publicKey, Client client) throws HWIDException { - for(MemoryHWIDEntity e : db) { - if(Arrays.equals(e.publicKey, publicKey)) - { - if(e.banned) throw new HWIDException("You HWID banned"); + for (MemoryHWIDEntity e : db) { + if (Arrays.equals(e.publicKey, publicKey)) { + if (e.banned) throw new HWIDException("You HWID banned"); return e.hardware; } } @@ -85,17 +81,15 @@ public void createHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, @Override public boolean addPublicKeyToHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException { boolean isAlreadyWarning = false; - for(MemoryHWIDEntity e : db) { + for (MemoryHWIDEntity e : db) { HardwareInfoCompareResult result = compareHardwareInfo(e.hardware, hardwareInfo); - if(warningSpoofingLevel > 0 && result.firstSpoofingLevel > warningSpoofingLevel && !isAlreadyWarning) - { + if (warningSpoofingLevel > 0 && result.firstSpoofingLevel > warningSpoofingLevel && !isAlreadyWarning) { LogHelper.warning("HardwareInfo spoofing level too high: %d", result.firstSpoofingLevel); isAlreadyWarning = true; } - if(result.compareLevel > criticalCompareLevel) - { + if (result.compareLevel > criticalCompareLevel) { LogHelper.debug("HardwareInfo publicKey change: compareLevel %d", result.compareLevel); - if(e.banned) throw new HWIDException("You HWID banned"); + if (e.banned) throw new HWIDException("You HWID banned"); e.publicKey = publicKey; return true; } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MysqlHWIDProvider.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MysqlHWIDProvider.java index 00dfa188..3dfa3e24 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MysqlHWIDProvider.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/hwid/MysqlHWIDProvider.java @@ -36,33 +36,28 @@ public void init(LaunchServer server) { sqlCreateHardware = String.format("INSERT INTO `%s` (`publickey`, `hwDiskId`, `baseboardSerialNumber`, `displayId`, `bitness`, `totalMemory`, `logicalProcessors`, `physicalProcessors`, `processorMaxFreq`, `battery`, `banned`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0')", tableHWID); sqlCreateHWIDLog = String.format("INSERT INTO %s (`hwidId`, `newPublicKey`) VALUES (?, ?)", tableHWIDLog); sqlUpdateHardware = String.format("UPDATE %s SET `publicKey` = ? WHERE `id` = ?", tableHWID); - if(tableUsers != null && usersHWIDColumn != null && usersNameColumn != null) { + if (tableUsers != null && usersHWIDColumn != null && usersNameColumn != null) { sqlUpdateUsers = String.format("UPDATE %s SET `%s` = ? WHERE `%s` = ?", tableUsers, usersHWIDColumn, usersNameColumn); - } - else { + } else { LogHelper.warning("[MysqlHWIDProvider] Link to users table not configured"); } } @Override public HardwareReportRequest.HardwareInfo findHardwareInfoByPublicKey(byte[] publicKey, Client client) throws HWIDException { - try(Connection connection = mySQLHolder.getConnection()) - { + try (Connection connection = mySQLHolder.getConnection()) { PreparedStatement s = connection.prepareStatement(sqlFindByPublicKey); s.setBlob(1, new ByteArrayInputStream(publicKey)); ResultSet set = s.executeQuery(); - if(set.next()) - { - if(set.getBoolean(11)) //isBanned + if (set.next()) { + if (set.getBoolean(11)) //isBanned { throw new SecurityException("You HWID banned"); } long id = set.getLong(10); setUserHardwareId(connection, client.username, id); return fetchHardwareInfo(set); - } - else - { + } else { return null; } } catch (SQLException | IOException throwables) { @@ -88,8 +83,7 @@ private HardwareReportRequest.HardwareInfo fetchHardwareInfo(ResultSet set) thro @Override public void createHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException { - try(Connection connection = mySQLHolder.getConnection()) - { + try (Connection connection = mySQLHolder.getConnection()) { PreparedStatement s = connection.prepareStatement(sqlCreateHardware, Statement.RETURN_GENERATED_KEYS); s.setBlob(1, new ByteArrayInputStream(publicKey)); s.setString(2, hardwareInfo.hwDiskId); @@ -116,18 +110,15 @@ public void createHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, @Override public boolean addPublicKeyToHardwareInfo(HardwareReportRequest.HardwareInfo hardwareInfo, byte[] publicKey, Client client) throws HWIDException { - try(Connection connection = mySQLHolder.getConnection()) - { + try (Connection connection = mySQLHolder.getConnection()) { PreparedStatement s = connection.prepareStatement(sqlFindByHardware); ResultSet set = s.executeQuery(); - while(set.next()) - { + while (set.next()) { HardwareReportRequest.HardwareInfo hw = fetchHardwareInfo(set); long id = set.getLong(10); HardwareInfoCompareResult result = compareHardwareInfo(hw, hardwareInfo); - if(result.compareLevel > criticalCompareLevel) - { - if(set.getBoolean(11)) //isBanned + if (result.compareLevel > criticalCompareLevel) { + if (set.getBoolean(11)) //isBanned { throw new SecurityException("You HWID banned"); } @@ -137,27 +128,29 @@ public boolean addPublicKeyToHardwareInfo(HardwareReportRequest.HardwareInfo har return true; } } - } catch (SQLException | IOException throwables) - { + } catch (SQLException | IOException throwables) { LogHelper.error(throwables); throw new SecurityException("SQL error. Please try again later"); } return false; } + private void changePublicKey(Connection connection, long id, byte[] publicKey) throws SQLException { PreparedStatement s = connection.prepareStatement(sqlUpdateHardware); s.setBlob(1, new ByteArrayInputStream(publicKey)); s.setLong(2, id); s.executeUpdate(); } + private void writeHwidLog(Connection connection, long hwidId, byte[] newPublicKey) throws SQLException { PreparedStatement s = connection.prepareStatement(sqlCreateHWIDLog); s.setLong(1, hwidId); s.setBlob(2, new ByteArrayInputStream(newPublicKey)); s.executeUpdate(); } + private void setUserHardwareId(Connection connection, String username, long hwidId) throws SQLException { - if(sqlUpdateUsers == null || username == null) return; + if (sqlUpdateUsers == null || username == null) return; PreparedStatement s = connection.prepareStatement(sqlUpdateUsers); s.setLong(1, hwidId); s.setString(2, username); diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/interfaces/JoinServerProtectHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/interfaces/JoinServerProtectHandler.java index dafedbe1..e33a9e11 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/interfaces/JoinServerProtectHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/interfaces/JoinServerProtectHandler.java @@ -3,8 +3,7 @@ import pro.gravit.launchserver.socket.Client; public interface JoinServerProtectHandler { - default boolean onJoinServer(String serverID, String username, Client client) - { + default boolean onJoinServer(String serverID, String username, Client client) { return true; } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/interfaces/SecureProtectHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/interfaces/SecureProtectHandler.java index d19b9538..0170bba9 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/interfaces/SecureProtectHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/protect/interfaces/SecureProtectHandler.java @@ -32,8 +32,8 @@ default void verifySecureLevelKey(byte[] publicKey, byte[] data, byte[] signatur default SecurityReportRequestEvent onSecurityReport(SecurityReportResponse report, Client client) { return new SecurityReportRequestEvent(); } - default VerifySecureLevelKeyRequestEvent onSuccessVerify(Client client) - { + + default VerifySecureLevelKeyRequestEvent onSuccessVerify(Client client) { return new VerifySecureLevelKeyRequestEvent(); } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/binary/tasks/ProGuardBuildTask.java b/LaunchServer/src/main/java/pro/gravit/launchserver/binary/tasks/ProGuardBuildTask.java index b8094ae4..7fe6b43a 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/binary/tasks/ProGuardBuildTask.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/binary/tasks/ProGuardBuildTask.java @@ -32,19 +32,18 @@ public Path process(Path inputFile) throws IOException { Configuration proguard_cfg = new Configuration(); ConfigurationParser parser = new ConfigurationParser(server.proguardConf.buildConfig(inputFile, outputJar), server.proguardConf.proguard.toFile(), System.getProperties()); - if (JVMHelper.JVM_VERSION >= 9) - { + if (JVMHelper.JVM_VERSION >= 9) { Path javaJModsPath = Paths.get(System.getProperty("java.home")).resolve("jmods"); - if(!IOHelper.exists(javaJModsPath)) - { + if (!IOHelper.exists(javaJModsPath)) { LogHelper.warning("Directory %s not found. It is not good", javaJModsPath); - } - else - { + } else { //Find javaFX libraries - if(!IOHelper.exists(javaJModsPath.resolve("javafx.base.jmod"))) LogHelper.error("javafx.base.jmod not found. Launcher can be assembled incorrectly. Maybe you need to install OpenJFX?"); - if(!IOHelper.exists(javaJModsPath.resolve("javafx.graphics.jmod"))) LogHelper.error("javafx.graphics.jmod not found. Launcher can be assembled incorrectly. Maybe you need to install OpenJFX?"); - if(!IOHelper.exists(javaJModsPath.resolve("javafx.controls.jmod"))) LogHelper.error("javafx.controls.jmod not found. Launcher can be assembled incorrectly. Maybe you need to install OpenJFX?"); + if (!IOHelper.exists(javaJModsPath.resolve("javafx.base.jmod"))) + LogHelper.error("javafx.base.jmod not found. Launcher can be assembled incorrectly. Maybe you need to install OpenJFX?"); + if (!IOHelper.exists(javaJModsPath.resolve("javafx.graphics.jmod"))) + LogHelper.error("javafx.graphics.jmod not found. Launcher can be assembled incorrectly. Maybe you need to install OpenJFX?"); + if (!IOHelper.exists(javaJModsPath.resolve("javafx.controls.jmod"))) + LogHelper.error("javafx.controls.jmod not found. Launcher can be assembled incorrectly. Maybe you need to install OpenJFX?"); } } try { diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/command/basic/TestCommand.java b/LaunchServer/src/main/java/pro/gravit/launchserver/command/basic/TestCommand.java index ebccc90a..93c53356 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/command/basic/TestCommand.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/command/basic/TestCommand.java @@ -58,31 +58,26 @@ public void invoke(String... args) throws Exception { server.certificateManager.writePrivateKey(Paths.get(name.concat(".key")), pair.getPrivate()); server.certificateManager.writeCertificate(Paths.get(name.concat(".crt")), cert); } - if(args[0].equals("authstresser")) - { + if (args[0].equals("authstresser")) { AuthProviderPair pair = server.config.getAuthProviderPair(); AuthPlainPassword plainPassword = new AuthPlainPassword("test"); Runnable runnable = () -> { long startTime = System.currentTimeMillis(); - for(int i=0;i<100000;++i) - { + for (int i = 0; i < 100000; ++i) { try { pair.provider.auth("Test", plainPassword, "127.0.0.1"); - } catch (AuthException ignored) - { + } catch (AuthException ignored) { } catch (Exception e) { throw new RuntimeException(e); } - if((i % 10000) == 0) - { + if ((i % 10000) == 0) { LogHelper.info("Completed %d requests", i); } } LogHelper.info("Completed all requests. Time %d ms", System.currentTimeMillis() - startTime); }; - for(int i=0;i<7;++i) - { + for (int i = 0; i < 7; ++i) { CommonHelper.newThread(String.format("Stresser #%d", i), true, runnable).start(); } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/DownloadClientCommand.java b/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/DownloadClientCommand.java index 211d32af..760aa109 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/DownloadClientCommand.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/DownloadClientCommand.java @@ -63,11 +63,9 @@ public void invoke(String... args) throws IOException, CommandException { client.setTitle(dirName); client.setDir(dirName); client.setUUID(UUID.randomUUID()); - if(client.getServers() != null) - { - ClientProfile.ServerProfile serverProfile = client.getDefaultServerProfile(); - if(serverProfile != null) - { + if (client.getServers() != null) { + ClientProfile.ServerProfile serverProfile = client.getDefaultServerProfile(); + if (serverProfile != null) { serverProfile.name = dirName; } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/SaveProfilesCommand.java b/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/SaveProfilesCommand.java index 12c05a9d..745d5f76 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/SaveProfilesCommand.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/SaveProfilesCommand.java @@ -27,8 +27,7 @@ public SaveProfilesCommand(LaunchServer server) { @SuppressWarnings("deprecation") public static void saveProfile(ClientProfile profile, Path path) throws IOException { if (profile.getUUID() == null) profile.setUUID(UUID.randomUUID()); - if(profile.getServers().size() == 0) - { + if (profile.getServers().size() == 0) { ClientProfile.ServerProfile serverProfile = new ClientProfile.ServerProfile(); serverProfile.isDefault = true; serverProfile.name = profile.getTitle(); @@ -36,19 +35,16 @@ public static void saveProfile(ClientProfile profile, Path path) throws IOExcept serverProfile.serverPort = profile.getServerPort(); profile.getServers().add(serverProfile); } - for(OptionalFile file : profile.getOptional()) - { - if(file.list != null) - { + for (OptionalFile file : profile.getOptional()) { + if (file.list != null) { String[] list = file.list; file.list = null; - if(file.actions == null) file.actions = new ArrayList<>(2); + if (file.actions == null) file.actions = new ArrayList<>(2); OptionalAction action; - switch (file.type) - { + switch (file.type) { case FILE: OptionalActionFile result = new OptionalActionFile(new HashMap<>()); - for(String s : list) result.files.put(s, ""); + for (String s : list) result.files.put(s, ""); action = result; break; case CLASSPATH: diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/SyncUPCommand.java b/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/SyncUPCommand.java index 83bb9c61..386ffc46 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/SyncUPCommand.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/command/hash/SyncUPCommand.java @@ -25,7 +25,7 @@ public String getUsageDescription() { public void invoke(String... args) throws IOException { server.syncProfilesDir(); LogHelper.subInfo("Profiles successfully resynced"); - + server.syncUpdatesDir(null); LogHelper.subInfo("Updates dir successfully resynced"); } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/launchermodules/LauncherModuleLoader.java b/LaunchServer/src/main/java/pro/gravit/launchserver/launchermodules/LauncherModuleLoader.java index 6575c9ca..d0bf6847 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/launchermodules/LauncherModuleLoader.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/launchermodules/LauncherModuleLoader.java @@ -29,7 +29,8 @@ public class LauncherModuleLoader { private final LaunchServer server; public LauncherModuleLoader(LaunchServer server) { - this.server = server; modulesDir = server.dir.resolve("launcher-modules"); + this.server = server; + modulesDir = server.dir.resolve("launcher-modules"); } public void init() { @@ -140,19 +141,17 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO return super.visitFile(file, attrs); } } + public void addClassFieldsToProperties(Map propertyMap, String prefix, Object object, Class classOfObject) throws IllegalAccessException { Field[] fields = classOfObject.getFields(); for (Field field : fields) { if ((field.getModifiers() & Modifier.STATIC) != 0) continue; Object obj = field.get(object); String propertyName = prefix.concat(".").concat(field.getName().toLowerCase(Locale.US)); - if(InjectClassAcceptor.isSerializableValue(obj)) - { + if (InjectClassAcceptor.isSerializableValue(obj)) { LogHelper.dev("Property name %s", propertyName); propertyMap.put(propertyName, obj); - } - else - { + } else { //Try recursive add fields addClassFieldsToProperties(propertyMap, propertyName, obj, obj.getClass()); } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/manangers/PingServerManager.java b/LaunchServer/src/main/java/pro/gravit/launchserver/manangers/PingServerManager.java index 2222db81..8a720f92 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/manangers/PingServerManager.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/manangers/PingServerManager.java @@ -8,10 +8,9 @@ import java.util.Map; public class PingServerManager { - public static final long REPORT_EXPIRED_TIME = 20*1000; + public static final long REPORT_EXPIRED_TIME = 20 * 1000; - public static class ServerInfoEntry - { + public static class ServerInfoEntry { public PingServerReportRequest.PingServerReport lastReport; public long lastReportTime; public final ClientProfile profile; @@ -26,37 +25,34 @@ public ServerInfoEntry(ClientProfile profile) { this.profile = profile; } - public boolean isExpired() - { + public boolean isExpired() { return System.currentTimeMillis() - lastReportTime > REPORT_EXPIRED_TIME; } } + public final Map map = new HashMap<>(); private final LaunchServer server; public PingServerManager(LaunchServer server) { this.server = server; } - public void syncServers() - { + + public void syncServers() { server.getProfiles().forEach((p) -> { - for(ClientProfile.ServerProfile sp : p.getServers()) - { + for (ClientProfile.ServerProfile sp : p.getServers()) { ServerInfoEntry entry = map.get(sp.name); - if(entry == null) - { + if (entry == null) { map.put(sp.name, new ServerInfoEntry(p)); } } }); } - public boolean updateServer(String name, PingServerReportRequest.PingServerReport report) - { + + public boolean updateServer(String name, PingServerReportRequest.PingServerReport report) { ServerInfoEntry entry = map.get(name); - if(entry == null) + if (entry == null) return false; - else - { + else { entry.lastReportTime = System.currentTimeMillis(); entry.lastReport = report; return true; diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/Client.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/Client.java index b9c7af11..1b5639d5 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/Client.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/Client.java @@ -62,16 +62,15 @@ public static class TrustLevel { public byte[] publicKey; public HardwareReportRequest.HardwareInfo hardwareInfo; } + @SuppressWarnings("unchecked") - public T getProperty(String name) - { - if(properties == null) properties = new HashMap<>(); + public T getProperty(String name) { + if (properties == null) properties = new HashMap<>(); return (T) properties.get(name); } - public void setProperty(String name, T object) - { - if(properties == null) properties = new HashMap<>(); + public void setProperty(String name, T object) { + if (properties == null) properties = new HashMap<>(); properties.put(name, object); } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/LauncherNettyServer.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/LauncherNettyServer.java index f0f5a1dd..7b4f621e 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/LauncherNettyServer.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/LauncherNettyServer.java @@ -61,7 +61,7 @@ public void initChannel(SocketChannel ch) { pipeline.addLast("forward-http", new NettyIpForwardHandler(context)); pipeline.addLast("websock-comp", new WebSocketServerCompressionHandler()); pipeline.addLast("websock-codec", new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true)); - if(!server.config.netty.disableWebApiInterface) + if (!server.config.netty.disableWebApiInterface) pipeline.addLast("webapi", new NettyWebAPIHandler(context)); if (server.config.netty.fileServerEnabled) pipeline.addLast("fileserver", new FileServerHandler(server.updatesDir, true, config.showHiddenFiles)); diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/WebSocketService.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/WebSocketService.java index 41850f60..41588e9e 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/WebSocketService.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/WebSocketService.java @@ -67,8 +67,7 @@ public WebSocketService(ChannelGroup channels, LaunchServer server) { this.gson = Launcher.gsonManager.gson; } - public void forEachActiveChannels(BiConsumer callback) - { + public void forEachActiveChannels(BiConsumer callback) { channels.forEach((channel) -> { if (channel == null || channel.pipeline() == null) return; WebSocketFrameHandler wsHandler = channel.pipeline().get(WebSocketFrameHandler.class); @@ -113,32 +112,28 @@ public void process(ChannelHandlerContext ctx, TextWebSocketFrame frame, Client } process(ctx, response, client, ip); long executeTime = System.nanoTime() - startTimeNanos; - if(executeTime > 0) - { + if (executeTime > 0) { addRequestTimeToStats(executeTime); } } - public void addRequestTimeToStats(long nanos) - { - if(nanos < 100_000_000L) // < 100 millis + public void addRequestTimeToStats(long nanos) { + if (nanos < 100_000_000L) // < 100 millis { shortRequestCounter.getAndIncrement(); shortRequestLatency.getAndAdd(nanos); - } - else if(nanos < 1_000_000_000L) // > 100 millis and < 1 second + } else if (nanos < 1_000_000_000L) // > 100 millis and < 1 second { middleRequestCounter.getAndIncrement(); middleRequestLatency.getAndAdd(nanos); - } - else // > 1 second + } else // > 1 second { longRequestCounter.getAndIncrement(); longRequestLatency.getAndAdd(nanos); } long lastTime = lastRequestTime.get(); long currentTime = System.currentTimeMillis(); - if(currentTime - lastTime > 60*1000) //1 minute + if (currentTime - lastTime > 60 * 1000) //1 minute { lastRequestTime.set(currentTime); shortRequestLatency.set(0); diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/handlers/NettyWebAPIHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/handlers/NettyWebAPIHandler.java index d445473b..84e7da03 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/handlers/NettyWebAPIHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/handlers/NettyWebAPIHandler.java @@ -2,10 +2,11 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.handler.codec.http.*; +import io.netty.handler.codec.http.FullHttpRequest; import pro.gravit.launchserver.socket.NettyConnectContext; -import java.util.*; +import java.util.Comparator; +import java.util.TreeSet; public class NettyWebAPIHandler extends SimpleChannelInboundHandler { private final NettyConnectContext context; @@ -14,10 +15,12 @@ public NettyWebAPIHandler(NettyConnectContext context) { super(); this.context = context; } + @FunctionalInterface public interface SimpleSeverletHandler { void handle(ChannelHandlerContext ctx, FullHttpRequest msg, NettyConnectContext context) throws Exception; } + public static class SeverletPathPair { public final String key; public final SimpleSeverletHandler callback; @@ -27,37 +30,36 @@ public SeverletPathPair(String key, SimpleSeverletHandler callback) { this.callback = callback; } } + private static final TreeSet severletList = new TreeSet<>(Comparator.comparingInt((e) -> -e.key.length())); - public static SeverletPathPair addNewSeverlet(String path, SimpleSeverletHandler callback) - { + + public static SeverletPathPair addNewSeverlet(String path, SimpleSeverletHandler callback) { SeverletPathPair pair = new SeverletPathPair("/webapi/".concat(path), callback); severletList.add(pair); return pair; } - public static SeverletPathPair addUnsafeSeverlet(String path, SimpleSeverletHandler callback) - { + + public static SeverletPathPair addUnsafeSeverlet(String path, SimpleSeverletHandler callback) { SeverletPathPair pair = new SeverletPathPair(path, callback); severletList.add(pair); return pair; } - public static void removeSeverlet(SeverletPathPair pair) - { + + public static void removeSeverlet(SeverletPathPair pair) { severletList.remove(pair); } + @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { boolean isNext = true; - for(SeverletPathPair pair : severletList) - { - if(msg.uri().startsWith(pair.key)) - { + for (SeverletPathPair pair : severletList) { + if (msg.uri().startsWith(pair.key)) { pair.callback.handle(ctx, msg, context); isNext = false; break; } } - if(isNext) - { + if (isNext) { msg.retain(); ctx.fireChannelRead(msg); } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/handlers/WebSocketFrameHandler.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/handlers/WebSocketFrameHandler.java index c6950756..5e374f42 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/handlers/WebSocketFrameHandler.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/handlers/WebSocketFrameHandler.java @@ -50,13 +50,13 @@ public void channelActive(ChannelHandlerContext ctx) { client = new Client(null); Channel ch = ctx.channel(); service.registerClient(ch); - ctx.executor().scheduleAtFixedRate(() -> ch.writeAndFlush(new PingWebSocketFrame(), ch.voidPromise()), 30L , 30L, TimeUnit.SECONDS); + ctx.executor().scheduleAtFixedRate(() -> ch.writeAndFlush(new PingWebSocketFrame(), ch.voidPromise()), 30L, 30L, TimeUnit.SECONDS); } @Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) { // ping and pong frames already handled - if(hooks.hook(ctx, frame)) return; + if (hooks.hook(ctx, frame)) return; if (frame instanceof TextWebSocketFrame) { service.process(ctx, (TextWebSocketFrame) frame, client, context.ip); } else if ((frame instanceof PingWebSocketFrame)) { diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/AuthResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/AuthResponse.java index 0f09af7c..ed2ec816 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/AuthResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/AuthResponse.java @@ -85,8 +85,7 @@ public void execute(ChannelHandlerContext ctx, Client clientData) throws Excepti clientData.username = aresult.username; else clientData.username = login; - if(aresult instanceof AuthProviderDAOResult) - { + if (aresult instanceof AuthProviderDAOResult) { clientData.daoObject = ((AuthProviderDAOResult) aresult).daoObject; } result.accessToken = aresult.accessToken; @@ -104,9 +103,7 @@ public void execute(ChannelHandlerContext ctx, Client clientData) throws Excepti if (LogHelper.isDebugEnabled()) { LogHelper.debug("Auth: %s accessToken %s uuid: %s", login, result.accessToken, uuid.toString()); } - } - else - { + } else { uuid = pair.handler.usernameToUUID(aresult.username); result.accessToken = null; } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/CurrentUserResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/CurrentUserResponse.java index 5f5be740..6d5cfd33 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/CurrentUserResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/CurrentUserResponse.java @@ -20,13 +20,11 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception { sendResult(new CurrentUserRequestEvent(collectUserInfoFromClient(client))); } - public static CurrentUserRequestEvent.UserInfo collectUserInfoFromClient(Client client) throws IOException - { + public static CurrentUserRequestEvent.UserInfo collectUserInfoFromClient(Client client) throws IOException { CurrentUserRequestEvent.UserInfo result = new CurrentUserRequestEvent.UserInfo(); - if(client.auth != null && client.isAuth && client.username != null) { + if (client.auth != null && client.isAuth && client.username != null) { UUID uuid = client.auth.handler.usernameToUUID(client.username); - if(uuid != null) - { + if (uuid != null) { result.playerProfile = ProfileByUUIDResponse.getProfile(uuid, client.username, client.profile == null ? null : client.profile.getTitle(), client.auth.textureProvider); } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/ExitResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/ExitResponse.java index 60cfbc0d..66d3cec1 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/ExitResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/ExitResponse.java @@ -54,16 +54,15 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception { } else { service.forEachActiveChannels(((channel, webSocketFrameHandler) -> { Client client1 = webSocketFrameHandler.getClient(); - if(client1 != null && client.isAuth && client.username != null && client1.username.equals(username)) - { + if (client1 != null && client.isAuth && client.username != null && client1.username.equals(username)) { exit(server, webSocketFrameHandler, channel, ExitRequestEvent.ExitReason.SERVER); } })); sendResult(new ExitRequestEvent(ExitRequestEvent.ExitReason.NO_EXIT)); } } - public static void exit(LaunchServer server, WebSocketFrameHandler wsHandler, Channel channel, ExitRequestEvent.ExitReason reason) - { + + public static void exit(LaunchServer server, WebSocketFrameHandler wsHandler, Channel channel, ExitRequestEvent.ExitReason reason) { Client chClient = wsHandler.getClient(); Client newCusClient = new Client(null); diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/JoinServerResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/JoinServerResponse.java index 1fd65dc0..503f1474 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/JoinServerResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/JoinServerResponse.java @@ -28,11 +28,9 @@ public void execute(ChannelHandlerContext ctx, Client client) { boolean success; try { server.authHookManager.joinServerHook.hook(this, client); - if(server.config.protectHandler instanceof JoinServerProtectHandler) - { + if (server.config.protectHandler instanceof JoinServerProtectHandler) { success = ((JoinServerProtectHandler) server.config.protectHandler).onJoinServer(serverID, username, client); - if(!success) - { + if (!success) { sendResult(new JoinServerRequestEvent(false)); return; } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/RestoreSessionResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/RestoreSessionResponse.java index 3896f3a9..f68aefb6 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/RestoreSessionResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/auth/RestoreSessionResponse.java @@ -28,12 +28,9 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception { } WebSocketFrameHandler frameHandler = ctx.pipeline().get(WebSocketFrameHandler.class); frameHandler.setClient(rClient); - if(needUserInfo) - { + if (needUserInfo) { sendResult(new RestoreSessionRequestEvent(CurrentUserResponse.collectUserInfoFromClient(rClient))); - } - else - { + } else { sendResult(new RestoreSessionRequestEvent()); } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/PingServerReportResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/PingServerReportResponse.java index b0956a0c..e44c7bfd 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/PingServerReportResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/PingServerReportResponse.java @@ -10,6 +10,7 @@ public class PingServerReportResponse extends SimpleResponse { public PingServerReportRequest.PingServerReport data; public String name; + @Override public String getType() { return "pingServerReport"; @@ -17,8 +18,7 @@ public String getType() { @Override public void execute(ChannelHandlerContext ctx, Client client) throws Exception { - if(!client.isAuth || client.permissions == null || !client.permissions.isPermission(ClientPermissions.PermissionConsts.MANAGEMENT)) - { + if (!client.isAuth || client.permissions == null || !client.permissions.isPermission(ClientPermissions.PermissionConsts.MANAGEMENT)) { sendError("Access denied"); return; } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/PingServerResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/PingServerResponse.java index 8fc83c28..c1281a16 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/PingServerResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/PingServerResponse.java @@ -13,6 +13,7 @@ public class PingServerResponse extends SimpleResponse { public List serverNames; //May be null + @Override public String getType() { return "pingServer"; @@ -21,24 +22,18 @@ public String getType() { @Override public void execute(ChannelHandlerContext ctx, Client client) throws Exception { Map map = new HashMap<>(); - if(serverNames == null) - { + if (serverNames == null) { server.pingServerManager.map.forEach((name, entity) -> { - if(server.config.protectHandler instanceof ProfilesProtectHandler) - { - if(!((ProfilesProtectHandler) server.config.protectHandler).canGetProfile(entity.profile, client)) - { + if (server.config.protectHandler instanceof ProfilesProtectHandler) { + if (!((ProfilesProtectHandler) server.config.protectHandler).canGetProfile(entity.profile, client)) { return; } } - if(!entity.isExpired()) - { + if (!entity.isExpired()) { map.put(name, entity.lastReport); } }); - } - else - { + } else { sendError("Not implemented"); return; } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/ServerStatusResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/ServerStatusResponse.java index d6e17c45..4eb8939e 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/ServerStatusResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/management/ServerStatusResponse.java @@ -17,11 +17,11 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception { ServerStatusRequestEvent event = new ServerStatusRequestEvent(server.config.projectName); event.totalJavaMemory = JVMHelper.RUNTIME.totalMemory(); event.freeJavaMemory = JVMHelper.RUNTIME.freeMemory(); - event.shortLatency = ( service.shortRequestLatency.get() / service.shortRequestCounter.get() ) / 1_000_000; - event.middleLatency = ( service.middleRequestLatency.get() / service.middleRequestCounter.get() ) / 1_000_000; - event.longLatency = ( service.longRequestLatency.get() / service.longRequestCounter.get() ) / 1_000_000; - event.latency = ( ( service.shortRequestLatency.get() + service.middleRequestLatency.get() + service.longRequestLatency.get() ) / - ( service.shortRequestCounter.get() + service.middleRequestCounter.get() + service.longRequestCounter.get() ) ) / 1_000_000; + event.shortLatency = (service.shortRequestLatency.get() / service.shortRequestCounter.get()) / 1_000_000; + event.middleLatency = (service.middleRequestLatency.get() / service.middleRequestCounter.get()) / 1_000_000; + event.longLatency = (service.longRequestLatency.get() / service.longRequestCounter.get()) / 1_000_000; + event.latency = ((service.shortRequestLatency.get() + service.middleRequestLatency.get() + service.longRequestLatency.get()) / + (service.shortRequestCounter.get() + service.middleRequestCounter.get() + service.longRequestCounter.get())) / 1_000_000; sendResult(event); } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/profile/ProfileByUsername.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/profile/ProfileByUsername.java index d63e21c0..506b0c92 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/profile/ProfileByUsername.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/profile/ProfileByUsername.java @@ -2,9 +2,9 @@ import io.netty.channel.ChannelHandlerContext; import pro.gravit.launcher.events.request.ProfileByUsernameRequestEvent; +import pro.gravit.launchserver.auth.AuthProviderPair; import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.response.SimpleResponse; -import pro.gravit.launchserver.auth.AuthProviderPair; import java.util.UUID; @@ -21,10 +21,9 @@ public String getType() { public void execute(ChannelHandlerContext ctx, Client client) throws Exception { UUID uuid; AuthProviderPair pair = client.auth; - if(pair == null) pair = server.config.getAuthProviderPair(); + if (pair == null) pair = server.config.getAuthProviderPair(); uuid = pair.handler.usernameToUUID(username); - if(uuid == null) - { + if (uuid == null) { sendError("User not found"); return; } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/HardwareReportResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/HardwareReportResponse.java index df1610e5..501ba310 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/HardwareReportResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/HardwareReportResponse.java @@ -17,17 +17,13 @@ public String getType() { @Override public void execute(ChannelHandlerContext ctx, Client client) throws Exception { - if(server.config.protectHandler instanceof HardwareProtectHandler) - { + if (server.config.protectHandler instanceof HardwareProtectHandler) { try { ((HardwareProtectHandler) server.config.protectHandler).onHardwareReport(this, client); - } catch (SecurityException e) - { + } catch (SecurityException e) { sendError(e.getMessage()); } - } - else - { + } else { sendResult(new HardwareReportRequestEvent()); } } diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/VerifySecureLevelKeyResponse.java b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/VerifySecureLevelKeyResponse.java index 05673e12..d289c4f0 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/VerifySecureLevelKeyResponse.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/socket/response/secure/VerifySecureLevelKeyResponse.java @@ -40,8 +40,7 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception { client.trustLevel.publicKey = publicKey; try { sendResult(secureProtectHandler.onSuccessVerify(client)); - } catch (SecurityException e) - { + } catch (SecurityException e) { sendError(e.getMessage()); } diff --git a/Launcher/src/main/java/pro/gravit/launcher/ClientLauncherWrapper.java b/Launcher/src/main/java/pro/gravit/launcher/ClientLauncherWrapper.java index 90e52953..94edcf82 100644 --- a/Launcher/src/main/java/pro/gravit/launcher/ClientLauncherWrapper.java +++ b/Launcher/src/main/java/pro/gravit/launcher/ClientLauncherWrapper.java @@ -22,8 +22,8 @@ public class ClientLauncherWrapper { public static final String NO_JAVA_CHECK_PROPERTY = "launcher.noJavaCheck"; public static boolean noJavaCheck = Boolean.getBoolean(NO_JAVA_CHECK_PROPERTY); public static boolean waitProcess = Boolean.getBoolean(WAIT_PROCESS_PROPERTY); - public static class JavaVersion - { + + public static class JavaVersion { public final Path jvmDir; public final int version; public boolean enabledJavaFX; @@ -33,31 +33,29 @@ public JavaVersion(Path jvmDir, int version) { this.version = version; this.enabledJavaFX = true; } - public static JavaVersion getCurrentJavaVersion() - { + + public static JavaVersion getCurrentJavaVersion() { return new JavaVersion(Paths.get(System.getProperty("java.home")), JVMHelper.getVersion()); } + public static JavaVersion getByPath(Path jvmDir) throws IOException { Path releaseFile = jvmDir.resolve("release"); - if(!IOHelper.isFile(releaseFile)) return null; + if (!IOHelper.isFile(releaseFile)) return null; Properties properties = new Properties(); properties.load(IOHelper.newReader(releaseFile)); int javaVersion = getJavaVersion(properties.getProperty("JAVA_VERSION").replaceAll("\"", "")); JavaVersion resultJavaVersion = new JavaVersion(jvmDir, javaVersion); - if(javaVersion <= 8) - { + if (javaVersion <= 8) { resultJavaVersion.enabledJavaFX = isExistExtJavaLibrary(jvmDir, "jfxrt"); - } - else - { + } else { resultJavaVersion.enabledJavaFX = tryFindModule(jvmDir, "javafx.base") != null; - if(!resultJavaVersion.enabledJavaFX) + if (!resultJavaVersion.enabledJavaFX) resultJavaVersion.enabledJavaFX = tryFindModule(jvmDir.resolve("jre"), "javafx.base") != null; } return resultJavaVersion; } - public static boolean isExistExtJavaLibrary(Path jvmDir, String name) - { + + public static boolean isExistExtJavaLibrary(Path jvmDir, String name) { Path jrePath = jvmDir.resolve("lib").resolve("ext").resolve(name.concat(".jar")); Path jdkPath = jvmDir.resolve("jre").resolve("lib").resolve("ext").resolve(name.concat(".jar")); return IOHelper.isFile(jrePath) || IOHelper.isFile(jdkPath); @@ -94,12 +92,11 @@ public static void main(String[] arguments) throws IOException, InterruptedExcep JavaVersion javaVersion = null; try { - if(!noJavaCheck) javaVersion = findJava(); + if (!noJavaCheck) javaVersion = findJava(); } catch (Throwable e) { LogHelper.error(e); } - if (javaVersion == null) - { + if (javaVersion == null) { javaVersion = JavaVersion.getCurrentJavaVersion(); } @@ -187,64 +184,54 @@ public static boolean tryAddModule(Path[] paths, String moduleName, StringBuilde return false; } - public static JavaVersion findJavaByProgramFiles(Path path) - { + public static JavaVersion findJavaByProgramFiles(Path path) { LogHelper.debug("Check Java in %s", path.toString()); JavaVersion selectedJava = null; File[] candidates = path.toFile().listFiles(File::isDirectory); - if(candidates == null) return null; - for(File candidate : candidates) - { + if (candidates == null) return null; + for (File candidate : candidates) { Path javaPath = candidate.toPath(); try { JavaVersion javaVersion = JavaVersion.getByPath(javaPath); - if(javaVersion == null || javaVersion.version < 8) continue; + if (javaVersion == null || javaVersion.version < 8) continue; LogHelper.debug("Found Java %d in %s (javafx %s)", javaVersion.version, javaVersion.jvmDir.toString(), javaVersion.enabledJavaFX ? "true" : "false"); - if(javaVersion.enabledJavaFX && (selectedJava == null || !selectedJava.enabledJavaFX)) - { + if (javaVersion.enabledJavaFX && (selectedJava == null || !selectedJava.enabledJavaFX)) { selectedJava = javaVersion; continue; } - if(selectedJava != null && javaVersion.enabledJavaFX && javaVersion.version < selectedJava.version) - { + if (selectedJava != null && javaVersion.enabledJavaFX && javaVersion.version < selectedJava.version) { selectedJava = javaVersion; } } catch (IOException e) { LogHelper.error(e); } } - if(selectedJava != null) - { + if (selectedJava != null) { LogHelper.debug("Selected Java %d in %s (javafx %s)", selectedJava.version, selectedJava.jvmDir.toString(), selectedJava.enabledJavaFX ? "true" : "false"); } return selectedJava; } - public static JavaVersion findJava() - { - if(JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE) - { + public static JavaVersion findJava() { + if (JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE) { JavaVersion result = null; Path defaultJvmContainerDir = Paths.get(System.getProperty("java.home")).getParent(); - if(defaultJvmContainerDir.getParent().getFileName().toString().contains("x86")) //Program Files (x86) ? + if (defaultJvmContainerDir.getParent().getFileName().toString().contains("x86")) //Program Files (x86) ? { Path programFiles64 = defaultJvmContainerDir.getParent().getParent().resolve("Program Files").resolve("Java"); - if(IOHelper.isDir(programFiles64)) - { + if (IOHelper.isDir(programFiles64)) { result = findJavaByProgramFiles(programFiles64); } } - if(result == null) - { + if (result == null) { result = findJavaByProgramFiles(defaultJvmContainerDir); } return result; } - return null; + return null; } - public static int getJavaVersion(String version) - { + public static int getJavaVersion(String version) { if (version.startsWith("1.")) { version = version.substring(2, 3); } else { diff --git a/Launcher/src/main/java/pro/gravit/launcher/client/ClientLauncherEntryPoint.java b/Launcher/src/main/java/pro/gravit/launcher/client/ClientLauncherEntryPoint.java index ef0cb3d0..9c5cc9b6 100644 --- a/Launcher/src/main/java/pro/gravit/launcher/client/ClientLauncherEntryPoint.java +++ b/Launcher/src/main/java/pro/gravit/launcher/client/ClientLauncherEntryPoint.java @@ -54,7 +54,7 @@ private static ClientLauncherProcess.ClientParams readParams(SocketAddress addre params.clientHDir = new HashedDir(input); params.assetHDir = new HashedDir(input); boolean isNeedReadJavaDir = input.readBoolean(); - if(isNeedReadJavaDir) + if (isNeedReadJavaDir) params.javaHDir = new HashedDir(input); return params; } @@ -98,9 +98,9 @@ public static void main(String[] args) throws Throwable { List classpath = new LinkedList<>(); resolveClassPathStream(clientDir, params.profile.getClassPath()).map(IOHelper::toURL).collect(Collectors.toCollection(() -> classpath)); - for(OptionalAction a : params.actions) { - if(a instanceof OptionalActionClassPath) - resolveClassPathStream(clientDir, ((OptionalActionClassPath) a).args).map(IOHelper::toURL).collect(Collectors.toCollection(() -> classpath)); + for (OptionalAction a : params.actions) { + if (a instanceof OptionalActionClassPath) + resolveClassPathStream(clientDir, ((OptionalActionClassPath) a).args).map(IOHelper::toURL).collect(Collectors.toCollection(() -> classpath)); } classLoader = new ClientClassLoader(classpath.toArray(new URL[0]), ClassLoader.getSystemClassLoader()); Thread.currentThread().setContextClassLoader(classLoader); @@ -152,14 +152,14 @@ public static void main(String[] args) throws Throwable { // Start WatchService, and only then client CommonHelper.newThread("Asset Directory Watcher", true, assetWatcher).start(); CommonHelper.newThread("Client Directory Watcher", true, clientWatcher).start(); - if(javaWatcher != null) + if (javaWatcher != null) CommonHelper.newThread("Java Directory Watcher", true, clientWatcher).start(); verifyHDir(assetDir, params.assetHDir, assetMatcher, digest); verifyHDir(clientDir, params.clientHDir, clientMatcher, digest); - if(javaWatcher != null) + if (javaWatcher != null) verifyHDir(javaDir, params.javaHDir, null, digest); - if(params.javaHDir != null) - LauncherEngine.modulesManager.invokeEvent(new ClientProcessLaunchEvent(engine, params)); + if (params.javaHDir != null) + LauncherEngine.modulesManager.invokeEvent(new ClientProcessLaunchEvent(engine, params)); launch(profile, params); } } diff --git a/Launcher/src/main/java/pro/gravit/launcher/client/ClientLauncherProcess.java b/Launcher/src/main/java/pro/gravit/launcher/client/ClientLauncherProcess.java index 50789552..136b7400 100644 --- a/Launcher/src/main/java/pro/gravit/launcher/client/ClientLauncherProcess.java +++ b/Launcher/src/main/java/pro/gravit/launcher/client/ClientLauncherProcess.java @@ -78,8 +78,7 @@ public ClientLauncherProcess(Path clientDir, Path assetDir, Path javaDir, Path r this.params.assetHDir = assetHDir; this.params.clientHDir = clientHDir; this.params.javaHDir = jvmHDir; - if(view != null) - { + if (view != null) { this.params.actions = view.getEnabledActions(); } this.bits = JVMHelper.JVM_BITS; @@ -96,10 +95,8 @@ public static String getPathSeparator() { private void applyClientProfile() { this.systemClassPath.add(IOHelper.getCodeSource(ClientLauncherEntryPoint.class).toAbsolutePath().toString()); Collections.addAll(this.jvmArgs, this.params.profile.getJvmArgs()); - for(OptionalAction a : this.params.actions) - { - if(a instanceof OptionalActionJvmArgs) - { + for (OptionalAction a : this.params.actions) { + if (a instanceof OptionalActionJvmArgs) { this.jvmArgs.addAll(((OptionalActionJvmArgs) a).args); } } @@ -164,10 +161,9 @@ public void runWriteParams(SocketAddress address) throws IOException { output.writeByteArray(serializedMainParams, 0); params.clientHDir.write(output); params.assetHDir.write(output); - if(params.javaHDir == null || params.javaHDir == params.assetHDir) { //TODO: OLD RUNTIME USE params.assetHDir AS NULL IN java.javaHDir + if (params.javaHDir == null || params.javaHDir == params.assetHDir) { //TODO: OLD RUNTIME USE params.assetHDir AS NULL IN java.javaHDir output.writeBoolean(false); - } - else { + } else { output.writeBoolean(true); params.javaHDir.write(output); } @@ -279,10 +275,8 @@ private void addModernClientArgs(Collection args) { Collections.addAll(args, "--server", profile.getServerAddress()); Collections.addAll(args, "--port", Integer.toString(profile.getServerPort())); } - for(OptionalAction a : actions) - { - if(a instanceof OptionalActionClientArgs) - { + for (OptionalAction a : actions) { + if (a instanceof OptionalActionClientArgs) { args.addAll(((OptionalActionClientArgs) a).args); } } diff --git a/Launcher/src/main/java/pro/gravit/launcher/client/ServerPinger.java b/Launcher/src/main/java/pro/gravit/launcher/client/ServerPinger.java index 136efc9c..21cb94da 100644 --- a/Launcher/src/main/java/pro/gravit/launcher/client/ServerPinger.java +++ b/Launcher/src/main/java/pro/gravit/launcher/client/ServerPinger.java @@ -38,10 +38,9 @@ public final class ServerPinger { public ServerPinger(ClientProfile profile) { this(profile.getDefaultServerProfile(), profile.getVersion()); } - public ServerPinger(ClientProfile.ServerProfile profile, ClientProfile.Version version) - { - if(profile == null) - { + + public ServerPinger(ClientProfile.ServerProfile profile, ClientProfile.Version version) { + if (profile == null) { throw new NullPointerException("ServerProfile null"); } this.address = profile.toSocketAddress(); diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/events/request/CurrentUserRequestEvent.java b/LauncherAPI/src/main/java/pro/gravit/launcher/events/request/CurrentUserRequestEvent.java index eed9b1a1..db4d0edc 100644 --- a/LauncherAPI/src/main/java/pro/gravit/launcher/events/request/CurrentUserRequestEvent.java +++ b/LauncherAPI/src/main/java/pro/gravit/launcher/events/request/CurrentUserRequestEvent.java @@ -10,6 +10,7 @@ public static class UserInfo { public String accessToken; public PlayerProfile playerProfile; } + public final UserInfo userInfo; public CurrentUserRequestEvent(UserInfo userInfo) { diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/ClientProfile.java b/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/ClientProfile.java index 7e91dc0b..3c83cdad 100644 --- a/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/ClientProfile.java +++ b/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/ClientProfile.java @@ -72,24 +72,23 @@ public final class ClientProfile implements Comparable { @LauncherNetworkAPI private String mainClass; - public static class ServerProfile - { + public static class ServerProfile { public String name; public String serverAddress; public int serverPort; public boolean isDefault = true; - public InetSocketAddress toSocketAddress() - { + + public InetSocketAddress toSocketAddress() { return InetSocketAddress.createUnresolved(serverAddress, serverPort); } } + @LauncherNetworkAPI private List servers = new ArrayList<>(1); - public ServerProfile getDefaultServerProfile() - { - for(ServerProfile profile : servers) - { - if(profile.isDefault) return profile; + + public ServerProfile getDefaultServerProfile() { + for (ServerProfile profile : servers) { + if (profile.isDefault) return profile; } return null; } @@ -184,6 +183,7 @@ public void updateOptionalGraph() { } } } + @Deprecated public OptionalFile getOptionalFile(String file, OptionalType type) { for (OptionalFile f : updateOptional) @@ -220,6 +220,7 @@ public void markOptional(OptionalFile file) { } } } + @Deprecated public void unmarkOptional(OptionalFile file) { if (!file.mark) return; @@ -246,6 +247,7 @@ public void unmarkOptional(OptionalFile file) { } } } + @Deprecated public void pushOptionalFile(HashedDir dir, boolean digest) { for (OptionalFile opt : updateOptional) { @@ -255,6 +257,7 @@ public void pushOptionalFile(HashedDir dir, boolean digest) { } } } + @Deprecated public void pushOptionalJvmArgs(Collection jvmArgs1) { for (OptionalFile opt : updateOptional) { @@ -263,6 +266,7 @@ public void pushOptionalJvmArgs(Collection jvmArgs1) { } } } + @Deprecated public void pushOptionalClientArgs(Collection clientArgs1) { for (OptionalFile opt : updateOptional) { @@ -271,6 +275,7 @@ public void pushOptionalClientArgs(Collection clientArgs1) { } } } + @Deprecated public void pushOptionalClassPath(pushOptionalClassPathCallback callback) throws IOException { for (OptionalFile opt : updateOptional) { @@ -284,6 +289,7 @@ public int getServerPort() { ServerProfile profile = getDefaultServerProfile(); return profile == null ? 25565 : profile.serverPort; } + @Deprecated public InetSocketAddress getServerSocketAddress() { return InetSocketAddress.createUnresolved(getServerAddress(), getServerPort()); diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/OptionalView.java b/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/OptionalView.java index 0430f34f..debcedeb 100644 --- a/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/OptionalView.java +++ b/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/OptionalView.java @@ -14,17 +14,12 @@ public class OptionalView { public Set all; @SuppressWarnings("unchecked") - public Set getActionsByClass(Class clazz) - { + public Set getActionsByClass(Class clazz) { Set results = new HashSet<>(); - for(OptionalFile e : enabled) - { - if(e.actions != null) - { - for(OptionalAction a : e.actions) - { - if(clazz.isAssignableFrom(a.getClass())) - { + for (OptionalFile e : enabled) { + if (e.actions != null) { + for (OptionalAction a : e.actions) { + if (clazz.isAssignableFrom(a.getClass())) { results.add((T) a); } } @@ -33,36 +28,29 @@ public Set getActionsByClass(Class clazz) return results; } - public Set getEnabledActions() - { + public Set getEnabledActions() { Set results = new HashSet<>(); - for(OptionalFile e : enabled) - { - if(e.actions != null) - { + for (OptionalFile e : enabled) { + if (e.actions != null) { results.addAll(e.actions); } } return results; } - public Set getDisabledActions() - { + public Set getDisabledActions() { Set results = new HashSet<>(); - for(OptionalFile e : all) - { - if(enabled.contains(e)) continue; - if(e.actions != null) - { + for (OptionalFile e : all) { + if (enabled.contains(e)) continue; + if (e.actions != null) { results.addAll(e.actions); } } return results; } - public void enable(OptionalFile file) - { - if(enabled.contains(file)) return; + public void enable(OptionalFile file) { + if (enabled.contains(file)) return; enabled.add(file); file.watchEvent(true); if (file.dependencies != null) { @@ -78,9 +66,9 @@ public void enable(OptionalFile file) } } } - public void disable(OptionalFile file) - { - if(!enabled.remove(file)) return; + + public void disable(OptionalFile file) { + if (!enabled.remove(file)) return; file.watchEvent(false); Set dependenciesCount = dependenciesCountMap.get(file); if (dependenciesCount != null) { @@ -103,16 +91,15 @@ public void disable(OptionalFile file) } } } - public OptionalView(ClientProfile profile) - { + + public OptionalView(ClientProfile profile) { this.all = profile.getOptional(); - for(OptionalFile f : this.all) - { - if(f.mark) enable(f); + for (OptionalFile f : this.all) { + if (f.mark) enable(f); } } - public OptionalView(OptionalView view) - { + + public OptionalView(OptionalView view) { this.enabled = new HashSet<>(view.enabled); this.dependenciesCountMap = new HashMap<>(view.dependenciesCountMap); this.all = view.all; diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/actions/OptionalAction.java b/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/actions/OptionalAction.java index fda3c137..aabc8ccc 100644 --- a/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/actions/OptionalAction.java +++ b/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/actions/OptionalAction.java @@ -5,10 +5,9 @@ public class OptionalAction { public static final ProviderMap providers = new ProviderMap<>(); private static boolean registerProviders = false; - public static void registerProviders() - { - if(!registerProviders) - { + + public static void registerProviders() { + if (!registerProviders) { providers.register("file", OptionalActionFile.class); providers.register("clientArgs", OptionalActionClientArgs.class); providers.register("jvmArgs", OptionalActionJvmArgs.class); diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/actions/OptionalActionFile.java b/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/actions/OptionalActionFile.java index a0005e38..55c0a63b 100644 --- a/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/actions/OptionalActionFile.java +++ b/LauncherAPI/src/main/java/pro/gravit/launcher/profiles/optional/actions/OptionalActionFile.java @@ -7,10 +7,10 @@ public class OptionalActionFile extends OptionalAction { public Map files; - public void injectToHashedDir(HashedDir dir) - { - if(files == null) return; - files.forEach((k,v) -> { + + public void injectToHashedDir(HashedDir dir) { + if (files == null) return; + files.forEach((k, v) -> { HashedDir.FindRecursiveResult firstPath = dir.findRecursive(k); if (v != null && !v.isEmpty()) { LogHelper.dev("Debug findRecursive: name %s, parent: ", firstPath.name, firstPath.parent == null ? "null" : "not null", firstPath.entry == null ? "null" : "not null"); @@ -20,10 +20,10 @@ public void injectToHashedDir(HashedDir dir) } }); } - public void disableInHashedDir(HashedDir dir) - { - if(files == null) return; - files.forEach((k,v) -> { + + public void disableInHashedDir(HashedDir dir) { + if (files == null) return; + files.forEach((k, v) -> { HashedDir.FindRecursiveResult firstPath = dir.findRecursive(k); firstPath.parent.remove(firstPath.name); }); diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/Auth2FAPassword.java b/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/Auth2FAPassword.java index 55cfea1d..19996d53 100644 --- a/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/Auth2FAPassword.java +++ b/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/Auth2FAPassword.java @@ -5,6 +5,7 @@ public class Auth2FAPassword implements AuthRequest.AuthPasswordInterface { public AuthRequest.AuthPasswordInterface firstPassword; public AuthRequest.AuthPasswordInterface secondPassword; + @Override public boolean check() { return firstPassword != null && firstPassword.check() && secondPassword != null && secondPassword.check(); diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/AuthSignaturePassword.java b/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/AuthSignaturePassword.java index 1a7ba47c..7996aa2b 100644 --- a/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/AuthSignaturePassword.java +++ b/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/AuthSignaturePassword.java @@ -6,6 +6,7 @@ public class AuthSignaturePassword implements AuthRequest.AuthPasswordInterface public byte[] signature; public byte[] publicKey; public byte[] salt; + @Override public boolean check() { return true; diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/AuthTOTPPassword.java b/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/AuthTOTPPassword.java index 92b57c0d..96679d29 100644 --- a/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/AuthTOTPPassword.java +++ b/LauncherAPI/src/main/java/pro/gravit/launcher/request/auth/password/AuthTOTPPassword.java @@ -4,6 +4,7 @@ public class AuthTOTPPassword implements AuthRequest.AuthPasswordInterface { public String totp; + @Override public boolean check() { return true; diff --git a/LauncherAPI/src/main/java/pro/gravit/launcher/request/management/PingServerReportRequest.java b/LauncherAPI/src/main/java/pro/gravit/launcher/request/management/PingServerReportRequest.java index 1b783bc2..d98e8311 100644 --- a/LauncherAPI/src/main/java/pro/gravit/launcher/request/management/PingServerReportRequest.java +++ b/LauncherAPI/src/main/java/pro/gravit/launcher/request/management/PingServerReportRequest.java @@ -11,19 +11,19 @@ public String getType() { return "pingServerReport"; } - public static class PingServerReport - { + public static class PingServerReport { public final String name; public final int maxPlayers; // player slots public final int playersOnline; - public static class UsernameInfo - { + + public static class UsernameInfo { public final String username; public UsernameInfo(String username) { this.username = username; } } + //Server addional info public double tps; //Server tps public List users; @@ -34,6 +34,7 @@ public PingServerReport(String name, int maxPlayers, int playersOnline) { this.playersOnline = playersOnline; } } + public final String name; public final PingServerReport data; diff --git a/LauncherCore/src/main/java/pro/gravit/launcher/hasher/HashedDir.java b/LauncherCore/src/main/java/pro/gravit/launcher/hasher/HashedDir.java index 4b4d4ebe..cc80ec4f 100644 --- a/LauncherCore/src/main/java/pro/gravit/launcher/hasher/HashedDir.java +++ b/LauncherCore/src/main/java/pro/gravit/launcher/hasher/HashedDir.java @@ -100,13 +100,13 @@ public void removeR(String name) { } } } - public void moveTo(String elementName, HashedDir target, String targetElementName) - { + + public void moveTo(String elementName, HashedDir target, String targetElementName) { HashedEntry entry = map.remove(elementName); target.map.put(targetElementName, entry); } - public static class FindRecursiveResult - { + + public static class FindRecursiveResult { public final HashedDir parent; public final HashedEntry entry; public final String name; @@ -117,8 +117,8 @@ public FindRecursiveResult(HashedDir parent, HashedEntry entry, String name) { this.name = name; } } - public FindRecursiveResult findRecursive(String path) - { + + public FindRecursiveResult findRecursive(String path) { StringTokenizer t = new StringTokenizer(path, "/"); HashedDir current = this; HashedEntry entry = null; @@ -126,16 +126,14 @@ public FindRecursiveResult findRecursive(String path) while (t.hasMoreTokens()) { name = t.nextToken(); HashedEntry e = current.map.get(name); - if(e == null && !t.hasMoreTokens()) - { + if (e == null && !t.hasMoreTokens()) { break; } if (e.getType() == Type.DIR) { - if(!t.hasMoreTokens()) { + if (!t.hasMoreTokens()) { entry = e; break; - } - else { + } else { current = ((HashedDir) e); } } else { diff --git a/LauncherCore/src/main/java/pro/gravit/utils/UniversalJsonAdapter.java b/LauncherCore/src/main/java/pro/gravit/utils/UniversalJsonAdapter.java index 15c753cd..0b7eede7 100644 --- a/LauncherCore/src/main/java/pro/gravit/utils/UniversalJsonAdapter.java +++ b/LauncherCore/src/main/java/pro/gravit/utils/UniversalJsonAdapter.java @@ -54,8 +54,7 @@ public R deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext Class cls = providerMap.getClass(typename); if (cls == null) { //if (printErrorIfUnknownType) LogHelper.error("%s %s not found", name, typename); - if(defaultClass != null) - { + if (defaultClass != null) { return context.deserialize(json, defaultClass); } return null; diff --git a/modules b/modules index aab3e310..4795b7a9 160000 --- a/modules +++ b/modules @@ -1 +1 @@ -Subproject commit aab3e310b3b4b396c80a3aad3f6f9386cf427c39 +Subproject commit 4795b7a967af69ddea48116c718bb32b96e43f83