Refactoring other classes

This commit is contained in:
dima_dencep 2023-07-02 12:06:16 +07:00
parent 2028838440
commit 74449c194c
No known key found for this signature in database
GPG key ID: ED87FE0D1750A12D
3 changed files with 104 additions and 145 deletions

View file

@ -5,7 +5,6 @@
import java.io.IOException; import java.io.IOException;
import java.lang.instrument.Instrumentation; import java.lang.instrument.Instrumentation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType; import java.lang.invoke.MethodType;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
@ -16,43 +15,32 @@
import java.util.jar.JarFile; import java.util.jar.JarFile;
public class ServerAgent { public class ServerAgent {
public static final Boolean isAutoloadLibraries = Boolean.getBoolean(System.getProperty("serverwrapper,agentlibrariesload", "false")); public static final Boolean isAutoloadLibraries = Boolean.getBoolean(System.getProperty("serverwrapper.agentlibrariesload", "false"));
public static final String proxyClassName = System.getProperty("serverwrapper.agentproxy", null);
public static Instrumentation inst = null; public static Instrumentation inst = null;
private static boolean isAgentStarted = false; public static boolean isAgentStarted = false;
public static void addJVMClassPath(String path) throws IOException {
LogHelper.debug("Load %s", path);
inst.appendToSystemClassLoaderSearch(new JarFile(path));
}
public static void addJVMClassPath(JarFile file) { public static void addJVMClassPath(JarFile file) {
LogHelper.debug("Load %s", file.getName()); LogHelper.debug("Load %s", file.getName());
inst.appendToSystemClassLoaderSearch(file); inst.appendToSystemClassLoaderSearch(file);
} }
public static boolean isAgentStarted() {
return isAgentStarted;
}
public static long getObjSize(Object obj) {
return inst.getObjectSize(obj);
}
public static void premain(String agentArgument, Instrumentation instrumentation) { public static void premain(String agentArgument, Instrumentation instrumentation) {
LogHelper.debug("Server Agent"); LogHelper.debug("Server Agent");
inst = instrumentation; inst = instrumentation;
isAgentStarted = true; isAgentStarted = true;
if (isAutoloadLibraries) { if (isAutoloadLibraries) {
Path libraries = Paths.get("libraries"); Path libraries = Paths.get("libraries");
if (IOHelper.exists(libraries)) loadLibraries(libraries); if (IOHelper.exists(libraries)) loadLibraries(libraries);
} }
String proxyClassName = System.getProperty("serverwrapper.agentproxy", null);
if (proxyClassName != null) { if (proxyClassName != null) {
Class<?> proxyClass;
try { try {
proxyClass = Class.forName(proxyClassName); MethodHandles.publicLookup()
MethodHandle mainMethod = MethodHandles.publicLookup().findStatic(proxyClass, "premain", MethodType.methodType(void.class, String.class, Instrumentation.class)); .findStatic(Class.forName(proxyClassName), "premain", MethodType.methodType(void.class, String.class, Instrumentation.class))
mainMethod.invoke(agentArgument, instrumentation); .invoke(agentArgument, instrumentation);
} catch (Throwable e) { } catch (Throwable e) {
LogHelper.error(e); LogHelper.error(e);
} }

View file

@ -1,28 +1,31 @@
package pro.gravit.launcher.server; package pro.gravit.launcher.server;
import pro.gravit.launcher.ClientPermissions; import com.google.gson.GsonBuilder;
import pro.gravit.launcher.Launcher; import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.LauncherConfig; import pro.gravit.launcher.LauncherConfig;
import pro.gravit.launcher.api.KeyService; import pro.gravit.launcher.api.KeyService;
import pro.gravit.launcher.config.JsonConfigurable; import pro.gravit.launcher.config.JsonConfigurable;
import pro.gravit.launcher.events.request.AuthRequestEvent; import pro.gravit.launcher.events.request.AuthRequestEvent;
import pro.gravit.launcher.events.request.ProfilesRequestEvent; import pro.gravit.launcher.managers.GsonManager;
import pro.gravit.launcher.profiles.ClientProfile; import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.profiles.PlayerProfile;
import pro.gravit.launcher.profiles.optional.actions.OptionalAction; import pro.gravit.launcher.profiles.optional.actions.OptionalAction;
import pro.gravit.launcher.profiles.optional.triggers.OptionalTrigger; import pro.gravit.launcher.profiles.optional.triggers.OptionalTrigger;
import pro.gravit.launcher.request.Request; import pro.gravit.launcher.request.Request;
import pro.gravit.launcher.request.auth.AuthRequest; import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.request.auth.GetAvailabilityAuthRequest; import pro.gravit.launcher.request.auth.GetAvailabilityAuthRequest;
import pro.gravit.launcher.request.update.ProfilesRequest; import pro.gravit.launcher.request.websockets.ClientWebSocketService;
import pro.gravit.launcher.request.websockets.StdWebSocketService; import pro.gravit.launcher.request.websockets.StdWebSocketService;
import pro.gravit.launcher.server.authlib.InstallAuthlib; import pro.gravit.launcher.server.commands.InstallAuthLib;
import pro.gravit.launcher.server.commands.SetupCommand;
import pro.gravit.launcher.server.launch.ClasspathLaunch; import pro.gravit.launcher.server.launch.ClasspathLaunch;
import pro.gravit.launcher.server.launch.Launch; import pro.gravit.launcher.server.launch.Launch;
import pro.gravit.launcher.server.launch.ModuleLaunch; import pro.gravit.launcher.server.launch.ModuleLaunch;
import pro.gravit.launcher.server.launch.SimpleLaunch; import pro.gravit.launcher.server.launch.SimpleLaunch;
import pro.gravit.launcher.server.setup.ServerWrapperSetup; import pro.gravit.utils.command.Command;
import pro.gravit.utils.PublicURLClassLoader; import pro.gravit.utils.command.CommandHandler;
import pro.gravit.utils.command.JLineCommandHandler;
import pro.gravit.utils.command.StdCommandHandler;
import pro.gravit.utils.command.basic.HelpCommand;
import pro.gravit.utils.helper.IOHelper; import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.LogHelper; import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper; import pro.gravit.utils.helper.SecurityHelper;
@ -35,136 +38,119 @@
public class ServerWrapper extends JsonConfigurable<ServerWrapper.Config> { public class ServerWrapper extends JsonConfigurable<ServerWrapper.Config> {
public static final Path configFile = Paths.get(System.getProperty("serverwrapper.configFile", "ServerWrapperConfig.json")); public static final Path configFile = Paths.get(System.getProperty("serverwrapper.configFile", "ServerWrapperConfig.json"));
public static final boolean disableSetup = Boolean.parseBoolean(System.getProperty("serverwrapper.disableSetup", "false")); public static final boolean disableSetup = Boolean.parseBoolean(System.getProperty("serverwrapper.disableSetup", "false"));
public static ServerWrapper wrapper; public CommandHandler commandHandler;
public Config config; public Config config;
public PublicURLClassLoader ucp;
public ClassLoader loader;
public ClientPermissions permissions;
public ClientProfile profile;
public PlayerProfile playerProfile;
public ClientProfile.ServerProfile serverProfile;
@Deprecated
public ServerWrapper(Type type, Path configPath) { public ServerWrapper(Type type, Path configPath) {
super(type, configPath); super(type, configPath);
} }
public static void initGson() {
Launcher.gsonManager = new ServerWrapperGsonManager();
Launcher.gsonManager.initGson();
}
public static void main(String... args) throws Throwable { public static void main(String... args) throws Throwable {
LogHelper.printVersion("ServerWrapper"); LogHelper.printVersion("ServerWrapper");
LogHelper.printLicense("ServerWrapper"); LogHelper.printLicense("ServerWrapper");
ServerWrapper.wrapper = new ServerWrapper(ServerWrapper.Config.class, configFile);
ServerWrapper.wrapper.run(args);
}
public void restore() throws Exception { Launcher.gsonManager = new GsonManager() {
if(config.oauth != null) { @Override
Request.setOAuth(config.authId, config.oauth, config.oauthExpireTime); public void registerAdapters(GsonBuilder builder) {
} super.registerAdapters(builder);
if(config.extendedTokens != null) { ClientWebSocketService.appendTypeAdapters(builder);
Request.addAllExtendedToken(config.extendedTokens);
}
Request.restore();
}
public void getProfiles() throws Exception {
ProfilesRequestEvent result = new ProfilesRequest().request();
for (ClientProfile p : result.profiles) {
LogHelper.debug("Get profile: %s", p.getTitle());
boolean isFound = false;
for (ClientProfile.ServerProfile srv : p.getServers()) {
if (srv != null && srv.name.equals(config.serverName)) {
this.serverProfile = srv;
this.profile = p;
Launcher.profile = p;
LogHelper.debug("Found profile: %s", Launcher.profile.getTitle());
isFound = true;
break;
}
} }
if (isFound) break; };
} Launcher.gsonManager.initGson();
if (profile == null) {
LogHelper.warning("Not connected to ServerProfile. May be serverName incorrect?"); new ServerWrapper(args);
}
} }
public void run(String... args) throws Throwable { public ServerWrapper(String[] args) throws Exception {
initGson(); super(ServerWrapper.Config.class, configFile);
LogHelper.debug("Read ServerWrapperConfig.json");
loadConfig();
Launcher.applyLauncherEnv(config.env == null ? LauncherConfig.LauncherEnvironment.STD : config.env);
if (config.logFile != null)
LogHelper.addOutput(IOHelper.newWriter(Paths.get(config.logFile), true));
AuthRequest.registerProviders(); AuthRequest.registerProviders();
GetAvailabilityAuthRequest.registerProviders(); GetAvailabilityAuthRequest.registerProviders();
OptionalAction.registerProviders(); OptionalAction.registerProviders();
OptionalTrigger.registerProviders(); OptionalTrigger.registerProviders();
if (args.length > 0 && args[0].equalsIgnoreCase("setup") && !disableSetup) {
LogHelper.debug("Read ServerWrapperConfig.json"); if (args.length > 0 && !disableSetup) {
loadConfig(); try {
ServerWrapperSetup setup = new ServerWrapperSetup(); Class.forName("org.jline.terminal.Terminal");
setup.run();
System.exit(0); this.commandHandler = new JLineCommandHandler();
LogHelper.debug("JLine2 terminal enabled");
} catch (ClassNotFoundException ignored) {
this.commandHandler = new StdCommandHandler(true);
LogHelper.debug("JLine2 isn't in classpath, using std");
}
this.commandHandler.registerCommand("help", new HelpCommand(this.commandHandler));
this.commandHandler.registerCommand("setup", new SetupCommand(this));
this.commandHandler.registerCommand("installauthlib", new InstallAuthLib());
} }
if (args.length > 1 && args[0].equalsIgnoreCase("installAuthlib") && !disableSetup) {
LogHelper.debug("Read ServerWrapperConfig.json"); if (this.commandHandler != null) {
loadConfig(); Command command = this.commandHandler.findCommand(args[0].toLowerCase());
InstallAuthlib command = new InstallAuthlib();
command. run(args[1]); if (command != null) {
System.exit(0); command.invoke(Arrays.copyOfRange(args, 1, args.length));
System.exit(0);
}
} }
LogHelper.debug("Read ServerWrapperConfig.json");
loadConfig();
updateLauncherConfig();
if (config.env != null) Launcher.applyLauncherEnv(config.env);
else Launcher.applyLauncherEnv(LauncherConfig.LauncherEnvironment.STD);
StdWebSocketService service = StdWebSocketService.initWebSockets(config.address).get(); StdWebSocketService service = StdWebSocketService.initWebSockets(config.address).get();
service.reconnectCallback = () -> service.reconnectCallback = () -> {
{
LogHelper.debug("WebSocket connect closed. Try reconnect"); LogHelper.debug("WebSocket connect closed. Try reconnect");
try { try {
Request.reconnect(); Request.reconnect();
getProfiles();
} catch (Exception e) { } catch (Exception e) {
LogHelper.error(e); LogHelper.error(e);
} }
}; };
Request.setRequestService(service); Request.setRequestService(service);
if (config.logFile != null) LogHelper.addOutput(IOHelper.newWriter(Paths.get(config.logFile), true));
{ restore();
restore();
getProfiles(); if (config.encodedServerRsaPublicKey != null)
}
if(config.encodedServerRsaPublicKey != null) {
KeyService.serverRsaPublicKey = SecurityHelper.toPublicRSAKey(config.encodedServerRsaPublicKey); KeyService.serverRsaPublicKey = SecurityHelper.toPublicRSAKey(config.encodedServerRsaPublicKey);
}
String classname = (config.mainclass == null || config.mainclass.isEmpty()) ? args[0] : config.mainclass; String classname = (config.mainclass == null || config.mainclass.isEmpty()) ? args[0] : config.mainclass;
if (classname.length() == 0) { if (classname.length() == 0) {
LogHelper.error("MainClass not found. Please set MainClass for ServerWrapper.json or first commandline argument"); LogHelper.error("MainClass not found. Please set MainClass for ServerWrapper.json or first commandline argument");
System.exit(-1); System.exit(-1);
} }
if(config.oauth == null && ( config.extendedTokens == null || config.extendedTokens.isEmpty())) {
if (config.oauth == null && (config.extendedTokens == null || config.extendedTokens.isEmpty())) {
LogHelper.error("Auth not configured. Please use 'java -jar ServerWrapper.jar setup'"); LogHelper.error("Auth not configured. Please use 'java -jar ServerWrapper.jar setup'");
System.exit(-1); System.exit(-1);
} }
if (config.autoloadLibraries) { if (config.autoloadLibraries) {
if (!ServerAgent.isAgentStarted()) { if (!ServerAgent.isAgentStarted)
throw new UnsupportedOperationException("JavaAgent not found, autoloadLibraries not available"); throw new UnsupportedOperationException("JavaAgent not found, autoLoadLibraries not available");
}
if (config.librariesDir == null) if (config.librariesDir == null)
throw new UnsupportedOperationException("librariesDir is null, autoloadLibraries not available"); throw new UnsupportedOperationException("librariesDir is null, autoLoadLibraries not available");
Path librariesDir = Paths.get(config.librariesDir);
LogHelper.info("Load libraries"); LogHelper.info("Loading libraries");
ServerAgent.loadLibraries(librariesDir); ServerAgent.loadLibraries(Paths.get(config.librariesDir));
} }
LogHelper.info("ServerWrapper: LaunchServer address: %s. Title: %s", config.address, Launcher.profile != null ? Launcher.profile.getTitle() : "unknown");
LogHelper.info("Minecraft Version (for profile): %s", wrapper.profile == null ? "unknown" : wrapper.profile.getVersion().toString()); LogHelper.info("Start Minecraft Server");
String[] real_args;
if(config.args != null && config.args.size() > 0) { List<String> real_args = Arrays.asList(args);
real_args = config.args.toArray(new String[0]); if (config.args != null) {
} else if (args.length > 0) { real_args.addAll(config.args);
real_args = new String[args.length - 1]; }
System.arraycopy(args, 1, real_args, 0, args.length - 1);
} else real_args = args;
Launch launch; Launch launch;
switch (config.classLoaderConfig) { switch (config.classLoaderConfig) {
case LAUNCHER: case LAUNCHER:
@ -177,19 +163,25 @@ public void run(String... args) throws Throwable {
launch = new SimpleLaunch(); launch = new SimpleLaunch();
break; break;
} }
LogHelper.info("Start Minecraft Server");
LogHelper.debug("Invoke main method %s with %s", classname, launch.getClass().getName()); LogHelper.debug("Invoke main method %s with %s", classname, launch.getClass().getCanonicalName());
try { try {
launch.run(classname, config, real_args); launch.run(classname, config, real_args.toArray(new String[0]));
} catch (Throwable e) { } catch (Throwable e) {
LogHelper.error(e); LogHelper.error(e);
System.exit(-1); System.exit(-1);
} }
} }
public void updateLauncherConfig() { public void restore() throws Exception {
LauncherConfig cfg = new LauncherConfig(config.address, null, null, new HashMap<>(), "ServerWrapper"); if (config.oauth != null)
Launcher.setConfig(cfg); Request.setOAuth(config.authId, config.oauth, config.oauthExpireTime);
if (config.extendedTokens != null)
Request.addAllExtendedToken(config.extendedTokens);
Request.restore();
} }
@Override @Override
@ -205,7 +197,6 @@ public void setConfig(Config config) {
@Override @Override
public Config getDefaultConfig() { public Config getDefaultConfig() {
Config newConfig = new Config(); Config newConfig = new Config();
newConfig.serverName = "your server name";
newConfig.mainclass = ""; newConfig.mainclass = "";
newConfig.extendedTokens = new HashMap<>(); newConfig.extendedTokens = new HashMap<>();
newConfig.args = new ArrayList<>(); newConfig.args = new ArrayList<>();
@ -217,10 +208,7 @@ public Config getDefaultConfig() {
} }
public static final class Config { public static final class Config {
@Deprecated
public String projectname;
public String address; public String address;
public String serverName;
public boolean autoloadLibraries; public boolean autoloadLibraries;
public String logFile; public String logFile;
public List<String> classpath; public List<String> classpath;

View file

@ -1,17 +0,0 @@
package pro.gravit.launcher.server;
import com.google.gson.GsonBuilder;
import pro.gravit.launcher.managers.GsonManager;
import pro.gravit.launcher.request.websockets.ClientWebSocketService;
public class ServerWrapperGsonManager extends GsonManager {
public ServerWrapperGsonManager() {
}
@Override
public void registerAdapters(GsonBuilder builder) {
super.registerAdapters(builder);
ClientWebSocketService.appendTypeAdapters(builder);
}
}