idea cleanup serverwrapper

This commit is contained in:
dima_dencep 2022-09-24 00:44:02 +07:00
parent 642cec3886
commit 7ae6b6dbb6
8 changed files with 83 additions and 83 deletions

View file

@ -30,7 +30,10 @@
import java.lang.reflect.Type;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ServerWrapper extends JsonConfigurable<ServerWrapper.Config> {
public static final Path configFile = Paths.get(System.getProperty("serverwrapper.configFile", "ServerWrapperConfig.json"));
@ -61,10 +64,10 @@ public static void main(String... args) throws Throwable {
}
public void restore() throws Exception {
if(config.oauth != null) {
if (config.oauth != null) {
Request.setOAuth(config.authId, config.oauth, config.oauthExpireTime);
}
if(config.extendedTokens != null) {
if (config.extendedTokens != null) {
Request.addAllExtendedToken(config.extendedTokens);
}
Request.restore();
@ -111,7 +114,7 @@ public void run(String... args) throws Throwable {
LogHelper.debug("Read ServerWrapperConfig.json");
loadConfig();
InstallAuthlib command = new InstallAuthlib();
command. run(args[1]);
command.run(args[1]);
System.exit(0);
}
LogHelper.debug("Read ServerWrapperConfig.json");
@ -136,7 +139,7 @@ public void run(String... args) throws Throwable {
restore();
getProfiles();
}
if(config.encodedServerRsaPublicKey != null) {
if (config.encodedServerRsaPublicKey != null) {
KeyService.serverRsaPublicKey = SecurityHelper.toPublicRSAKey(config.encodedServerRsaPublicKey);
}
String classname = (config.mainclass == null || config.mainclass.isEmpty()) ? args[0] : config.mainclass;
@ -144,7 +147,7 @@ public void run(String... args) throws Throwable {
LogHelper.error("MainClass not found. Please set MainClass for ServerWrapper.json or first commandline argument");
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'");
System.exit(-1);
}
@ -161,7 +164,7 @@ public void run(String... args) throws Throwable {
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().name);
String[] real_args;
if(config.args != null && config.args.size() > 0) {
if (config.args != null && config.args.size() > 0) {
real_args = config.args.toArray(new String[0]);
} else if (args.length > 0) {
real_args = new String[args.length - 1];

View file

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

View file

@ -7,17 +7,16 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DownloadContextModifier implements LibrariesHashFileModifier {
@Override
public byte[] apply(byte[] data, InstallAuthlib.InstallAuthlibContext context) throws IOException {
String[] lines = new String(data).split("\n");
for(int i=0;i<lines.length;++i) {
if(lines[i].contains("mojang_")) {
for (int i = 0; i < lines.length; ++i) {
if (lines[i].contains("mojang_")) {
String[] separated = lines[i].split("\t");
Path path = context.workdir.resolve("cache").resolve(separated[2]);
if(Files.notExists(path)) {
if (Files.notExists(path)) {
LogHelper.warning("Unable to find %s. Maybe you should start the server at least once?", path);
return data;
}

View file

@ -15,19 +15,21 @@
public class InstallAuthlib {
private static Map<String, LibrariesHashFileModifier> modifierMap;
static {
modifierMap = new HashMap<>();
modifierMap.put("META-INF/libraries.list", new LibrariesLstModifier());
modifierMap.put("patch.properties", new PatchPropertiesModifier());
modifierMap.put("META-INF/download-context", new DownloadContextModifier());
}
public void run(String... args) throws Exception {
boolean deleteAuthlibAfterInstall = false;
InstallAuthlibContext context = new InstallAuthlibContext();
if(args[0].startsWith("http://") || args[0].startsWith("https://")) {
if (args[0].startsWith("http://") || args[0].startsWith("https://")) {
Path tempAuthlib = Paths.get("authlib.jar");
LogHelper.info("Download %s to %s", args[0], tempAuthlib);
try(InputStream input = IOHelper.newInput(new URL(args[0]))) {
try (InputStream input = IOHelper.newInput(new URL(args[0]))) {
IOHelper.transfer(input, tempAuthlib);
}
context.pathToAuthlib = tempAuthlib;
@ -35,7 +37,7 @@ public void run(String... args) throws Exception {
} else {
context.pathToAuthlib = Paths.get(args[0]);
}
if(Files.notExists(context.pathToAuthlib)) {
if (Files.notExists(context.pathToAuthlib)) {
throw new FileNotFoundException(context.pathToAuthlib.toString());
}
context.workdir = IOHelper.WORKING_DIR;
@ -43,26 +45,26 @@ public void run(String... args) throws Exception {
IOHelper.walk(context.workdir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if(file.getFileName().toString().endsWith(".jar")) {
if (file.getFileName().toString().endsWith(".jar")) {
context.files.add(file);
}
return FileVisitResult.CONTINUE;
}
}, true);
LogHelper.info("Search authlib in %d files", context.files.size());
for(Path path : context.files) {
for (Path path : context.files) {
boolean foundAuthlib = false;
try(ZipInputStream input = IOHelper.newZipInput(path)) {
try (ZipInputStream input = IOHelper.newZipInput(path)) {
ZipEntry e = input.getNextEntry();
while(e != null) {
while (e != null) {
String name = e.getName();
if(!e.isDirectory() && name.contains("com/mojang/authlib") && !foundAuthlib) {
if (!e.isDirectory() && name.contains("com/mojang/authlib") && !foundAuthlib) {
boolean isJarFile = name.endsWith(".jar");
String prefix = isJarFile ? name : name.substring(0, name.indexOf("com/mojang/authlib"));
context.repack.add(new RepackInfo(path, prefix, isJarFile));
foundAuthlib = true;
}
if(!e.isDirectory() && modifierMap.containsKey(name)) {
if (!e.isDirectory() && modifierMap.containsKey(name)) {
context.hashes.add(new HashFile(path, name, modifierMap.get(name)));
}
e = input.getNextEntry();
@ -70,14 +72,14 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
}
}
Path tmpFile = Paths.get("repack.tmp");
for(RepackInfo ri : context.repack) {
for (RepackInfo ri : context.repack) {
LogHelper.info("Found authlib in %s (prefix '%s' jar %s)", ri.path, ri.prefix, ri.isJarFile ? "true" : "false");
try(ZipInputStream input = IOHelper.newZipInput(ri.path)) {
try(ZipOutputStream output = new ZipOutputStream(IOHelper.newOutput(tmpFile))) {
try (ZipInputStream input = IOHelper.newZipInput(ri.path)) {
try (ZipOutputStream output = new ZipOutputStream(IOHelper.newOutput(tmpFile))) {
ZipEntry e;
e = input.getNextEntry();
while(e != null) {
if(!e.getName().equals("META-INF") && !e.getName().equals("META-INF/") && !e.getName().equals("META-INF/MANIFEST.MF")) {
while (e != null) {
if (!e.getName().equals("META-INF") && !e.getName().equals("META-INF/") && !e.getName().equals("META-INF/MANIFEST.MF")) {
break;
}
ZipEntry newEntry = IOHelper.newZipEntry(e);
@ -85,11 +87,11 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
IOHelper.transfer(input, output);
e = input.getNextEntry();
}
if(!ri.isJarFile) {
try(ZipInputStream input2 = new ZipInputStream(IOHelper.newInput(context.pathToAuthlib))) {
if (!ri.isJarFile) {
try (ZipInputStream input2 = new ZipInputStream(IOHelper.newInput(context.pathToAuthlib))) {
ZipEntry e2 = input2.getNextEntry();
while(e2 != null) {
if(e2.getName().startsWith("META-INF")) {
while (e2 != null) {
if (e2.getName().startsWith("META-INF")) {
e2 = input2.getNextEntry();
continue;
}
@ -102,10 +104,10 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
}
}
}
while(e != null) {
if(e.getName().startsWith(ri.prefix)) {
if(ri.isJarFile) {
if(context.repackedAuthlibBytes == null) {
while (e != null) {
if (e.getName().startsWith(ri.prefix)) {
if (ri.isJarFile) {
if (context.repackedAuthlibBytes == null) {
byte[] orig = IOHelper.read(input);
context.repackedAuthlibBytes = repackAuthlibJar(orig, context.pathToAuthlib);
}
@ -115,10 +117,10 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
e = input.getNextEntry();
continue;
} else {
if(context.repackedAuthlibFiles == null) {
if (context.repackedAuthlibFiles == null) {
context.repackedAuthlibFiles = getNames(context.pathToAuthlib);
}
if(context.repackedAuthlibFiles.contains(e.getName().substring(ri.prefix.length()))) {
if (context.repackedAuthlibFiles.contains(e.getName().substring(ri.prefix.length()))) {
e = input.getNextEntry();
continue;
}
@ -135,15 +137,15 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
Files.move(tmpFile, ri.path);
}
LogHelper.info("%d authlib files repacked", context.repack.size());
for(HashFile hf : context.hashes) {
for (HashFile hf : context.hashes) {
LogHelper.info("Found hash file %s in %s", hf.prefix, hf.path);
try(ZipInputStream input = IOHelper.newZipInput(hf.path)) {
try (ZipInputStream input = IOHelper.newZipInput(hf.path)) {
try (ZipOutputStream output = new ZipOutputStream(IOHelper.newOutput(tmpFile))) {
ZipEntry e = input.getNextEntry();
while(e != null) {
while (e != null) {
ZipEntry newEntry = IOHelper.newZipEntry(e);
output.putNextEntry(newEntry);
if(e.getName().equals(hf.prefix)) {
if (e.getName().equals(hf.prefix)) {
byte[] orig = IOHelper.read(input);
byte[] bytes = hf.modifier.apply(orig, context);
output.write(bytes);
@ -158,7 +160,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
Files.move(tmpFile, hf.path);
}
LogHelper.info("%d hash files repacked", context.hashes.size());
if(deleteAuthlibAfterInstall) {
if (deleteAuthlibAfterInstall) {
LogHelper.info("Delete %s", context.pathToAuthlib);
Files.delete(context.pathToAuthlib);
}
@ -167,10 +169,10 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
private Set<String> getNames(Path path) throws IOException {
Set<String> set = new HashSet<>();
try(ZipInputStream input = IOHelper.newZipInput(path)) {
try (ZipInputStream input = IOHelper.newZipInput(path)) {
ZipEntry e = input.getNextEntry();
while(e != null) {
if(!e.getName().startsWith("META-INF")) {
while (e != null) {
if (!e.getName().startsWith("META-INF")) {
set.add(e.getName());
}
e = input.getNextEntry();
@ -180,14 +182,14 @@ private Set<String> getNames(Path path) throws IOException {
}
private byte[] repackAuthlibJar(byte[] data, Path path) throws IOException {
try(ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(data))) {
try (ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(data))) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
try(ZipOutputStream output = new ZipOutputStream(result)) {
try (ZipOutputStream output = new ZipOutputStream(result)) {
Set<String> blacklist = new HashSet<>();
try(ZipInputStream input2 = IOHelper.newZipInput(path)) {
try (ZipInputStream input2 = IOHelper.newZipInput(path)) {
ZipEntry e = input2.getNextEntry();
while(e != null) {
if(e.getName().startsWith("META-INF")) {
while (e != null) {
if (e.getName().startsWith("META-INF")) {
e = input2.getNextEntry();
continue;
}
@ -199,8 +201,8 @@ private byte[] repackAuthlibJar(byte[] data, Path path) throws IOException {
}
}
ZipEntry e = input.getNextEntry();
while(e != null) {
if(blacklist.contains(e.getName())) {
while (e != null) {
if (blacklist.contains(e.getName())) {
e = input.getNextEntry();
continue;
}

View file

@ -10,8 +10,8 @@ public class LibrariesLstModifier implements LibrariesHashFileModifier {
@Override
public byte[] apply(byte[] data, InstallAuthlib.InstallAuthlibContext context) throws IOException {
String[] lines = new String(data).split("\n");
for(int i=0;i<lines.length;++i) {
if(lines[i].contains("com.mojang:authlib")) {
for (int i = 0; i < lines.length; ++i) {
if (lines[i].contains("com.mojang:authlib")) {
String[] separated = lines[i].split("\t");
separated[0] = SecurityHelper.toHex(SecurityHelper.digest(SecurityHelper.DigestAlgorithm.SHA256, context.repackedAuthlibBytes));
lines[i] = String.join("\t", separated);

View file

@ -15,34 +15,34 @@ public byte[] apply(byte[] data, InstallAuthlib.InstallAuthlibContext context) t
String version = null;
int linePatchedHashIndex = -1;
int lineOriginalHashIndex = -1;
for(int i=0;i<lines.length;++i) {
if(lines[i].startsWith("version=")) {
for (int i = 0; i < lines.length; ++i) {
if (lines[i].startsWith("version=")) {
version = lines[i].split("=")[1];
} else if(lines[i].startsWith("patchedHash=")) {
} else if (lines[i].startsWith("patchedHash=")) {
linePatchedHashIndex = i;
} else if(lines[i].startsWith("originalHash=")) {
} else if (lines[i].startsWith("originalHash=")) {
lineOriginalHashIndex = i;
}
}
if(version == null) {
if (version == null) {
LogHelper.warning("Unable to parse version from patch.properties");
return data;
}
if(linePatchedHashIndex < 0) {
if (linePatchedHashIndex < 0) {
LogHelper.warning("Unable to parse patchedHash from patch.properties");
return data;
}
if(lineOriginalHashIndex < 0) {
if (lineOriginalHashIndex < 0) {
LogHelper.warning("Unable to parse originalHash from patch.properties");
return data;
}
Path patchedFile = context.workdir.resolve("cache").resolve("patched_".concat(version).concat(".jar"));
Path originalFile = context.workdir.resolve("cache").resolve("mojang_".concat(version).concat(".jar"));
if(Files.notExists(patchedFile)) {
if (Files.notExists(patchedFile)) {
LogHelper.warning("Unable to find %s. Maybe you should start the server at least once?", patchedFile);
return data;
}
if(Files.notExists(originalFile)) {
if (Files.notExists(originalFile)) {
LogHelper.warning("Unable to find %s. Maybe you should start the server at least once?", originalFile);
return data;
}

View file

@ -11,14 +11,12 @@
import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper;
import java.io.Closeable;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.jar.JarFile;
public class ServerWrapperSetup {
@ -62,7 +60,7 @@ public void run() throws Exception {
wrapper.config.mainclass = mainClassName;
boolean altMode = false;
for (int i = 0; i < 10; ++i) {
if(!Request.isAvailable() || Request.getRequestService().isClosed()) {
if (!Request.isAvailable() || Request.getRequestService().isClosed()) {
System.out.println("Print launchserver websocket host( ws://host:port/api ):");
wrapper.config.address = commands.commandHandler.readLine();
StdWebSocketService service;
@ -87,12 +85,12 @@ public void run() throws Exception {
break;
} catch (Throwable e) {
LogHelper.error(e);
if(Request.isAvailable() && Request.getRequestService() instanceof AutoCloseable) {
if (Request.isAvailable() && Request.getRequestService() instanceof AutoCloseable) {
((AutoCloseable) Request.getRequestService()).close();
}
}
}
if(wrapper.profile != null && wrapper.profile.getVersion().compareTo(ClientProfile.Version.MC118) >= 0) {
if (wrapper.profile != null && wrapper.profile.getVersion().compareTo(ClientProfile.Version.MC118) >= 0) {
LogHelper.info("Switch to alternative start mode (1.18)");
wrapper.config.classpath.add(jarName);
wrapper.config.classLoaderConfig = ClientProfile.ClassLoaderConfig.LAUNCHER;
@ -129,7 +127,7 @@ public void run() throws Exception {
writer.append("-cp ");
String pathServerWrapper = IOHelper.getCodeSource(ServerWrapper.class).getFileName().toString();
writer.append(pathServerWrapper);
if(!altMode) {
if (!altMode) {
if (JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE) {
writer.append(";");
} else writer.append(":");
@ -139,8 +137,8 @@ public void run() throws Exception {
writer.append(ServerWrapper.class.getName());
writer.append("\n");
}
if(JVMHelper.OS_TYPE != JVMHelper.OS.MUSTDIE) {
if(!startScript.toFile().setExecutable(true)) {
if (JVMHelper.OS_TYPE != JVMHelper.OS.MUSTDIE) {
if (!startScript.toFile().setExecutable(true)) {
LogHelper.error("Failed to set executable %s", startScript);
}
}

View file

@ -13,9 +13,16 @@
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class ModuleLaunch implements Launch {
private static String getPackageFromClass(String clazz) {
int index = clazz.lastIndexOf(".");
if (index >= 0) {
return clazz.substring(0, index);
}
return clazz;
}
@Override
@SuppressWarnings("ConfusingArgumentToVarargsMethod")
public void run(ServerWrapper.Config config, String[] args) throws Throwable {
@ -29,28 +36,28 @@ public void run(ServerWrapper.Config config, String[] args) throws Throwable {
ModuleLayer.Controller controller = ModuleLayer.defineModulesWithOneLoader(configuration, List.of(bootLayer), ucl);
ModuleLayer layer = controller.layer();
// Configure exports / opens
for(var e : config.moduleConf.exports.entrySet()) {
for (var e : config.moduleConf.exports.entrySet()) {
String[] split = e.getKey().split("\\\\");
Module source = layer.findModule(split[0]).orElseThrow();
String pkg = split[1];
Module target = layer.findModule(e.getValue()).orElseThrow();
controller.addExports(source, pkg, target);
}
for(var e : config.moduleConf.opens.entrySet()) {
for (var e : config.moduleConf.opens.entrySet()) {
String[] split = e.getKey().split("\\\\");
Module source = layer.findModule(split[0]).orElseThrow();
String pkg = split[1];
Module target = layer.findModule(e.getValue()).orElseThrow();
controller.addOpens(source, pkg, target);
}
for(var e : config.moduleConf.reads.entrySet()) {
for (var e : config.moduleConf.reads.entrySet()) {
Module source = layer.findModule(e.getKey()).orElseThrow();
Module target = layer.findModule(e.getValue()).orElseThrow();
controller.addReads(source, target);
}
Module mainModule = layer.findModule(config.moduleConf.mainModule).orElseThrow();
Module unnamed = ModuleLaunch.class.getClassLoader().getUnnamedModule();
if(unnamed != null) {
if (unnamed != null) {
controller.addOpens(mainModule, getPackageFromClass(config.mainclass), unnamed);
}
// Start main class
@ -59,12 +66,4 @@ public void run(ServerWrapper.Config config, String[] args) throws Throwable {
MethodHandle mainMethod = MethodHandles.lookup().findStatic(mainClass, "main", MethodType.methodType(void.class, String[].class));
mainMethod.invoke(args);
}
private static String getPackageFromClass(String clazz) {
int index = clazz.lastIndexOf(".");
if(index >= 0) {
return clazz.substring(0, index);
}
return clazz;
}
}