[ANY] IDEA code inspect

This commit is contained in:
Gravita 2023-04-03 13:04:12 +07:00
parent e0b3f3d6a5
commit 06e9bc8578
129 changed files with 215 additions and 1244 deletions

View file

@ -50,17 +50,18 @@
} }
} }
task sourcesJar(type: Jar) { tasks.register('sourcesJar', Jar) {
from sourceSets.main.allJava from sourceSets.main.allJava
archiveClassifier.set('sources') archiveClassifier.set('sources')
} }
task javadocJar(type: Jar) { tasks.register('javadocJar', Jar) {
from javadoc from javadoc
archiveClassifier.set('javadoc') archiveClassifier.set('javadoc')
} }
task cleanjar(type: Jar, dependsOn: jar) { tasks.register('cleanjar', Jar) {
dependsOn jar
archiveClassifier.set('clean') archiveClassifier.set('clean')
manifest.attributes("Main-Class": mainClassName, manifest.attributes("Main-Class": mainClassName,
"Premain-Class": mainAgentName, "Premain-Class": mainAgentName,
@ -117,13 +118,13 @@ pack project(':LauncherAPI')
compileOnlyA 'org.apache.logging.log4j:log4j-core:2.14.1' compileOnlyA 'org.apache.logging.log4j:log4j-core:2.14.1'
} }
task hikari(type: Copy) { tasks.register('hikari', Copy) {
duplicatesStrategy = 'EXCLUDE' duplicatesStrategy = 'EXCLUDE'
into "$buildDir/libs/libraries/hikaricp" into "$buildDir/libs/libraries/hikaricp"
from configurations.hikari from configurations.hikari
} }
task launch4j(type: Copy) { tasks.register('launch4j', Copy) {
duplicatesStrategy = 'EXCLUDE' duplicatesStrategy = 'EXCLUDE'
into "$buildDir/libs/libraries/launch4j" into "$buildDir/libs/libraries/launch4j"
from(configurations.launch4j.collect { from(configurations.launch4j.collect {
@ -141,20 +142,20 @@ task launch4j(type: Copy) {
} }
} }
task dumpLibs(type: Copy) { tasks.register('dumpLibs', Copy) {
duplicatesStrategy = 'EXCLUDE' duplicatesStrategy = 'EXCLUDE'
dependsOn tasks.hikari, tasks.launch4j dependsOn tasks.hikari, tasks.launch4j
into "$buildDir/libs/libraries" into "$buildDir/libs/libraries"
from configurations.bundleOnly from configurations.bundleOnly
} }
task dumpCompileOnlyLibs(type: Copy) { tasks.register('dumpCompileOnlyLibs', Copy) {
duplicatesStrategy = 'EXCLUDE' duplicatesStrategy = 'EXCLUDE'
into "$buildDir/libs/launcher-libraries-compile" into "$buildDir/libs/launcher-libraries-compile"
from configurations.compileOnlyA from configurations.compileOnlyA
} }
task bundle(type: Zip) { tasks.register('bundle', Zip) {
duplicatesStrategy = 'EXCLUDE' duplicatesStrategy = 'EXCLUDE'
dependsOn parent.childProjects.Launcher.tasks.build, tasks.dumpLibs, tasks.dumpCompileOnlyLibs, tasks.jar dependsOn parent.childProjects.Launcher.tasks.build, tasks.dumpLibs, tasks.dumpCompileOnlyLibs, tasks.jar
archiveFileName = 'LaunchServer.zip' archiveFileName = 'LaunchServer.zip'
@ -165,7 +166,7 @@ task bundle(type: Zip) {
from(parent.childProjects.Launcher.tasks.dumpLibs) { into 'launcher-libraries' } from(parent.childProjects.Launcher.tasks.dumpLibs) { into 'launcher-libraries' }
} }
task dumpClientLibs(type: Copy) { tasks.register('dumpClientLibs', Copy) {
dependsOn parent.childProjects.Launcher.tasks.build dependsOn parent.childProjects.Launcher.tasks.build
into "$buildDir/libs/launcher-libraries" into "$buildDir/libs/launcher-libraries"
from parent.childProjects.Launcher.tasks.dumpLibs from parent.childProjects.Launcher.tasks.dumpLibs

View file

@ -121,7 +121,6 @@ public final class LaunchServer implements Runnable, AutoCloseable, Reconfigurab
// Updates and profiles // Updates and profiles
private volatile Set<ClientProfile> profilesList; private volatile Set<ClientProfile> profilesList;
@SuppressWarnings("deprecation")
public LaunchServer(LaunchServerDirectories directories, LaunchServerEnv env, LaunchServerConfig config, LaunchServerRuntimeConfig runtimeConfig, LaunchServerConfigManager launchServerConfigManager, LaunchServerModulesManager modulesManager, KeyAgreementManager keyAgreementManager, CommandHandler commandHandler, CertificateManager certificateManager) throws IOException { public LaunchServer(LaunchServerDirectories directories, LaunchServerEnv env, LaunchServerConfig config, LaunchServerRuntimeConfig runtimeConfig, LaunchServerConfigManager launchServerConfigManager, LaunchServerModulesManager modulesManager, KeyAgreementManager keyAgreementManager, CommandHandler commandHandler, CertificateManager certificateManager) throws IOException {
this.dir = directories.dir; this.dir = directories.dir;
this.tmpDir = directories.tmpDir; this.tmpDir = directories.tmpDir;

View file

@ -21,7 +21,6 @@
import pro.gravit.launchserver.manangers.LaunchServerGsonManager; import pro.gravit.launchserver.manangers.LaunchServerGsonManager;
import pro.gravit.launchserver.modules.impl.LaunchServerModulesManager; import pro.gravit.launchserver.modules.impl.LaunchServerModulesManager;
import pro.gravit.launchserver.socket.WebSocketService; import pro.gravit.launchserver.socket.WebSocketService;
import pro.gravit.utils.Version;
import pro.gravit.utils.command.CommandHandler; import pro.gravit.utils.command.CommandHandler;
import pro.gravit.utils.command.JLineCommandHandler; import pro.gravit.utils.command.JLineCommandHandler;
import pro.gravit.utils.command.StdCommandHandler; import pro.gravit.utils.command.StdCommandHandler;
@ -202,7 +201,6 @@ public static void initGson(LaunchServerModulesManager modulesManager) {
Launcher.gsonManager.initGson(); Launcher.gsonManager.initGson();
} }
@SuppressWarnings("deprecation")
public static void registerAll() { public static void registerAll() {
AuthCoreProvider.registerProviders(); AuthCoreProvider.registerProviders();
PasswordVerifier.registerProviders(); PasswordVerifier.registerProviders();

View file

@ -65,7 +65,7 @@ private static void visit(ClassNode classNode, Map<String, Object> values) {
return newClinitMethod; return newClinitMethod;
}); });
List<MethodNode> constructors = classNode.methods.stream().filter(method -> "<init>".equals(method.name)) List<MethodNode> constructors = classNode.methods.stream().filter(method -> "<init>".equals(method.name))
.collect(Collectors.toList()); .toList();
MethodNode initMethod = constructors.stream().filter(method -> method.invisibleAnnotations != null MethodNode initMethod = constructors.stream().filter(method -> method.invisibleAnnotations != null
&& method.invisibleAnnotations.stream().anyMatch(annotation -> INJECTED_CONSTRUCTOR_DESC.equals(annotation.desc))).findFirst() && method.invisibleAnnotations.stream().anyMatch(annotation -> INJECTED_CONSTRUCTOR_DESC.equals(annotation.desc))).findFirst()
.orElseGet(() -> constructors.stream().filter(method -> method.desc.equals("()V")).findFirst().orElse(null)); .orElseGet(() -> constructors.stream().filter(method -> method.desc.equals("()V")).findFirst().orElse(null));
@ -112,7 +112,7 @@ public void visit(final String name, final Object value) {
} }
List<FieldInsnNode> putStaticNodes = Arrays.stream(initMethod.instructions.toArray()) List<FieldInsnNode> putStaticNodes = Arrays.stream(initMethod.instructions.toArray())
.filter(node -> node instanceof FieldInsnNode && node.getOpcode() == Opcodes.PUTSTATIC).map(p -> (FieldInsnNode) p) .filter(node -> node instanceof FieldInsnNode && node.getOpcode() == Opcodes.PUTSTATIC).map(p -> (FieldInsnNode) p)
.filter(node -> node.owner.equals(classNode.name) && node.name.equals(field.name) && node.desc.equals(field.desc)).collect(Collectors.toList()); .filter(node -> node.owner.equals(classNode.name) && node.name.equals(field.name) && node.desc.equals(field.desc)).toList();
InsnList setter = serializeValue(value); InsnList setter = serializeValue(value);
if (putStaticNodes.isEmpty()) { if (putStaticNodes.isEmpty()) {
setter.add(new FieldInsnNode(Opcodes.PUTSTATIC, classNode.name, field.name, field.desc)); setter.add(new FieldInsnNode(Opcodes.PUTSTATIC, classNode.name, field.name, field.desc));
@ -130,7 +130,7 @@ public void visit(final String name, final Object value) {
} }
List<FieldInsnNode> putFieldNodes = Arrays.stream(initMethod.instructions.toArray()) List<FieldInsnNode> putFieldNodes = Arrays.stream(initMethod.instructions.toArray())
.filter(node -> node instanceof FieldInsnNode && node.getOpcode() == Opcodes.PUTFIELD).map(p -> (FieldInsnNode) p) .filter(node -> node instanceof FieldInsnNode && node.getOpcode() == Opcodes.PUTFIELD).map(p -> (FieldInsnNode) p)
.filter(node -> node.owner.equals(classNode.name) && node.name.equals(field.name) && node.desc.equals(field.desc)).collect(Collectors.toList()); .filter(node -> node.owner.equals(classNode.name) && node.name.equals(field.name) && node.desc.equals(field.desc)).toList();
InsnList setter = serializeValue(value); InsnList setter = serializeValue(value);
if (putFieldNodes.isEmpty()) { if (putFieldNodes.isEmpty()) {
setter.insert(new VarInsnNode(Opcodes.ALOAD, 0)); setter.insert(new VarInsnNode(Opcodes.ALOAD, 0));

View file

@ -3,10 +3,12 @@
import pro.gravit.launcher.events.request.AuthRequestEvent; import pro.gravit.launcher.events.request.AuthRequestEvent;
import java.io.IOException; import java.io.IOException;
import java.io.Serial;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public final class AuthException extends IOException { public final class AuthException extends IOException {
@Serial
private static final long serialVersionUID = -2586107832847245863L; private static final long serialVersionUID = -2586107832847245863L;

View file

@ -4,8 +4,6 @@
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.core.AuthCoreProvider; import pro.gravit.launchserver.auth.core.AuthCoreProvider;
import pro.gravit.launchserver.auth.core.MySQLCoreProvider;
import pro.gravit.launchserver.auth.core.PostgresSQLCoreProvider;
import pro.gravit.launchserver.auth.texture.TextureProvider; import pro.gravit.launchserver.auth.texture.TextureProvider;
import java.io.IOException; import java.io.IOException;
@ -23,7 +21,6 @@ public final class AuthProviderPair {
public transient Set<String> features; public transient Set<String> features;
public String displayName; public String displayName;
public boolean visible = true; public boolean visible = true;
private transient boolean warnOAuthShow = false;
public AuthProviderPair() { public AuthProviderPair() {
} }
@ -56,15 +53,6 @@ public static void getFeatures(Class<?> clazz, Set<String> list) {
} }
} }
public void internalShowOAuthWarnMessage() {
if (!warnOAuthShow) {
if (!(core instanceof MySQLCoreProvider) && !(core instanceof PostgresSQLCoreProvider)) { // MySQL and PostgreSQL upgraded later
logger.warn("AuthCoreProvider {} ({}) not supported OAuth. Legacy session system may be removed in next release", name, core.getClass().getName());
}
warnOAuthShow = true;
}
}
public final <T> T isSupport(Class<T> clazz) { public final <T> T isSupport(Class<T> clazz) {
if (core == null) return null; if (core == null) return null;
T result = null; T result = null;

View file

@ -29,7 +29,7 @@
import java.util.UUID; import java.util.UUID;
public abstract class AbstractSQLCoreProvider extends AuthCoreProvider { public abstract class AbstractSQLCoreProvider extends AuthCoreProvider {
public transient Logger logger = LogManager.getLogger(); public final transient Logger logger = LogManager.getLogger();
public int expireSeconds = 3600; public int expireSeconds = 3600;
public String uuidColumn; public String uuidColumn;
public String usernameColumn; public String usernameColumn;
@ -208,7 +208,7 @@ protected String makeUserCols() {
return String.format("%s, %s, %s, %s, %s", uuidColumn, usernameColumn, accessTokenColumn, serverIDColumn, passwordColumn); return String.format("%s, %s, %s, %s, %s", uuidColumn, usernameColumn, accessTokenColumn, serverIDColumn, passwordColumn);
} }
protected boolean updateAuth(User user, String accessToken) throws IOException { protected void updateAuth(User user, String accessToken) throws IOException {
try (Connection c = getSQLConfig().getConnection()) { try (Connection c = getSQLConfig().getConnection()) {
SQLUser SQLUser = (SQLUser) user; SQLUser SQLUser = (SQLUser) user;
SQLUser.accessToken = accessToken; SQLUser.accessToken = accessToken;
@ -216,7 +216,7 @@ protected boolean updateAuth(User user, String accessToken) throws IOException {
s.setString(1, accessToken); s.setString(1, accessToken);
s.setString(2, user.getUUID().toString()); s.setString(2, user.getUUID().toString());
s.setQueryTimeout(MySQLSourceConfig.TIMEOUT); s.setQueryTimeout(MySQLSourceConfig.TIMEOUT);
return s.executeUpdate() > 0; s.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
throw new IOException(e); throw new IOException(e);
} }
@ -238,7 +238,7 @@ protected boolean updateServerID(User user, String serverID) throws IOException
} }
@Override @Override
public void close() throws IOException { public void close() {
getSQLConfig().close(); getSQLConfig().close();
} }
@ -299,12 +299,12 @@ private List<String> queryRolesNames(String sql, String value) throws SQLExcepti
} }
public static class SQLUser implements User { public static class SQLUser implements User {
protected UUID uuid; protected final UUID uuid;
protected String username; protected final String username;
protected String accessToken; protected String accessToken;
protected String serverId; protected String serverId;
protected String password; protected final String password;
protected ClientPermissions permissions; protected final ClientPermissions permissions;
public SQLUser(UUID uuid, String username, String accessToken, String serverId, String password, ClientPermissions permissions) { public SQLUser(UUID uuid, String username, String accessToken, String serverId, String password, ClientPermissions permissions) {
this.uuid = uuid; this.uuid = uuid;

View file

@ -140,7 +140,7 @@ public void invoke(String... args) throws Exception {
if (instance != null) { if (instance != null) {
map.put("getallusers", new SubCommand("(limit)", "print all users information") { map.put("getallusers", new SubCommand("(limit)", "print all users information") {
@Override @Override
public void invoke(String... args) throws Exception { public void invoke(String... args) {
int max = Integer.MAX_VALUE; int max = Integer.MAX_VALUE;
if (args.length > 0) max = Integer.parseInt(args[0]); if (args.length > 0) max = Integer.parseInt(args[0]);
Iterable<User> users = instance.getAllUsers(); Iterable<User> users = instance.getAllUsers();
@ -316,7 +316,7 @@ public <T> T isSupport(Class<T> clazz) {
} }
@Override @Override
public abstract void close() throws IOException; public abstract void close();
public static class PasswordVerifyReport { public static class PasswordVerifyReport {
public static final PasswordVerifyReport REQUIRED_2FA = new PasswordVerifyReport(-1); public static final PasswordVerifyReport REQUIRED_2FA = new PasswordVerifyReport(-1);

View file

@ -1,6 +1,5 @@
package pro.gravit.launchserver.auth.core; package pro.gravit.launchserver.auth.core;
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.ClientPermissions; import pro.gravit.launcher.ClientPermissions;
@ -318,7 +317,7 @@ public void init(LaunchServer server) {
} }
@Override @Override
public void close() throws IOException { public void close() {
} }
@ -525,10 +524,6 @@ public class HttpUser implements User, UserSupportTextures, UserSupportPropertie
private String serverId; private String serverId;
private String accessToken; private String accessToken;
private ClientPermissions permissions; private ClientPermissions permissions;
@Deprecated
private Texture skin;
@Deprecated
private Texture cloak;
private Map<String, Texture> assets; private Map<String, Texture> assets;
private Map<String, String> properties; private Map<String, String> properties;
private long hwidId; private long hwidId;
@ -552,8 +547,6 @@ public HttpUser(String username, UUID uuid, String serverId, String accessToken,
this.serverId = serverId; this.serverId = serverId;
this.accessToken = accessToken; this.accessToken = accessToken;
this.permissions = permissions; this.permissions = permissions;
this.skin = skin;
this.cloak = cloak;
this.hwidId = hwidId; this.hwidId = hwidId;
} }
@ -563,8 +556,6 @@ public HttpUser(String username, UUID uuid, String serverId, String accessToken,
this.serverId = serverId; this.serverId = serverId;
this.accessToken = accessToken; this.accessToken = accessToken;
this.permissions = permissions; this.permissions = permissions;
this.skin = skin;
this.cloak = cloak;
this.properties = properties; this.properties = properties;
this.hwidId = hwidId; this.hwidId = hwidId;
} }
@ -607,30 +598,17 @@ public ClientPermissions getPermissions() {
@Override @Override
public Texture getSkinTexture() { public Texture getSkinTexture() {
if (assets == null) {
return skin;
}
return assets.get("SKIN"); return assets.get("SKIN");
} }
@Override @Override
public Texture getCloakTexture() { public Texture getCloakTexture() {
if (assets == null) {
return cloak;
}
return assets.get("CAPE"); return assets.get("CAPE");
} }
public Map<String, Texture> getAssets() { public Map<String, Texture> getAssets() {
if (assets == null) { if (assets == null) {
Map<String, Texture> map = new HashMap<>(); return new HashMap<>();
if (skin != null) {
map.put("SKIN", skin);
}
if (cloak != null) {
map.put("CAPE", cloak);
}
return map;
} }
return assets; return assets;
} }

View file

@ -53,7 +53,7 @@ public User getUserByUUID(UUID uuid) {
} }
@Override @Override
public UserSession getUserSessionByOAuthAccessToken(String accessToken) throws OAuthAccessTokenExpired { public UserSession getUserSessionByOAuthAccessToken(String accessToken) {
synchronized (memory) { synchronized (memory) {
for (MemoryUser u : memory) { for (MemoryUser u : memory) {
if (u.accessToken.equals(accessToken)) { if (u.accessToken.equals(accessToken)) {
@ -95,14 +95,14 @@ public AuthManager.AuthReport authorize(String login, AuthResponse.AuthContext c
} }
@Override @Override
protected boolean updateServerID(User user, String serverID) throws IOException { protected boolean updateServerID(User user, String serverID) {
MemoryUser memoryUser = (MemoryUser) user; MemoryUser memoryUser = (MemoryUser) user;
memoryUser.serverId = serverID; memoryUser.serverId = serverID;
return true; return true;
} }
@Override @Override
public User checkServer(Client client, String username, String serverID) throws IOException { public User checkServer(Client client, String username, String serverID) {
synchronized (memory) { synchronized (memory) {
for (MemoryUser u : memory) { for (MemoryUser u : memory) {
if (u.username.equals(username)) { if (u.username.equals(username)) {
@ -116,7 +116,7 @@ public User checkServer(Client client, String username, String serverID) throws
} }
@Override @Override
public boolean joinServer(Client client, String username, String accessToken, String serverID) throws IOException { public boolean joinServer(Client client, String username, String accessToken, String serverID) {
return true; return true;
} }
@ -126,16 +126,16 @@ public void init(LaunchServer server) {
} }
@Override @Override
public void close() throws IOException { public void close() {
} }
public static class MemoryUser implements User { public static class MemoryUser implements User {
private String username; private final String username;
private UUID uuid; private final UUID uuid;
private String serverId; private String serverId;
private String accessToken; private final String accessToken;
private ClientPermissions permissions; private final ClientPermissions permissions;
public MemoryUser(String username) { public MemoryUser(String username) {
this.username = username; this.username = username;
@ -188,9 +188,9 @@ public int hashCode() {
} }
public static class MemoryUserSession implements UserSession { public static class MemoryUserSession implements UserSession {
private String id; private final String id;
private MemoryUser user; private final MemoryUser user;
private long expireIn; private final long expireIn;
public MemoryUserSession(MemoryUser user) { public MemoryUserSession(MemoryUser user) {
this.id = SecurityHelper.randomStringToken(); this.id = SecurityHelper.randomStringToken();

View file

@ -17,7 +17,7 @@
public class MergeAuthCoreProvider extends AuthCoreProvider { public class MergeAuthCoreProvider extends AuthCoreProvider {
private transient final Logger logger = LogManager.getLogger(MergeAuthCoreProvider.class); private transient final Logger logger = LogManager.getLogger(MergeAuthCoreProvider.class);
public List<String> list = new ArrayList<>(); public List<String> list = new ArrayList<>();
private transient List<AuthCoreProvider> providers = new ArrayList<>(); private final transient List<AuthCoreProvider> providers = new ArrayList<>();
@Override @Override
public User getUserByUsername(String username) { public User getUserByUsername(String username) {
for(var core : providers) { for(var core : providers) {
@ -67,7 +67,7 @@ public User checkServer(Client client, String username, String serverID) throws
} }
@Override @Override
public boolean joinServer(Client client, String username, String accessToken, String serverID) throws IOException { public boolean joinServer(Client client, String username, String accessToken, String serverID) {
return false; // Authorization not supported return false; // Authorization not supported
} }
@ -84,7 +84,7 @@ public void init(LaunchServer server) {
} }
@Override @Override
public void close() throws IOException { public void close() {
// Providers closed automatically // Providers closed automatically
} }
} }

View file

@ -21,7 +21,7 @@ public User getUserByUUID(UUID uuid) {
} }
@Override @Override
public UserSession getUserSessionByOAuthAccessToken(String accessToken) throws OAuthAccessTokenExpired { public UserSession getUserSessionByOAuthAccessToken(String accessToken) {
return null; return null;
} }
@ -46,12 +46,12 @@ public void init(LaunchServer server) {
} }
@Override @Override
protected boolean updateServerID(User user, String serverID) throws IOException { protected boolean updateServerID(User user, String serverID) {
return false; return false;
} }
@Override @Override
public void close() throws IOException { public void close() {
} }
} }

View file

@ -4,7 +4,7 @@
import pro.gravit.launchserver.auth.core.UserSession; import pro.gravit.launchserver.auth.core.UserSession;
public interface AuthSupportExit extends AuthSupport { public interface AuthSupportExit extends AuthSupport {
boolean deleteSession(UserSession session); void deleteSession(UserSession session);
boolean exitUser(User user); void exitUser(User user);
} }

View file

@ -14,7 +14,7 @@
import java.time.Duration; import java.time.Duration;
public class JsonPasswordVerifier extends PasswordVerifier { public class JsonPasswordVerifier extends PasswordVerifier {
private static transient final Logger logger = LogManager.getLogger(); private static final Logger logger = LogManager.getLogger();
private transient final HttpClient client = HttpClient.newBuilder().build(); private transient final HttpClient client = HttpClient.newBuilder().build();
public String url; public String url;
public String bearerToken; public String bearerToken;

View file

@ -15,7 +15,6 @@
import pro.gravit.launchserver.auth.protect.interfaces.JoinServerProtectHandler; import pro.gravit.launchserver.auth.protect.interfaces.JoinServerProtectHandler;
import pro.gravit.launchserver.auth.protect.interfaces.SecureProtectHandler; import pro.gravit.launchserver.auth.protect.interfaces.SecureProtectHandler;
import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.response.auth.AuthResponse;
import pro.gravit.launchserver.socket.response.auth.RestoreResponse; import pro.gravit.launchserver.socket.response.auth.RestoreResponse;
import pro.gravit.launchserver.socket.response.secure.HardwareReportResponse; import pro.gravit.launchserver.socket.response.secure.HardwareReportResponse;
@ -27,16 +26,6 @@ public class AdvancedProtectHandler extends StdProtectHandler implements SecureP
public boolean enableHardwareFeature; public boolean enableHardwareFeature;
private transient LaunchServer server; private transient LaunchServer server;
@Override
public boolean allowGetAccessToken(AuthResponse.AuthContext context) {
return (context.authType == AuthResponse.ConnectTypes.CLIENT) && context.client.checkSign;
}
@Override
public void checkLaunchServerLicense() {
}
@Override @Override
public GetSecureLevelInfoRequestEvent onGetSecureLevelInfo(GetSecureLevelInfoRequestEvent event) { public GetSecureLevelInfoRequestEvent onGetSecureLevelInfo(GetSecureLevelInfoRequestEvent event) {
return event; return event;
@ -73,11 +62,9 @@ public void onHardwareReport(HardwareReportResponse response, Client client) {
} }
client.trustLevel.hardwareInfo = hardware.getHardwareInfo(); client.trustLevel.hardwareInfo = hardware.getHardwareInfo();
response.sendResult(new HardwareReportRequestEvent(createHardwareToken(client.username, hardware))); response.sendResult(new HardwareReportRequestEvent(createHardwareToken(client.username, hardware)));
return;
} else { } else {
logger.error("AuthCoreProvider not supported hardware"); logger.error("AuthCoreProvider not supported hardware");
response.sendError("AuthCoreProvider not supported hardware"); response.sendError("AuthCoreProvider not supported hardware");
return;
} }
} }
} }
@ -113,10 +100,6 @@ public void init(LaunchServer server) {
this.server = server; this.server = server;
} }
@Override
public void close() {
}
public String createHardwareToken(String username, UserHardware hardware) { public String createHardwareToken(String username, UserHardware hardware) {
return Jwts.builder() return Jwts.builder()
.setIssuer("LaunchServer") .setIssuer("LaunchServer")
@ -138,12 +121,10 @@ public String createPublicKeyToken(String username, byte[] publicKey) {
} }
public static class HardwareInfoTokenVerifier implements RestoreResponse.ExtendedTokenProvider { public static class HardwareInfoTokenVerifier implements RestoreResponse.ExtendedTokenProvider {
private transient final LaunchServer server;
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
private final JwtParser parser; private final JwtParser parser;
public HardwareInfoTokenVerifier(LaunchServer server) { public HardwareInfoTokenVerifier(LaunchServer server) {
this.server = server;
this.parser = Jwts.parserBuilder() this.parser = Jwts.parserBuilder()
.requireIssuer("LaunchServer") .requireIssuer("LaunchServer")
.setSigningKey(server.keyAgreementManager.ecdsaPublicKey) .setSigningKey(server.keyAgreementManager.ecdsaPublicKey)
@ -172,12 +153,10 @@ public boolean accept(Client client, AuthProviderPair pair, String extendedToken
} }
public static class PublicKeyTokenVerifier implements RestoreResponse.ExtendedTokenProvider { public static class PublicKeyTokenVerifier implements RestoreResponse.ExtendedTokenProvider {
private transient final LaunchServer server;
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
private final JwtParser parser; private final JwtParser parser;
public PublicKeyTokenVerifier(LaunchServer server) { public PublicKeyTokenVerifier(LaunchServer server) {
this.server = server;
this.parser = Jwts.parserBuilder() this.parser = Jwts.parserBuilder()
.requireIssuer("LaunchServer") .requireIssuer("LaunchServer")
.setSigningKey(server.keyAgreementManager.ecdsaPublicKey) .setSigningKey(server.keyAgreementManager.ecdsaPublicKey)

View file

@ -9,8 +9,4 @@ public boolean allowGetAccessToken(AuthResponse.AuthContext context) {
return true; return true;
} }
@Override
public void checkLaunchServerLicense() {
// None
}
} }

View file

@ -20,8 +20,6 @@ public static void registerHandlers() {
public abstract boolean allowGetAccessToken(AuthResponse.AuthContext context); public abstract boolean allowGetAccessToken(AuthResponse.AuthContext context);
public abstract void checkLaunchServerLicense(); //Выдает SecurityException при ошибке проверки лицензии
public void init(LaunchServer server) { public void init(LaunchServer server) {
} }

View file

@ -20,11 +20,6 @@ public boolean allowGetAccessToken(AuthResponse.AuthContext context) {
return (context.authType == AuthResponse.ConnectTypes.CLIENT) && context.client.checkSign; return (context.authType == AuthResponse.ConnectTypes.CLIENT) && context.client.checkSign;
} }
@Override
public void checkLaunchServerLicense() {
}
@Override @Override
public void init(LaunchServer server) { public void init(LaunchServer server) {
if (profileWhitelist != null && profileWhitelist.size() > 0) { if (profileWhitelist != null && profileWhitelist.size() > 0) {
@ -59,7 +54,6 @@ private boolean isWhitelisted(String property, ClientProfile profile, Client cli
} }
} }
List<String> allowedUsername = profileWhitelist.get(profile.getTitle()); List<String> allowedUsername = profileWhitelist.get(profile.getTitle());
if (allowedUsername != null && allowedUsername.contains(client.username)) return true; return allowedUsername != null && allowedUsername.contains(client.username);
return false;
} }
} }

View file

@ -15,24 +15,24 @@
import java.util.UUID; import java.util.UUID;
public class JsonTextureProvider extends TextureProvider { public class JsonTextureProvider extends TextureProvider {
private transient static final Type MAP_TYPE = new TypeToken<Map<String, Texture>>() { private static final Type MAP_TYPE = new TypeToken<Map<String, Texture>>() {
}.getType(); }.getType();
private transient final Logger logger = LogManager.getLogger(); private transient final Logger logger = LogManager.getLogger();
public String url; public String url;
@Override @Override
public void close() throws IOException { public void close() {
//None //None
} }
@Override @Override
public Texture getCloakTexture(UUID uuid, String username, String client) throws IOException { public Texture getCloakTexture(UUID uuid, String username, String client) {
logger.warn("Ineffective get cloak texture for {}", username); logger.warn("Ineffective get cloak texture for {}", username);
return getAssets(uuid, username, client).get("CAPE"); return getAssets(uuid, username, client).get("CAPE");
} }
@Override @Override
public Texture getSkinTexture(UUID uuid, String username, String client) throws IOException { public Texture getSkinTexture(UUID uuid, String username, String client) {
logger.warn("Ineffective get skin texture for {}", username); logger.warn("Ineffective get skin texture for {}", username);
return getAssets(uuid, username, client).get("SKIN"); return getAssets(uuid, username, client).get("SKIN");
} }

View file

@ -4,12 +4,9 @@
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;

View file

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

View file

@ -10,7 +10,7 @@
import pro.gravit.launchserver.command.Command; import pro.gravit.launchserver.command.Command;
public class DebugCommand extends Command { public class DebugCommand extends Command {
private transient Logger logger = LogManager.getLogger(); private final transient Logger logger = LogManager.getLogger();
public DebugCommand(LaunchServer server) { public DebugCommand(LaunchServer server) {
super(server); super(server);

View file

@ -12,7 +12,6 @@
import pro.gravit.utils.command.basic.HelpCommand; import pro.gravit.utils.command.basic.HelpCommand;
public abstract class CommandHandler extends pro.gravit.utils.command.CommandHandler { public abstract class CommandHandler extends pro.gravit.utils.command.CommandHandler {
@SuppressWarnings("deprecation")
public static void registerCommands(pro.gravit.utils.command.CommandHandler handler, LaunchServer server) { public static void registerCommands(pro.gravit.utils.command.CommandHandler handler, LaunchServer server) {
BaseCommandCategory basic = new BaseCommandCategory(); BaseCommandCategory basic = new BaseCommandCategory();
// Register basic commands // Register basic commands

View file

@ -30,7 +30,7 @@
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class SecurityCheckCommand extends Command { public class SecurityCheckCommand extends Command {
private static transient final Logger logger = LogManager.getLogger(); private static final Logger logger = LogManager.getLogger();
public SecurityCheckCommand(LaunchServer server) { public SecurityCheckCommand(LaunchServer server) {
super(server); super(server);
@ -110,7 +110,7 @@ public void invoke(String... args) {
try { try {
KeyStore keyStore = SignHelper.getStore(new File(config.sign.keyStore).toPath(), config.sign.keyStorePass, config.sign.keyStoreType); KeyStore keyStore = SignHelper.getStore(new File(config.sign.keyStore).toPath(), config.sign.keyStorePass, config.sign.keyStoreType);
Certificate[] certChainPlain = keyStore.getCertificateChain(config.sign.keyAlias); Certificate[] certChainPlain = keyStore.getCertificateChain(config.sign.keyAlias);
List<X509Certificate> certChain = Arrays.stream(certChainPlain).map(e -> (X509Certificate) e).collect(Collectors.toList()); List<X509Certificate> certChain = Arrays.stream(certChainPlain).map(e -> (X509Certificate) e).toList();
X509Certificate cert = certChain.get(0); X509Certificate cert = certChain.get(0);
cert.checkValidity(); cert.checkValidity();
if (certChain.size() <= 1) { if (certChain.size() <= 1) {

View file

@ -41,7 +41,7 @@ public void invoke(String... args) throws Exception {
Optional<SignJarTask> task = server.launcherBinary.getTaskByClass(SignJarTask.class); Optional<SignJarTask> task = server.launcherBinary.getTaskByClass(SignJarTask.class);
if (task.isEmpty()) throw new IllegalStateException("SignJarTask not found"); if (task.isEmpty()) throw new IllegalStateException("SignJarTask not found");
task.get().sign(server.config.sign, target, tmpSign); task.get().sign(server.config.sign, target, tmpSign);
if (args.length <= 1) { if (args.length == 1) {
logger.info("Move temp jar {} to {}", tmpSign.toString(), target.toString()); logger.info("Move temp jar {} to {}", tmpSign.toString(), target.toString());
Files.deleteIfExists(target); Files.deleteIfExists(target);
Files.move(tmpSign, target); Files.move(tmpSign, target);

View file

@ -25,7 +25,7 @@ public void invoke(String... args) throws Exception {
}); });
this.childCommands.put("server", new SubCommand("[profileName] (authId)", "generate new server token") { this.childCommands.put("server", new SubCommand("[profileName] (authId)", "generate new server token") {
@Override @Override
public void invoke(String... args) throws Exception { public void invoke(String... args) {
AuthProviderPair pair = args.length > 1 ? server.config.getAuthProviderPair(args[1]) : server.config.getAuthProviderPair(); AuthProviderPair pair = args.length > 1 ? server.config.getAuthProviderPair(args[1]) : server.config.getAuthProviderPair();
ClientProfile profile = null; ClientProfile profile = null;
for (ClientProfile p : server.getProfiles()) { for (ClientProfile p : server.getProfiles()) {

View file

@ -28,7 +28,7 @@
import java.util.Map; import java.util.Map;
public class ProGuardComponent extends Component implements AutoCloseable, Reconfigurable { public class ProGuardComponent extends Component implements AutoCloseable, Reconfigurable {
private transient static final Logger logger = LogManager.getLogger(); private static final Logger logger = LogManager.getLogger();
public String modeAfter = "MainBuild"; public String modeAfter = "MainBuild";
public String dir = "proguard"; public String dir = "proguard";
public boolean enabled = true; public boolean enabled = true;
@ -79,7 +79,7 @@ public void init(LaunchServer launchServer) {
} }
@Override @Override
public void close() throws Exception { public void close() {
if (launchServer != null && buildTask != null) { if (launchServer != null && buildTask != null) {
launchServer.launcherBinary.tasks.remove(buildTask); launchServer.launcherBinary.tasks.remove(buildTask);
} }

View file

@ -48,7 +48,7 @@ public boolean hookJoin(JoinServerResponse response, Client client) throws HookE
} }
@Override @Override
public void close() throws Exception { public void close() {
this.server.authHookManager.preHook.unregisterHook(this::hookAuth); this.server.authHookManager.preHook.unregisterHook(this::hookAuth);
this.server.authHookManager.joinServerHook.unregisterHook(this::hookJoin); this.server.authHookManager.joinServerHook.unregisterHook(this::hookJoin);
} }
@ -82,14 +82,14 @@ public void invoke(String... args) throws Exception {
}); });
commands.put("disable", new SubCommand() { commands.put("disable", new SubCommand() {
@Override @Override
public void invoke(String... args) throws Exception { public void invoke(String... args) {
enabled = false; enabled = false;
logger.info("Whitelist disabled"); logger.info("Whitelist disabled");
} }
}); });
commands.put("enable", new SubCommand() { commands.put("enable", new SubCommand() {
@Override @Override
public void invoke(String... args) throws Exception { public void invoke(String... args) {
enabled = true; enabled = true;
logger.info("Whitelist enabled"); logger.info("Whitelist enabled");
} }

View file

@ -106,9 +106,8 @@ public static LaunchServerConfig getDefault(LaunchServer.LaunchServerEnv env) {
return newConfig; return newConfig;
} }
public LaunchServerConfig setLaunchServer(LaunchServer server) { public void setLaunchServer(LaunchServer server) {
this.server = server; this.server = server;
return this;
} }
public AuthProviderPair getAuthProviderPair(String name) { public AuthProviderPair getAuthProviderPair(String name) {
@ -187,7 +186,6 @@ public void init(LaunchServer.ReloadType type) {
if (protectHandler != null) { if (protectHandler != null) {
server.registerObject("protectHandler", protectHandler); server.registerObject("protectHandler", protectHandler);
protectHandler.init(server); protectHandler.init(server);
protectHandler.checkLaunchServerLicense();
} }
if (components != null) { if (components != null) {
components.forEach((k, v) -> server.registerObject("component.".concat(k), v)); components.forEach((k, v) -> server.registerObject("component.".concat(k), v));

View file

@ -22,7 +22,7 @@
import java.util.function.Function; import java.util.function.Function;
public final class HttpHelper { public final class HttpHelper {
private static transient final Logger logger = LogManager.getLogger(); private static final Logger logger = LogManager.getLogger();
private HttpHelper() { private HttpHelper() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
@ -37,7 +37,7 @@ public static <T, E> HttpOptional<T, E> send(HttpClient client, HttpRequest requ
} }
} }
public static <T, E> CompletableFuture<HttpOptional<T, E>> sendAsync(HttpClient client, HttpRequest request, HttpErrorHandler<T, E> handler) throws IOException { public static <T, E> CompletableFuture<HttpOptional<T, E>> sendAsync(HttpClient client, HttpRequest request, HttpErrorHandler<T, E> handler) {
return client.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()).thenApply(handler::apply); return client.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()).thenApply(handler::apply);
} }

View file

@ -7,11 +7,9 @@
import java.util.Map; import java.util.Map;
public class FeaturesManager { public class FeaturesManager {
private final transient LaunchServer server;
private final Map<String, String> map; private final Map<String, String> map;
public FeaturesManager(LaunchServer server) { public FeaturesManager(LaunchServer server) {
this.server = server;
map = new HashMap<>(); map = new HashMap<>();
addFeatureInfo("version", Version.getVersion().getVersionString()); addFeatureInfo("version", Version.getVersion().getVersionString());
addFeatureInfo("projectName", server.config.projectName); addFeatureInfo("projectName", server.config.projectName);
@ -25,8 +23,8 @@ public String getFeatureInfo(String name) {
return map.get(name); return map.get(name);
} }
public String addFeatureInfo(String name, String featureInfo) { public void addFeatureInfo(String name, String featureInfo) {
return map.put(name, featureInfo); map.put(name, featureInfo);
} }
public String removeFeatureInfo(String name) { public String removeFeatureInfo(String name) {

View file

@ -22,7 +22,6 @@ public class KeyAgreementManager {
public final RSAPublicKey rsaPublicKey; public final RSAPublicKey rsaPublicKey;
public final RSAPrivateKey rsaPrivateKey; public final RSAPrivateKey rsaPrivateKey;
public final String legacySalt; public final String legacySalt;
private transient final Logger logger = LogManager.getLogger();
public KeyAgreementManager(ECPublicKey ecdsaPublicKey, ECPrivateKey ecdsaPrivateKey, RSAPublicKey rsaPublicKey, RSAPrivateKey rsaPrivateKey, String legacySalt) { public KeyAgreementManager(ECPublicKey ecdsaPublicKey, ECPrivateKey ecdsaPrivateKey, RSAPublicKey rsaPublicKey, RSAPrivateKey rsaPrivateKey, String legacySalt) {
this.ecdsaPublicKey = ecdsaPublicKey; this.ecdsaPublicKey = ecdsaPublicKey;
@ -34,6 +33,7 @@ public KeyAgreementManager(ECPublicKey ecdsaPublicKey, ECPrivateKey ecdsaPrivate
public KeyAgreementManager(Path keyDirectory) throws IOException, InvalidKeySpecException { public KeyAgreementManager(Path keyDirectory) throws IOException, InvalidKeySpecException {
Path ecdsaPublicKeyPath = keyDirectory.resolve("ecdsa_id.pub"), ecdsaPrivateKeyPath = keyDirectory.resolve("ecdsa_id"); Path ecdsaPublicKeyPath = keyDirectory.resolve("ecdsa_id.pub"), ecdsaPrivateKeyPath = keyDirectory.resolve("ecdsa_id");
Logger logger = LogManager.getLogger();
if (IOHelper.isFile(ecdsaPublicKeyPath) && IOHelper.isFile(ecdsaPrivateKeyPath)) { if (IOHelper.isFile(ecdsaPublicKeyPath) && IOHelper.isFile(ecdsaPrivateKeyPath)) {
logger.info("Reading ECDSA keypair"); logger.info("Reading ECDSA keypair");
ecdsaPublicKey = SecurityHelper.toPublicECDSAKey(IOHelper.read(ecdsaPublicKeyPath)); ecdsaPublicKey = SecurityHelper.toPublicECDSAKey(IOHelper.read(ecdsaPublicKeyPath));

View file

@ -1,7 +1,6 @@
package pro.gravit.launchserver.socket; package pro.gravit.launchserver.socket;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup; import io.netty.channel.EventLoopGroup;
@ -34,11 +33,11 @@ public class LauncherNettyServer implements AutoCloseable {
public final EventLoopGroup workerGroup; public final EventLoopGroup workerGroup;
public final WebSocketService service; public final WebSocketService service;
public final BiHookSet<NettyConnectContext, SocketChannel> pipelineHook = new BiHookSet<>(); public final BiHookSet<NettyConnectContext, SocketChannel> pipelineHook = new BiHookSet<>();
private transient final Logger logger = LogManager.getLogger();
public LauncherNettyServer(LaunchServer server) { public LauncherNettyServer(LaunchServer server) {
LaunchServerConfig.NettyConfig config = server.config.netty; LaunchServerConfig.NettyConfig config = server.config.netty;
NettyObjectFactory.setUsingEpoll(config.performance.usingEpoll); NettyObjectFactory.setUsingEpoll(config.performance.usingEpoll);
Logger logger = LogManager.getLogger();
if (config.performance.usingEpoll) { if (config.performance.usingEpoll) {
logger.debug("Netty: Epoll enabled"); logger.debug("Netty: Epoll enabled");
} }
@ -74,8 +73,8 @@ public void initChannel(SocketChannel ch) {
}); });
} }
public ChannelFuture bind(InetSocketAddress address) { public void bind(InetSocketAddress address) {
return serverBootstrap.bind(address); serverBootstrap.bind(address);
} }
@Override @Override

View file

@ -56,7 +56,6 @@ public WebSocketService(ChannelGroup channels, LaunchServer server) {
this.gson = Launcher.gsonManager.gson; this.gson = Launcher.gsonManager.gson;
} }
@SuppressWarnings("deprecation")
public static void registerResponses() { public static void registerResponses() {
providers.register("auth", AuthResponse.class); providers.register("auth", AuthResponse.class);
providers.register("checkServer", CheckServerResponse.class); providers.register("checkServer", CheckServerResponse.class);

View file

@ -36,10 +36,9 @@ public NettyWebAPIHandler(NettyConnectContext context) {
this.context = context; this.context = context;
} }
public static SeverletPathPair addNewSeverlet(String path, SimpleSeverletHandler callback) { public static void addNewSeverlet(String path, SimpleSeverletHandler callback) {
SeverletPathPair pair = new SeverletPathPair("/webapi/".concat(path), callback); SeverletPathPair pair = new SeverletPathPair("/webapi/".concat(path), callback);
severletList.add(pair); severletList.add(pair);
return pair;
} }
public static SeverletPathPair addUnsafeSeverlet(String path, SimpleSeverletHandler callback) { public static SeverletPathPair addUnsafeSeverlet(String path, SimpleSeverletHandler callback) {
@ -53,7 +52,7 @@ public static void removeSeverlet(SeverletPathPair pair) {
} }
@Override @Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
boolean isNext = true; boolean isNext = true;
for (SeverletPathPair pair : severletList) { for (SeverletPathPair pair : severletList) {
if (msg.uri().startsWith(pair.key)) { if (msg.uri().startsWith(pair.key)) {
@ -75,7 +74,7 @@ protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) thro
@FunctionalInterface @FunctionalInterface
public interface SimpleSeverletHandler { public interface SimpleSeverletHandler {
void handle(ChannelHandlerContext ctx, FullHttpRequest msg, NettyConnectContext context) throws Exception; void handle(ChannelHandlerContext ctx, FullHttpRequest msg, NettyConnectContext context);
default Map<String, String> getParamsFromUri(String uri) { default Map<String, String> getParamsFromUri(String uri) {
int ind = uri.indexOf("?"); int ind = uri.indexOf("?");

View file

@ -11,7 +11,6 @@
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@SuppressWarnings("deprecation")
public class AdditionalDataResponse extends SimpleResponse { public class AdditionalDataResponse extends SimpleResponse {
public String username; public String username;
public UUID uuid; public UUID uuid;
@ -22,7 +21,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception { public void execute(ChannelHandlerContext ctx, Client client) {
if (!client.isAuth) { if (!client.isAuth) {
sendError("Access denied"); sendError("Access denied");
return; return;

View file

@ -28,7 +28,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client clientData) throws Exception { public void execute(ChannelHandlerContext ctx, Client clientData) {
try { try {
AuthRequestEvent result = new AuthRequestEvent(); AuthRequestEvent result = new AuthRequestEvent();
AuthProviderPair pair; AuthProviderPair pair;

View file

@ -6,11 +6,9 @@
import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.response.SimpleResponse; import pro.gravit.launchserver.socket.response.SimpleResponse;
import java.io.IOException;
public class CurrentUserResponse extends SimpleResponse { public class CurrentUserResponse extends SimpleResponse {
public static CurrentUserRequestEvent.UserInfo collectUserInfoFromClient(LaunchServer server, Client client) throws IOException { public static CurrentUserRequestEvent.UserInfo collectUserInfoFromClient(LaunchServer server, Client client) {
CurrentUserRequestEvent.UserInfo result = new CurrentUserRequestEvent.UserInfo(); CurrentUserRequestEvent.UserInfo result = new CurrentUserRequestEvent.UserInfo();
if (client.auth != null && client.isAuth && client.username != null) { if (client.auth != null && client.isAuth && client.username != null) {
result.playerProfile = server.authManager.getPlayerProfile(client); result.playerProfile = server.authManager.getPlayerProfile(client);

View file

@ -14,7 +14,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception { public void execute(ChannelHandlerContext ctx, Client client) {
if (!client.isAuth || client.type != AuthResponse.ConnectTypes.CLIENT) { if (!client.isAuth || client.type != AuthResponse.ConnectTypes.CLIENT) {
sendError("Permissions denied"); sendError("Permissions denied");
return; return;

View file

@ -18,7 +18,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception { public void execute(ChannelHandlerContext ctx, Client client) {
if (refreshToken == null) { if (refreshToken == null) {
sendError("Invalid request"); sendError("Invalid request");
return; return;

View file

@ -76,6 +76,10 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
return; return;
} }
User user = session.getUser(); User user = session.getUser();
if(user == null) {
sendError("Internal Auth error: UserSession is broken");
return;
}
client.coreObject = user; client.coreObject = user;
client.sessionObject = session; client.sessionObject = session;
server.authManager.internalAuth(client, client.type == null ? AuthResponse.ConnectTypes.API : client.type, pair, user.getUsername(), user.getUUID(), user.getPermissions(), true); server.authManager.internalAuth(client, client.type == null ? AuthResponse.ConnectTypes.API : client.type, pair, user.getUsername(), user.getUUID(), user.getPermissions(), true);

View file

@ -18,7 +18,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception { public void execute(ChannelHandlerContext ctx, Client client) {
sendError("Legacy session system removed"); sendError("Legacy session system removed");
} }
} }

View file

@ -12,7 +12,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception { public void execute(ChannelHandlerContext ctx, Client client) {
sendResult(new GetPublicKeyRequestEvent(server.keyAgreementManager.rsaPublicKey, server.keyAgreementManager.ecdsaPublicKey)); sendResult(new GetPublicKeyRequestEvent(server.keyAgreementManager.rsaPublicKey, server.keyAgreementManager.ecdsaPublicKey));
} }
} }

View file

@ -16,7 +16,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception { public void execute(ChannelHandlerContext ctx, Client client) {
BatchProfileByUsernameRequestEvent result = new BatchProfileByUsernameRequestEvent(); BatchProfileByUsernameRequestEvent result = new BatchProfileByUsernameRequestEvent();
if (list == null) { if (list == null) {
sendError("Invalid request"); sendError("Invalid request");

View file

@ -19,7 +19,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception { public void execute(ChannelHandlerContext ctx, Client client) {
AuthProviderPair pair; AuthProviderPair pair;
if (client.auth == null) { if (client.auth == null) {
pair = server.config.getAuthProviderPair(); pair = server.config.getAuthProviderPair();

View file

@ -17,7 +17,7 @@ public String getType() {
} }
@Override @Override
public void execute(ChannelHandlerContext ctx, Client client) throws Exception { public void execute(ChannelHandlerContext ctx, Client client) {
AuthProviderPair pair = client.auth; AuthProviderPair pair = client.auth;
if (pair == null) pair = server.config.getAuthProviderPair(); if (pair == null) pair = server.config.getAuthProviderPair();
PlayerProfile profile = server.authManager.getPlayerProfile(pair, username); PlayerProfile profile = server.authManager.getPlayerProfile(pair, username);

View file

@ -85,12 +85,10 @@ private boolean checkSecure(String hash, String salt) {
} }
public static class LauncherTokenVerifier implements RestoreResponse.ExtendedTokenProvider { public static class LauncherTokenVerifier implements RestoreResponse.ExtendedTokenProvider {
private final LaunchServer server;
private final JwtParser parser; private final JwtParser parser;
private final Logger logger = LogManager.getLogger(); private final Logger logger = LogManager.getLogger();
public LauncherTokenVerifier(LaunchServer server) { public LauncherTokenVerifier(LaunchServer server) {
this.server = server;
parser = Jwts.parserBuilder() parser = Jwts.parserBuilder()
.setSigningKey(server.keyAgreementManager.ecdsaPublicKey) .setSigningKey(server.keyAgreementManager.ecdsaPublicKey)
.requireIssuer("LaunchServer") .requireIssuer("LaunchServer")

View file

@ -21,7 +21,7 @@ public class ASMTransformersTest {
public static ASMClassLoader classLoader; public static ASMClassLoader classLoader;
@BeforeAll @BeforeAll
public static void prepare() throws Throwable { public static void prepare() {
classLoader = new ASMClassLoader(ASMTransformersTest.class.getClassLoader()); classLoader = new ASMClassLoader(ASMTransformersTest.class.getClassLoader());
} }

View file

@ -2,6 +2,7 @@
import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
import pro.gravit.launcher.Launcher; import pro.gravit.launcher.Launcher;
import pro.gravit.launchserver.config.LaunchServerConfig; import pro.gravit.launchserver.config.LaunchServerConfig;
@ -45,4 +46,9 @@ public static void prepare() throws Throwable {
.setCommandHandler(new StdCommandHandler(false)); .setCommandHandler(new StdCommandHandler(false));
launchServer = builder.build(); launchServer = builder.build();
} }
@Test
public void test() {
}
} }

View file

@ -4,8 +4,6 @@
import pro.gravit.launchserver.config.LaunchServerConfig; import pro.gravit.launchserver.config.LaunchServerConfig;
import pro.gravit.launchserver.config.LaunchServerRuntimeConfig; import pro.gravit.launchserver.config.LaunchServerRuntimeConfig;
import java.io.IOException;
public class TestLaunchServerConfigManager implements LaunchServer.LaunchServerConfigManager { public class TestLaunchServerConfigManager implements LaunchServer.LaunchServerConfigManager {
public LaunchServerConfig config; public LaunchServerConfig config;
public LaunchServerRuntimeConfig runtimeConfig; public LaunchServerRuntimeConfig runtimeConfig;
@ -17,22 +15,22 @@ public TestLaunchServerConfigManager() {
} }
@Override @Override
public LaunchServerConfig readConfig() throws IOException { public LaunchServerConfig readConfig() {
return config; return config;
} }
@Override @Override
public LaunchServerRuntimeConfig readRuntimeConfig() throws IOException { public LaunchServerRuntimeConfig readRuntimeConfig() {
return runtimeConfig; return runtimeConfig;
} }
@Override @Override
public void writeConfig(LaunchServerConfig config) throws IOException { public void writeConfig(LaunchServerConfig config) {
} }
@Override @Override
public void writeRuntimeConfig(LaunchServerRuntimeConfig config) throws IOException { public void writeRuntimeConfig(LaunchServerRuntimeConfig config) {
} }
} }

View file

@ -29,12 +29,12 @@
"Multi-Release": "true") "Multi-Release": "true")
} }
task sourcesJar(type: Jar) { tasks.register('sourcesJar', Jar) {
from sourceSets.main.allJava from sourceSets.main.allJava
archiveClassifier.set('sources') archiveClassifier.set('sources')
} }
task javadocJar(type: Jar) { tasks.register('javadocJar', Jar) {
from javadoc from javadoc
archiveClassifier.set('javadoc') archiveClassifier.set('javadoc')
} }
@ -53,14 +53,14 @@ pack project(':LauncherAPI')
pack group: 'io.netty', name: 'netty-codec-http', version: rootProject['verNetty'] pack group: 'io.netty', name: 'netty-codec-http', version: rootProject['verNetty']
} }
task genRuntimeJS(type: Zip) { tasks.register('genRuntimeJS', Zip) {
duplicatesStrategy = 'EXCLUDE' duplicatesStrategy = 'EXCLUDE'
archiveFileName = "runtime.zip" archiveFileName = "runtime.zip"
destinationDirectory = file("${buildDir}/tmp") destinationDirectory = file("${buildDir}/tmp")
from "runtime/" from "runtime/"
} }
task dumpLibs(type: Copy) { tasks.register('dumpLibs', Copy) {
duplicatesStrategy = 'EXCLUDE' duplicatesStrategy = 'EXCLUDE'
into "$buildDir/libs/libraries" into "$buildDir/libs/libraries"
from configurations.bundle from configurations.bundle

View file

@ -83,8 +83,6 @@ public static void main(String[] arguments) throws IOException, InterruptedExcep
} }
context.executePath = IOHelper.resolveJavaBin(context.javaVersion.jvmDir); context.executePath = IOHelper.resolveJavaBin(context.javaVersion.jvmDir);
//List<String> args = new LinkedList<>();
//args.add(javaBin.toString());
String pathLauncher = IOHelper.getCodeSource(LauncherEngine.class).toString(); String pathLauncher = IOHelper.getCodeSource(LauncherEngine.class).toString();
context.mainClass = LauncherEngine.class.getName(); context.mainClass = LauncherEngine.class.getName();
context.memoryLimit = launcherMemoryLimit; context.memoryLimit = launcherMemoryLimit;

View file

@ -130,8 +130,6 @@ public static void main(String... args) throws Throwable {
} }
long endTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis();
LogHelper.debug("Launcher started in %dms", endTime - startTime); LogHelper.debug("Launcher started in %dms", endTime - startTime);
//Request.service.close();
//FunctionalBridge.close();
LauncherEngine.exitLauncher(0); LauncherEngine.exitLauncher(0);
} }

View file

@ -12,7 +12,7 @@ public class ClientClassLoader extends URLClassLoader {
private static final ClassLoader SYSTEM_CLASS_LOADER = ClassLoader.getSystemClassLoader(); private static final ClassLoader SYSTEM_CLASS_LOADER = ClassLoader.getSystemClassLoader();
public String nativePath; public String nativePath;
private List<String> packages = new ArrayList<>(); private final List<String> packages = new ArrayList<>();
/** /**
* Constructs a new URLClassLoader for the specified URLs using the * Constructs a new URLClassLoader for the specified URLs using the
@ -32,7 +32,6 @@ public class ClientClassLoader extends URLClassLoader {
* {@code checkCreateClassLoader} method doesn't allow * {@code checkCreateClassLoader} method doesn't allow
* creation of a class loader. * creation of a class loader.
* @throws NullPointerException if {@code urls} is {@code null}. * @throws NullPointerException if {@code urls} is {@code null}.
* @see SecurityManager#checkCreateClassLoader
*/ */
public ClientClassLoader(URL[] urls) { public ClientClassLoader(URL[] urls) {
super(urls); super(urls);
@ -59,7 +58,6 @@ public ClientClassLoader(URL[] urls) {
* {@code checkCreateClassLoader} method doesn't allow * {@code checkCreateClassLoader} method doesn't allow
* creation of a class loader. * creation of a class loader.
* @throws NullPointerException if {@code urls} is {@code null}. * @throws NullPointerException if {@code urls} is {@code null}.
* @see SecurityManager#checkCreateClassLoader
*/ */
public ClientClassLoader(URL[] urls, ClassLoader parent) { public ClientClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent); super(urls, parent);

View file

@ -186,20 +186,10 @@ public void start(boolean pipeOutput) throws IOException, InterruptedException {
} }
private void applyJava9Params(List<String> processArgs) { private void applyJava9Params(List<String> processArgs) {
/*jvmModulesPaths.add(javaVersion.jvmDir); // TODO: fix runtime in client
jvmModulesPaths.add(javaVersion.jvmDir.resolve("jre"));
Path openjfxPath = JavaHelper.tryGetOpenJFXPath(javaVersion.jvmDir);
if (openjfxPath != null) {
jvmModulesPaths.add(openjfxPath);
}*/ // TODO: fix runtime in client
StringBuilder modulesPath = new StringBuilder(); StringBuilder modulesPath = new StringBuilder();
StringBuilder modulesAdd = new StringBuilder(); StringBuilder modulesAdd = new StringBuilder();
for (String moduleName : jvmModules) { for (String moduleName : jvmModules) {
/*boolean success = JavaHelper.tryAddModule(jvmModulesPaths, moduleName, modulesPath);
if (success) {
if (modulesAdd.length() > 0) modulesAdd.append(",");
modulesAdd.append(moduleName);
}*/
if (modulesAdd.length() > 0) modulesAdd.append(","); if (modulesAdd.length() > 0) modulesAdd.append(",");
modulesAdd.append(moduleName); modulesAdd.append(moduleName);
} }

View file

@ -24,7 +24,7 @@ public String getUsageDescription() {
} }
@Override @Override
public void invoke(String... args) throws Exception { public void invoke(String... args) {
LogHelper.info("PublicKey: %s", Base64.getEncoder().encodeToString(engine.getClientPublicKey().getEncoded())); LogHelper.info("PublicKey: %s", Base64.getEncoder().encodeToString(engine.getClientPublicKey().getEncoded()));
} }
} }

View file

@ -23,7 +23,7 @@ public String getUsageDescription() {
} }
@Override @Override
public void invoke(String... args) throws Exception { public void invoke(String... args) {
for (LauncherModule module : LauncherEngine.modulesManager.getModules()) { for (LauncherModule module : LauncherEngine.modulesManager.getModules()) {
LauncherModuleInfo info = module.getModuleInfo(); LauncherModuleInfo info = module.getModuleInfo();
LauncherTrustManager.CheckClassResult checkStatus = module.getCheckResult(); LauncherTrustManager.CheckClassResult checkStatus = module.getCheckResult();

View file

@ -16,7 +16,7 @@ public String getUsageDescription() {
} }
@Override @Override
public void invoke(String... args) throws Exception { public void invoke(String... args) {
LogHelper.info("Your Hardware ID:"); LogHelper.info("Your Hardware ID:");
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
long currentTime; long currentTime;

View file

@ -4,12 +4,12 @@
public class NoRuntimeProvider implements RuntimeProvider { public class NoRuntimeProvider implements RuntimeProvider {
@Override @Override
public void run(String[] args) throws Exception { public void run(String[] args) {
JOptionPane.showMessageDialog(null, "GUI часть лаунчера не найдена.\nС 5.1.0 вам необходимо самостоятельно установить модуль, отвечающий за GUI. Рантайм на JS более не поддерживается"); JOptionPane.showMessageDialog(null, "GUI часть лаунчера не найдена.\nС 5.1.0 вам необходимо самостоятельно установить модуль, отвечающий за GUI. Рантайм на JS более не поддерживается");
} }
@Override @Override
public void preLoad() throws Exception { public void preLoad() {
} }

View file

@ -1,9 +1,9 @@
package pro.gravit.launcher.gui; package pro.gravit.launcher.gui;
public interface RuntimeProvider { public interface RuntimeProvider {
void run(String[] args) throws Exception; void run(String[] args);
void preLoad() throws Exception; void preLoad();
void init(boolean clientInstance); void init(boolean clientInstance);
} }

View file

@ -115,10 +115,6 @@ private final class RegisterFileVisitor extends SimpleFileVisitor<Path> {
@Override @Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
FileVisitResult result = super.preVisitDirectory(dir, attrs); FileVisitResult result = super.preVisitDirectory(dir, attrs);
if (DirWatcher.this.dir.equals(dir)) {
dir.register(service, KINDS);
return result;
}
// Maybe it's unnecessary to go deeper // Maybe it's unnecessary to go deeper
//if (matcher != null && !matcher.shouldVerify(path)) { //if (matcher != null && !matcher.shouldVerify(path)) {

View file

@ -17,7 +17,6 @@ public static void initFunc() {
} }
public static void haltA(int code) { public static void haltA(int code) {
Throwable[] th = new Throwable[3];
NativeJVMHalt halt = new NativeJVMHalt(code); NativeJVMHalt halt = new NativeJVMHalt(code);
try { try {
LogHelper.dev("Try invoke Shutdown.exit"); LogHelper.dev("Try invoke Shutdown.exit");
@ -26,7 +25,6 @@ public static void haltA(int code) {
exitMethod.setAccessible(true); exitMethod.setAccessible(true);
exitMethod.invoke(null, code); exitMethod.invoke(null, code);
} catch (Throwable e) { } catch (Throwable e) {
th[1] = e;
if (LogHelper.isDevEnabled()) { if (LogHelper.isDevEnabled()) {
LogHelper.error(e); LogHelper.error(e);
} }

View file

@ -37,12 +37,12 @@ java11Implementation files(sourceSets.main.output.classesDirs) { builtBy compile
targetCompatibility = 11 targetCompatibility = 11
} }
task sourcesJar(type: Jar) { tasks.register('sourcesJar', Jar) {
from sourceSets.main.allJava from sourceSets.main.allJava
archiveClassifier.set('sources') archiveClassifier.set('sources')
} }
task javadocJar(type: Jar) { tasks.register('javadocJar', Jar) {
from javadoc from javadoc
archiveClassifier.set('javadoc') archiveClassifier.set('javadoc')
} }

View file

@ -31,9 +31,8 @@ public InitStatus getInitStatus() {
return initStatus; return initStatus;
} }
public LauncherModule setInitStatus(InitStatus initStatus) { public void setInitStatus(InitStatus initStatus) {
this.initStatus = initStatus; this.initStatus = initStatus;
return this;
} }
/** /**
@ -71,11 +70,10 @@ public final void setCheckResult(LauncherTrustManager.CheckClassResult result) {
this.checkResult = result; this.checkResult = result;
} }
protected final LauncherModule requireModule(String name, Version minVersion) { protected final void requireModule(String name, Version minVersion) {
if (context == null) throw new IllegalStateException("requireModule must be used in init() phase"); if (context == null) throw new IllegalStateException("requireModule must be used in init() phase");
LauncherModule module = context.getModulesManager().getModule(name); LauncherModule module = context.getModulesManager().getModule(name);
requireModule(module, minVersion, name); requireModule(module, minVersion, name);
return module;
} }
protected final <T extends LauncherModule> T requireModule(Class<? extends T> clazz, Version minVersion) { protected final <T extends LauncherModule> T requireModule(Class<? extends T> clazz, Version minVersion) {
@ -107,13 +105,12 @@ public void preInitAction() {
//NOP //NOP
} }
public final LauncherModule preInit() { public final void preInit() {
if (!initStatus.equals(InitStatus.PRE_INIT_WAIT)) if (!initStatus.equals(InitStatus.PRE_INIT_WAIT))
throw new IllegalStateException("PreInit not allowed in current state"); throw new IllegalStateException("PreInit not allowed in current state");
initStatus = InitStatus.PRE_INIT; initStatus = InitStatus.PRE_INIT;
preInitAction(); preInitAction();
initStatus = InitStatus.INIT_WAIT; initStatus = InitStatus.INIT_WAIT;
return this;
} }
/** /**
@ -225,9 +222,8 @@ public boolean isCancel() {
return cancel; return cancel;
} }
public Event cancel() { public void cancel() {
this.cancel = true; this.cancel = true;
return this;
} }
} }
} }

View file

@ -8,7 +8,6 @@
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.VerifyHelper; import pro.gravit.utils.helper.VerifyHelper;
import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.*; import java.util.*;
@ -510,7 +509,7 @@ public enum CompatibilityFlags {
@FunctionalInterface @FunctionalInterface
public interface pushOptionalClassPathCallback { public interface pushOptionalClassPathCallback {
void run(String[] opt) throws IOException; void run(String[] opt);
} }
public static class ServerProfile { public static class ServerProfile {

View file

@ -35,9 +35,8 @@ public class ClientProfileBuilder {
private String info; private String info;
private String mainClass; private String mainClass;
public ClientProfileBuilder setUpdate(List<String> update) { public void setUpdate(List<String> update) {
this.update = update; this.update = update;
return this;
} }
public ClientProfileBuilder setUpdateExclusions(List<String> updateExclusions) { public ClientProfileBuilder setUpdateExclusions(List<String> updateExclusions) {
@ -50,34 +49,28 @@ public ClientProfileBuilder setUpdateShared(List<String> updateShared) {
return this; return this;
} }
public ClientProfileBuilder setUpdateVerify(List<String> updateVerify) { public void setUpdateVerify(List<String> updateVerify) {
this.updateVerify = updateVerify; this.updateVerify = updateVerify;
return this;
} }
public ClientProfileBuilder setUpdateOptional(Set<OptionalFile> updateOptional) { public void setUpdateOptional(Set<OptionalFile> updateOptional) {
this.updateOptional = updateOptional; this.updateOptional = updateOptional;
return this;
} }
public ClientProfileBuilder setJvmArgs(List<String> jvmArgs) { public void setJvmArgs(List<String> jvmArgs) {
this.jvmArgs = jvmArgs; this.jvmArgs = jvmArgs;
return this;
} }
public ClientProfileBuilder setClassPath(List<String> classPath) { public void setClassPath(List<String> classPath) {
this.classPath = classPath; this.classPath = classPath;
return this;
} }
public ClientProfileBuilder setAltClassPath(List<String> altClassPath) { public void setAltClassPath(List<String> altClassPath) {
this.altClassPath = altClassPath; this.altClassPath = altClassPath;
return this;
} }
public ClientProfileBuilder setClientArgs(List<String> clientArgs) { public void setClientArgs(List<String> clientArgs) {
this.clientArgs = clientArgs; this.clientArgs = clientArgs;
return this;
} }
public ClientProfileBuilder setCompatClasses(List<String> compatClasses) { public ClientProfileBuilder setCompatClasses(List<String> compatClasses) {
@ -90,39 +83,32 @@ public ClientProfileBuilder setProperties(Map<String, String> properties) {
return this; return this;
} }
public ClientProfileBuilder setServers(List<ClientProfile.ServerProfile> servers) { public void setServers(List<ClientProfile.ServerProfile> servers) {
this.servers = servers; this.servers = servers;
return this;
} }
public ClientProfileBuilder setClassLoaderConfig(ClientProfile.ClassLoaderConfig classLoaderConfig) { public void setClassLoaderConfig(ClientProfile.ClassLoaderConfig classLoaderConfig) {
this.classLoaderConfig = classLoaderConfig; this.classLoaderConfig = classLoaderConfig;
return this;
} }
public ClientProfileBuilder setVersion(String version) { public void setVersion(String version) {
this.version = version; this.version = version;
return this;
} }
public ClientProfileBuilder setAssetIndex(String assetIndex) { public void setAssetIndex(String assetIndex) {
this.assetIndex = assetIndex; this.assetIndex = assetIndex;
return this;
} }
public ClientProfileBuilder setDir(String dir) { public void setDir(String dir) {
this.dir = dir; this.dir = dir;
return this;
} }
public ClientProfileBuilder setAssetDir(String assetDir) { public void setAssetDir(String assetDir) {
this.assetDir = assetDir; this.assetDir = assetDir;
return this;
} }
public ClientProfileBuilder setRecommendJavaVersion(int recommendJavaVersion) { public void setRecommendJavaVersion(int recommendJavaVersion) {
this.recommendJavaVersion = recommendJavaVersion; this.recommendJavaVersion = recommendJavaVersion;
return this;
} }
public ClientProfileBuilder setModulePath(List<String> modulePath) { public ClientProfileBuilder setModulePath(List<String> modulePath) {
@ -135,14 +121,12 @@ public ClientProfileBuilder setModules(List<String> modules) {
return this; return this;
} }
public ClientProfileBuilder setMinJavaVersion(int minJavaVersion) { public void setMinJavaVersion(int minJavaVersion) {
this.minJavaVersion = minJavaVersion; this.minJavaVersion = minJavaVersion;
return this;
} }
public ClientProfileBuilder setMaxJavaVersion(int maxJavaVersion) { public void setMaxJavaVersion(int maxJavaVersion) {
this.maxJavaVersion = maxJavaVersion; this.maxJavaVersion = maxJavaVersion;
return this;
} }
public ClientProfileBuilder setSettings(ClientProfile.ProfileDefaultSettings settings) { public ClientProfileBuilder setSettings(ClientProfile.ProfileDefaultSettings settings) {
@ -155,24 +139,20 @@ public ClientProfileBuilder setSortIndex(int sortIndex) {
return this; return this;
} }
public ClientProfileBuilder setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
return this;
} }
public ClientProfileBuilder setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
return this;
} }
public ClientProfileBuilder setInfo(String info) { public void setInfo(String info) {
this.info = info; this.info = info;
return this;
} }
public ClientProfileBuilder setMainClass(String mainClass) { public void setMainClass(String mainClass) {
this.mainClass = mainClass; this.mainClass = mainClass;
return this;
} }
public ClientProfileBuilder setFlags(List<ClientProfile.CompatibilityFlags> flags) { public ClientProfileBuilder setFlags(List<ClientProfile.CompatibilityFlags> flags) {

View file

@ -31,7 +31,6 @@ public boolean isTriggered(OptionalFile optional, OptionalTriggerContext context
JavaHelper.JavaVersion version = context.getJavaVersion(); JavaHelper.JavaVersion version = context.getJavaVersion();
if (version.version < minVersion) return false; if (version.version < minVersion) return false;
if (version.version > maxVersion) return false; if (version.version > maxVersion) return false;
if (requireJavaFX && !version.enabledJavaFX) return false; return !requireJavaFX || version.enabledJavaFX;
return true;
} }
} }

View file

@ -116,9 +116,9 @@ public static String getRefreshToken() {
return oauth == null ? null : oauth.refreshToken; return oauth == null ? null : oauth.refreshToken;
} }
public static RequestRestoreReport reconnect() throws Exception { public static void reconnect() throws Exception {
service.open(); service.open();
return restore(); restore();
} }
public static RequestRestoreReport restore() throws Exception { public static RequestRestoreReport restore() throws Exception {

View file

@ -29,7 +29,7 @@ default <T extends WebSocketEvent> T requestSync(Request<T> request) throws IOEx
boolean isClosed(); boolean isClosed();
@FunctionalInterface @FunctionalInterface
public interface EventHandler { interface EventHandler {
/** /**
* @param event processing event * @param event processing event
* @param <T> event type * @param <T> event type

View file

@ -126,9 +126,9 @@ public void openAsync(Runnable onConnect, Consumer<Throwable> onFail) {
}); });
} }
public ChannelFuture send(String text) { public void send(String text) {
LogHelper.dev("Send: %s", text); LogHelper.dev("Send: %s", text);
return ch.writeAndFlush(new TextWebSocketFrame(text), ch.voidPromise()); ch.writeAndFlush(new TextWebSocketFrame(text), ch.voidPromise());
} }
abstract void onMessage(String message); abstract void onMessage(String message);

View file

@ -114,33 +114,17 @@ public void registerResults() {
} }
public void waitIfNotConnected() { public void waitIfNotConnected() {
/*if(!isOpen() && !isClosed() && !isClosing())
{
LogHelper.warning("WebSocket not connected. Try wait onConnect object");
synchronized (onConnect)
{
try {
onConnect.wait(5000);
} catch (InterruptedException e) {
LogHelper.error(e);
}
}
}*/
} }
public void sendObject(Object obj) throws IOException { public void sendObject(Object obj) throws IOException {
waitIfNotConnected(); waitIfNotConnected();
if (ch == null || !ch.isActive()) reconnectCallback.onReconnect(); if (ch == null || !ch.isActive()) reconnectCallback.onReconnect();
//if(isClosed() && reconnectCallback != null)
// reconnectCallback.onReconnect();
send(gson.toJson(obj, WebSocketRequest.class)); send(gson.toJson(obj, WebSocketRequest.class));
} }
public void sendObject(Object obj, Type type) throws IOException { public void sendObject(Object obj, Type type) throws IOException {
waitIfNotConnected(); waitIfNotConnected();
if (ch == null || !ch.isActive()) reconnectCallback.onReconnect(); if (ch == null || !ch.isActive()) reconnectCallback.onReconnect();
//if(isClosed() && reconnectCallback != null)
// reconnectCallback.onReconnect();
send(gson.toJson(obj, type)); send(gson.toJson(obj, type));
} }

View file

@ -7,7 +7,6 @@
import pro.gravit.launcher.request.WebSocketEvent; import pro.gravit.launcher.request.WebSocketEvent;
import pro.gravit.utils.helper.LogHelper; import pro.gravit.utils.helper.LogHelper;
import java.io.IOException;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -19,7 +18,7 @@ public class OfflineRequestService implements RequestService {
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends WebSocketEvent> CompletableFuture<T> request(Request<T> request) throws IOException { public <T extends WebSocketEvent> CompletableFuture<T> request(Request<T> request) {
RequestProcessor<T, Request<T>> processor = (RequestProcessor<T, Request<T>>) processors.get(request.getClass()); RequestProcessor<T, Request<T>> processor = (RequestProcessor<T, Request<T>>) processors.get(request.getClass());
CompletableFuture<T> future = new CompletableFuture<>(); CompletableFuture<T> future = new CompletableFuture<>();
if (processor == null) { if (processor == null) {

View file

@ -27,7 +27,7 @@ public StdWebSocketService(String address) throws SSLException {
super(address); super(address);
} }
public static CompletableFuture<StdWebSocketService> initWebSockets(String address) throws Exception { public static CompletableFuture<StdWebSocketService> initWebSockets(String address) {
StdWebSocketService service; StdWebSocketService service;
try { try {
service = new StdWebSocketService(address); service = new StdWebSocketService(address);
@ -41,16 +41,12 @@ public static CompletableFuture<StdWebSocketService> initWebSockets(String addre
future.complete(service); future.complete(service);
JVMHelper.RUNTIME.addShutdownHook(new Thread(() -> { JVMHelper.RUNTIME.addShutdownHook(new Thread(() -> {
try { try {
//if(service.isOpen())
// service.closeBlocking();
service.close(); service.close();
} catch (InterruptedException e) { } catch (InterruptedException e) {
LogHelper.error(e); LogHelper.error(e);
} }
})); }));
}, (error) -> { }, (error) -> future.completeExceptionally(error));
future.completeExceptionally(error);
});
return future; return future;
} }
@ -74,7 +70,7 @@ public <T extends WebSocketEvent> void processEventHandlers(T event) {
} }
} }
@SuppressWarnings({"unchecked", "deprecation"}) @SuppressWarnings({"unchecked"})
public <T extends WebSocketEvent> void eventHandle(T webSocketEvent) { public <T extends WebSocketEvent> void eventHandle(T webSocketEvent) {
if (webSocketEvent instanceof RequestEvent) { if (webSocketEvent instanceof RequestEvent) {
RequestEvent event = (RequestEvent) webSocketEvent; RequestEvent event = (RequestEvent) webSocketEvent;

View file

@ -5,7 +5,6 @@
import pro.gravit.launcher.request.RequestService; import pro.gravit.launcher.request.RequestService;
import pro.gravit.launcher.request.WebSocketEvent; import pro.gravit.launcher.request.WebSocketEvent;
import java.io.IOException;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
public class VoidRequestService implements RequestService { public class VoidRequestService implements RequestService {
@ -20,7 +19,7 @@ public VoidRequestService() {
} }
@Override @Override
public <T extends WebSocketEvent> CompletableFuture<T> request(Request<T> request) throws IOException { public <T extends WebSocketEvent> CompletableFuture<T> request(Request<T> request) {
CompletableFuture<T> future = new CompletableFuture<>(); CompletableFuture<T> future = new CompletableFuture<>();
future.completeExceptionally(ex != null ? ex : new RequestException("Connection fail")); future.completeExceptionally(ex != null ? ex : new RequestException("Connection fail"));
return future; return future;

View file

@ -29,14 +29,14 @@ public void handlerAdded(final ChannelHandlerContext ctx) {
} }
@Override @Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception { public void channelActive(final ChannelHandlerContext ctx) {
handshaker.handshake(ctx.channel()); handshaker.handshake(ctx.channel());
clientJSONPoint.onOpen(); clientJSONPoint.onOpen();
ctx.executor().scheduleWithFixedDelay(() -> ctx.channel().writeAndFlush(new PingWebSocketFrame()), 20L, 20L, TimeUnit.SECONDS); ctx.executor().scheduleWithFixedDelay(() -> ctx.channel().writeAndFlush(new PingWebSocketFrame()), 20L, 20L, TimeUnit.SECONDS);
} }
@Override @Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception { public void channelInactive(final ChannelHandlerContext ctx) {
//System.out.println("WebSocket Client disconnected!"); //System.out.println("WebSocket Client disconnected!");
clientJSONPoint.onDisconnect(); clientJSONPoint.onDisconnect();
} }

View file

@ -43,12 +43,12 @@ java11Implementation files(sourceSets.main.output.classesDirs) { builtBy compile
targetCompatibility = 11 targetCompatibility = 11
} }
task sourcesJar(type: Jar) { tasks.register('sourcesJar', Jar) {
from sourceSets.main.allJava from sourceSets.main.allJava
archiveClassifier.set('sources') archiveClassifier.set('sources')
} }
task javadocJar(type: Jar) { tasks.register('javadocJar', Jar) {
from javadoc from javadoc
archiveClassifier.set('javadoc') archiveClassifier.set('javadoc')
} }

View file

@ -101,7 +101,7 @@ public void downloadListInOneThread(List<SizedFile> files, String baseURL, Path
} }
} }
public void downloadListInOneThreadSimple(List<SizedFile> files, String baseURL, Path targetDir) throws URISyntaxException, IOException { public void downloadListInOneThreadSimple(List<SizedFile> files, String baseURL, Path targetDir) throws IOException {
for (AsyncDownloader.SizedFile currentFile : files) { for (AsyncDownloader.SizedFile currentFile : files) {
downloadFile(new URL(baseURL + currentFile.urlPath), targetDir.resolve(currentFile.filePath), currentFile.size); downloadFile(new URL(baseURL + currentFile.urlPath), targetDir.resolve(currentFile.filePath), currentFile.size);
@ -157,7 +157,7 @@ public CompletableFuture[] runDownloadListSimple(List<List<SizedFile>> files, St
futures[i] = CompletableFuture.runAsync(() -> { futures[i] = CompletableFuture.runAsync(() -> {
try { try {
downloadListInOneThreadSimple(currentTasks, baseURL, targetDir); downloadListInOneThreadSimple(currentTasks, baseURL, targetDir);
} catch (URISyntaxException | IOException e) { } catch (IOException e) {
throw new CompletionException(e); throw new CompletionException(e);
} }
}, executor); }, executor);

View file

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

View file

@ -10,8 +10,8 @@ public void registerHook(Hook<V, R> hook) {
list.add(hook); list.add(hook);
} }
public boolean unregisterHook(Hook<V, R> hook) { public void unregisterHook(Hook<V, R> hook) {
return list.remove(hook); list.remove(hook);
} }
/** /**

View file

@ -17,7 +17,7 @@ private Downloader(CompletableFuture<Void> future, AsyncDownloader downloader) {
this.asyncDownloader = downloader; this.asyncDownloader = downloader;
} }
public static Downloader downloadList(List<AsyncDownloader.SizedFile> files, String baseURL, Path targetDir, DownloadCallback callback, ExecutorService executor, int threads) throws Exception { public static Downloader downloadList(List<AsyncDownloader.SizedFile> files, String baseURL, Path targetDir, DownloadCallback callback, ExecutorService executor, int threads) {
final boolean closeExecutor; final boolean closeExecutor;
LogHelper.info("Download with legacy mode"); LogHelper.info("Download with legacy mode");
if (executor == null) { if (executor == null) {

View file

@ -10,8 +10,8 @@ public void registerHook(Hook<R> hook) {
list.add(hook); list.add(hook);
} }
public boolean unregisterHook(Hook<R> hook) { public void unregisterHook(Hook<R> hook) {
return list.remove(hook); list.remove(hook);
} }
/** /**

View file

@ -23,7 +23,6 @@ public class PublicURLClassLoader extends URLClassLoader {
* {@code checkCreateClassLoader} method doesn't allow * {@code checkCreateClassLoader} method doesn't allow
* creation of a class loader. * creation of a class loader.
* @throws NullPointerException if {@code urls} is {@code null}. * @throws NullPointerException if {@code urls} is {@code null}.
* @see SecurityManager#checkCreateClassLoader
*/ */
public PublicURLClassLoader(URL[] urls) { public PublicURLClassLoader(URL[] urls) {
super(urls); super(urls);
@ -48,7 +47,6 @@ public PublicURLClassLoader(URL[] urls) {
* {@code checkCreateClassLoader} method doesn't allow * {@code checkCreateClassLoader} method doesn't allow
* creation of a class loader. * creation of a class loader.
* @throws NullPointerException if {@code urls} is {@code null}. * @throws NullPointerException if {@code urls} is {@code null}.
* @see SecurityManager#checkCreateClassLoader
*/ */
public PublicURLClassLoader(URL[] urls, ClassLoader parent) { public PublicURLClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent); super(urls, parent);

View file

@ -82,8 +82,8 @@ public void registerCategory(Category category) {
categories.add(category); categories.add(category);
} }
public boolean unregisterCategory(Category category) { public void unregisterCategory(Category category) {
return categories.remove(category); categories.remove(category);
} }
public Category findCategory(String name) { public Category findCategory(String name) {

View file

@ -9,18 +9,6 @@
import java.util.List; import java.util.List;
public class JLineCommandHandler extends CommandHandler { public class JLineCommandHandler extends CommandHandler {
/*private final class JLineOutput implements Output {
@Override
public void println(String message) {
try {
reader.println(ConsoleReader.RESET_LINE + message);
reader.drawLine();
reader.flush();
} catch (IOException ignored) {
// Ignored
}
}
}*/
private final Terminal terminal; private final Terminal terminal;
private final LineReader reader; private final LineReader reader;
@ -40,8 +28,6 @@ public JLineCommandHandler() throws IOException {
//reader.setExpandEvents(false); //reader.setExpandEvents(false);
// Replace writer // Replace writer
//LogHelper.removeStdOutput();
//LogHelper.addOutput(new JLineOutput(), LogHelper.OutputTypes.JANSI);
} }
@Override @Override

View file

@ -384,7 +384,7 @@ public static BasicFileAttributes readAttributes(Path path) throws IOException {
return Files.readAttributes(path, BasicFileAttributes.class, LINK_OPTIONS); return Files.readAttributes(path, BasicFileAttributes.class, LINK_OPTIONS);
} }
public static BufferedImage readTexture(Object input, boolean cloak) throws IOException { public static void readTexture(Object input, boolean cloak) throws IOException {
ImageReader reader = ImageIO.getImageReadersByMIMEType("image/png").next(); ImageReader reader = ImageIO.getImageReadersByMIMEType("image/png").next();
try { try {
reader.setInput(ImageIO.createImageInputStream(input), false, false); reader.setInput(ImageIO.createImageInputStream(input), false, false);
@ -396,7 +396,7 @@ public static BufferedImage readTexture(Object input, boolean cloak) throws IOEx
throw new IOException(String.format("Invalid texture bounds: %dx%d", width, height)); throw new IOException(String.format("Invalid texture bounds: %dx%d", width, height));
// Read image // Read image
return reader.read(0); reader.read(0);
} finally { } finally {
reader.dispose(); reader.dispose();
} }
@ -528,8 +528,8 @@ public static long transfer(InputStream input, OutputStream output) throws IOExc
return transferred; return transferred;
} }
public static long transfer(InputStream input, Path file) throws IOException { public static void transfer(InputStream input, Path file) throws IOException {
return transfer(input, file, false); transfer(input, file, false);
} }
public static long transfer(InputStream input, Path file, boolean append) throws IOException { public static long transfer(InputStream input, Path file, boolean append) throws IOException {

View file

@ -87,7 +87,7 @@ public static InputStream getClassBytesStream(Class<?> clazz) throws IOException
return getClassBytesStream(clazz, clazz.getClassLoader()); return getClassBytesStream(clazz, clazz.getClassLoader());
} }
public static InputStream getClassBytesStream(Class<?> clazz, ClassLoader classLoader) throws IOException { public static InputStream getClassBytesStream(Class<?> clazz, ClassLoader classLoader) {
return classLoader.getResourceAsStream(getClassFile(clazz)); return classLoader.getResourceAsStream(getClassFile(clazz));
} }
@ -107,7 +107,7 @@ public static byte[] getClassFromJar(String name, Path file) throws IOException
@FunctionalInterface @FunctionalInterface
public interface ZipWalkCallback { public interface ZipWalkCallback {
void process(ZipInputStream input, ZipEntry e) throws IOException; void process(ZipInputStream input, ZipEntry e);
} }
@FunctionalInterface @FunctionalInterface

View file

@ -63,11 +63,7 @@ public synchronized static List<JavaVersion> findJava() {
} }
List<String> javaPaths = new ArrayList<>(4); List<String> javaPaths = new ArrayList<>(4);
List<JavaVersion> result = new ArrayList<>(4); List<JavaVersion> result = new ArrayList<>(4);
try { tryAddJava(javaPaths, result, JavaVersion.getCurrentJavaVersion());
tryAddJava(javaPaths, result, JavaVersion.getCurrentJavaVersion());
} catch (IOException e) {
LogHelper.error(e);
}
String[] path = System.getenv("PATH").split(JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE ? ";" : ":"); String[] path = System.getenv("PATH").split(JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE ? ";" : ":");
for (String p : path) { for (String p : path) {
try { try {
@ -121,25 +117,20 @@ private static JavaVersion tryFindJavaByPath(Path path) {
return null; return null;
} }
public static boolean tryAddJava(List<String> javaPaths, List<JavaVersion> result, JavaVersion version) throws IOException { public static void tryAddJava(List<String> javaPaths, List<JavaVersion> result, JavaVersion version) {
if (version == null) return false; if (version == null) return;
String path = version.jvmDir.toAbsolutePath().toString(); String path = version.jvmDir.toAbsolutePath().toString();
if (javaPaths.contains(path)) return false; if (javaPaths.contains(path)) return;
javaPaths.add(path); javaPaths.add(path);
result.add(version); result.add(version);
return true;
} }
public static void trySearchJava(List<String> javaPaths, List<JavaVersion> result, Path path) throws IOException { public static void trySearchJava(List<String> javaPaths, List<JavaVersion> result, Path path) throws IOException {
if (path == null || !Files.isDirectory(path)) return; if (path == null || !Files.isDirectory(path)) return;
Files.list(path).filter(p -> Files.exists(p.resolve("bin").resolve(JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE ? "java.exe" : "java"))).forEach(e -> { Files.list(path).filter(p -> Files.exists(p.resolve("bin").resolve(JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE ? "java.exe" : "java"))).forEach(e -> {
try { tryAddJava(javaPaths, result, JavaVersion.getByPath(e));
tryAddJava(javaPaths, result, JavaVersion.getByPath(e)); if (Files.exists(e.resolve("jre"))) {
if (Files.exists(e.resolve("jre"))) { tryAddJava(javaPaths, result, JavaVersion.getByPath(e.resolve("jre")));
tryAddJava(javaPaths, result, JavaVersion.getByPath(e.resolve("jre")));
}
} catch (IOException ioException) {
LogHelper.error(ioException);
} }
}); });
} }
@ -233,7 +224,7 @@ private static boolean isCurrentJavaSupportJavaFX() {
} }
} }
public static JavaVersion getByPath(Path jvmDir) throws IOException { public static JavaVersion getByPath(Path jvmDir) {
{ {
JavaVersion version = JavaHelper.tryFindJavaByPath(jvmDir); JavaVersion version = JavaHelper.tryFindJavaByPath(jvmDir);
if (version != null) { if (version != null) {
@ -241,18 +232,23 @@ public static JavaVersion getByPath(Path jvmDir) throws IOException {
} }
} }
Path releaseFile = jvmDir.resolve("release"); Path releaseFile = jvmDir.resolve("release");
JavaVersionAndBuild versionAndBuild; JavaVersionAndBuild versionAndBuild = null;
JVMHelper.ARCH arch = JVMHelper.ARCH_TYPE; JVMHelper.ARCH arch = JVMHelper.ARCH_TYPE;
if (IOHelper.isFile(releaseFile)) { if (IOHelper.isFile(releaseFile)) {
Properties properties = new Properties();
properties.load(IOHelper.newReader(releaseFile));
versionAndBuild = getJavaVersion(properties.getProperty("JAVA_VERSION").replaceAll("\"", ""));
try { try {
arch = JVMHelper.getArch(properties.getProperty("OS_ARCH").replaceAll("\"", "")); Properties properties = new Properties();
} catch (Throwable ignored) { properties.load(IOHelper.newReader(releaseFile));
arch = null; versionAndBuild = getJavaVersion(properties.getProperty("JAVA_VERSION").replaceAll("\"", ""));
try {
arch = JVMHelper.getArch(properties.getProperty("OS_ARCH").replaceAll("\"", ""));
} catch (Throwable ignored) {
arch = null;
}
} catch (IOException ignored) {
} }
} else { }
if(versionAndBuild == null) {
versionAndBuild = new JavaVersionAndBuild(isExistExtJavaLibrary(jvmDir, "rt") ? 8 : 9, 0); versionAndBuild = new JavaVersionAndBuild(isExistExtJavaLibrary(jvmDir, "rt") ? 8 : 9, 0);
} }
JavaVersion resultJavaVersion = new JavaVersion(jvmDir, versionAndBuild.version, versionAndBuild.build, arch, false); JavaVersion resultJavaVersion = new JavaVersion(jvmDir, versionAndBuild.version, versionAndBuild.build, arch, false);

View file

@ -25,7 +25,7 @@ public final class LogHelper {
public static final String NO_JANSI_PROPERTY = "launcher.noJAnsi"; public static final String NO_JANSI_PROPERTY = "launcher.noJAnsi";
public static final String NO_SLF4J_PROPERTY = "launcher.noSlf4j"; public static final String NO_SLF4J_PROPERTY = "launcher.noSlf4j";
private static final Set<Consumer<Throwable>> EXCEPTIONS_CALLBACKS = Collections.newSetFromMap(new ConcurrentHashMap<>(2)); private static final Set<Consumer<Throwable>> EXCEPTIONS_CALLBACKS = Collections.newSetFromMap(new ConcurrentHashMap<>(2));
private static LogHelperAppender impl; private static final LogHelperAppender impl;
static { static {
boolean useSlf4j = false; boolean useSlf4j = false;

View file

@ -11,16 +11,15 @@
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
public final class UnpackHelper { public final class UnpackHelper {
public static boolean unpack(URL resource, Path target) throws IOException { public static void unpack(URL resource, Path target) throws IOException {
if (IOHelper.isFile(target)) { if (IOHelper.isFile(target)) {
if (matches(target, resource)) return false; if (matches(target, resource)) return;
} }
Files.deleteIfExists(target); Files.deleteIfExists(target);
IOHelper.createParentDirs(target); IOHelper.createParentDirs(target);
try (InputStream in = IOHelper.newInput(resource)) { try (InputStream in = IOHelper.newInput(resource)) {
IOHelper.transfer(in, target); IOHelper.transfer(in, target);
} }
return true;
} }
private static boolean matches(Path target, URL in) { private static boolean matches(Path target, URL in) {
@ -48,10 +47,10 @@ public static boolean unpackZipNoCheck(URL resource, Path target) throws IOExcep
return true; return true;
} }
public static boolean unpackZipNoCheck(String resource, Path target) throws IOException { public static void unpackZipNoCheck(String resource, Path target) throws IOException {
try { try {
if (Files.isDirectory(target)) if (Files.isDirectory(target))
return false; return;
Files.deleteIfExists(target); Files.deleteIfExists(target);
Files.createDirectory(target); Files.createDirectory(target);
try (ZipInputStream input = IOHelper.newZipInput(IOHelper.getResourceURL(resource))) { try (ZipInputStream input = IOHelper.newZipInput(IOHelper.getResourceURL(resource))) {
@ -62,9 +61,7 @@ public static boolean unpackZipNoCheck(String resource, Path target) throws IOEx
IOHelper.transfer(input, target.resolve(IOHelper.toPath(entry.getName()))); IOHelper.transfer(input, target.resolve(IOHelper.toPath(entry.getName())));
} }
} }
return true;
} catch (NoSuchFileException e) { } catch (NoSuchFileException e) {
return true;
} }
} }
} }

View file

@ -67,8 +67,8 @@ public static double verifyDouble(double d, DoublePredicate predicate, String er
throw new IllegalArgumentException(error); throw new IllegalArgumentException(error);
} }
public static String verifyIDName(String name) { public static void verifyIDName(String name) {
return verify(name, VerifyHelper::isValidIDName, String.format("Invalid name: '%s'", name)); verify(name, VerifyHelper::isValidIDName, String.format("Invalid name: '%s'", name));
} }
public static int verifyInt(int i, IntPredicate predicate, String error) { public static int verifyInt(int i, IntPredicate predicate, String error) {

View file

@ -31,7 +31,6 @@ public class SimpleLogHelperImpl implements LogHelperAppender {
// Output settings // Output settings
private final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss", Locale.US); private final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss", Locale.US);
private final Set<LogHelper.OutputEnity> OUTPUTS = Collections.newSetFromMap(new ConcurrentHashMap<>(2)); private final Set<LogHelper.OutputEnity> OUTPUTS = Collections.newSetFromMap(new ConcurrentHashMap<>(2));
private final LogHelper.OutputEnity STD_OUTPUT;
public SimpleLogHelperImpl() { public SimpleLogHelperImpl() {
// Use JAnsi if available // Use JAnsi if available
@ -50,7 +49,7 @@ public SimpleLogHelperImpl() {
JANSI = jansi; JANSI = jansi;
// Add std writer // Add std writer
STD_OUTPUT = new LogHelper.OutputEnity(System.out::println, JANSI ? LogHelper.OutputTypes.JANSI : LogHelper.OutputTypes.PLAIN); OutputEnity STD_OUTPUT = new OutputEnity(System.out::println, JANSI ? OutputTypes.JANSI : OutputTypes.PLAIN);
addOutput(STD_OUTPUT); addOutput(STD_OUTPUT);
// Add file log writer // Add file log writer

View file

@ -14,7 +14,6 @@
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.*; import java.util.concurrent.*;

View file

@ -47,12 +47,12 @@ java11Implementation files(sourceSets.main.output.classesDirs) { builtBy compile
"Multi-Release": "true") "Multi-Release": "true")
} }
task sourcesJar(type: Jar) { tasks.register('sourcesJar', Jar) {
from sourceSets.main.allJava from sourceSets.main.allJava
archiveClassifier.set('sources') archiveClassifier.set('sources')
} }
task javadocJar(type: Jar) { tasks.register('javadocJar', Jar) {
from javadoc from javadoc
archiveClassifier.set('javadoc') archiveClassifier.set('javadoc')
} }

View file

@ -70,7 +70,7 @@ public void restore() throws Exception {
Request.restore(); Request.restore();
} }
public ProfilesRequestEvent getProfiles() throws Exception { public void getProfiles() throws Exception {
ProfilesRequestEvent result = new ProfilesRequest().request(); ProfilesRequestEvent result = new ProfilesRequest().request();
for (ClientProfile p : result.profiles) { for (ClientProfile p : result.profiles) {
LogHelper.debug("Get profile: %s", p.getTitle()); LogHelper.debug("Get profile: %s", p.getTitle());
@ -90,10 +90,8 @@ public ProfilesRequestEvent getProfiles() throws Exception {
if (profile == null) { if (profile == null) {
LogHelper.warning("Not connected to ServerProfile. May be serverName incorrect?"); LogHelper.warning("Not connected to ServerProfile. May be serverName incorrect?");
} }
return result;
} }
@SuppressWarnings("ConfusingArgumentToVarargsMethod")
public void run(String... args) throws Throwable { public void run(String... args) throws Throwable {
initGson(); initGson();
AuthRequest.registerProviders(); AuthRequest.registerProviders();

View file

@ -2,7 +2,6 @@
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import pro.gravit.launcher.managers.GsonManager; import pro.gravit.launcher.managers.GsonManager;
import pro.gravit.launcher.modules.events.PreGsonPhase;
import pro.gravit.launcher.request.websockets.ClientWebSocketService; import pro.gravit.launcher.request.websockets.ClientWebSocketService;
public class ServerWrapperGsonManager extends GsonManager { public class ServerWrapperGsonManager extends GsonManager {

View file

@ -7,7 +7,6 @@
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths;
public class DownloadContextModifier implements LibrariesHashFileModifier { public class DownloadContextModifier implements LibrariesHashFileModifier {
@Override @Override

View file

@ -14,7 +14,7 @@
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
public class InstallAuthlib { public class InstallAuthlib {
private static Map<String, LibrariesHashFileModifier> modifierMap; private static final Map<String, LibrariesHashFileModifier> modifierMap;
static { static {
modifierMap = new HashMap<>(); modifierMap = new HashMap<>();
modifierMap.put("META-INF/libraries.list", new LibrariesLstModifier()); modifierMap.put("META-INF/libraries.list", new LibrariesLstModifier());
@ -43,7 +43,7 @@ public void run(String... args) throws Exception {
LogHelper.info("Search .jar files in %s", context.workdir.toAbsolutePath()); LogHelper.info("Search .jar files in %s", context.workdir.toAbsolutePath());
IOHelper.walk(context.workdir, new SimpleFileVisitor<Path>() { IOHelper.walk(context.workdir, new SimpleFileVisitor<Path>() {
@Override @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if(file.getFileName().toString().endsWith(".jar")) { if(file.getFileName().toString().endsWith(".jar")) {
context.files.add(file); context.files.add(file);
} }

View file

@ -2,13 +2,12 @@
import pro.gravit.utils.helper.SecurityHelper; import pro.gravit.utils.helper.SecurityHelper;
import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
public class LibrariesLstModifier implements LibrariesHashFileModifier { public class LibrariesLstModifier implements LibrariesHashFileModifier {
@Override @Override
public byte[] apply(byte[] data, InstallAuthlib.InstallAuthlibContext context) throws IOException { public byte[] apply(byte[] data, InstallAuthlib.InstallAuthlibContext context) {
String[] lines = new String(data).split("\n"); String[] lines = new String(data).split("\n");
for(int i=0;i<lines.length;++i) { for(int i=0;i<lines.length;++i) {
if(lines[i].contains("com.mojang:authlib")) { if(lines[i].contains("com.mojang:authlib")) {

View file

@ -4,7 +4,7 @@
public class ModuleLaunch implements Launch { public class ModuleLaunch implements Launch {
@Override @Override
public void run(String mainclass, ServerWrapper.Config config, String[] args) throws Throwable { public void run(String mainclass, ServerWrapper.Config config, String[] args) {
throw new UnsupportedOperationException("Module system not supported"); throw new UnsupportedOperationException("Module system not supported");
} }
} }

View file

@ -11,14 +11,12 @@
import pro.gravit.utils.helper.JVMHelper; import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper; import pro.gravit.utils.helper.LogHelper;
import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.net.URL; import java.net.URL;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.HashMap;
import java.util.jar.JarFile; import java.util.jar.JarFile;
public class ServerWrapperSetup { public class ServerWrapperSetup {

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