Merge branch 'release/5.6.0'

This commit is contained in:
Gravita 2024-03-24 22:13:15 +07:00
commit a8b165f081
399 changed files with 2999 additions and 2996 deletions

View file

@ -26,6 +26,8 @@ jobs:
- name: Build with Gradle
run: ./gradlew build
- name: Generate and submit dependency graph
uses: gradle/actions/dependency-submission@417ae3ccd767c252f5661f1ace9f835f9654f2b5
- name: Create artifacts
run: |

View file

@ -1,4 +1,4 @@
def mainClassName = "pro.gravit.launchserver.LaunchServerStarter"
def mainClassName = "pro.gravit.launchserver.Main"
def mainAgentName = "pro.gravit.launchserver.StarterAgent"
evaluationDependsOn(':Launcher')
@ -37,9 +37,6 @@
manifest.attributes("Main-Class": mainClassName,
"Premain-Class": mainAgentName,
"Multi-Release": "true",
"Can-Redefine-Classes": "true",
"Can-Retransform-Classes": "true",
"Can-Set-Native-Method-Prefix": "true"
)
}
@ -65,9 +62,7 @@
archiveClassifier.set('clean')
manifest.attributes("Main-Class": mainClassName,
"Premain-Class": mainAgentName,
"Can-Redefine-Classes": "true",
"Can-Retransform-Classes": "true",
"Can-Set-Native-Method-Prefix": "true"
"Automatic-Module-Name": "launchserver"
)
from sourceSets.main.output
}
@ -75,7 +70,6 @@
dependencies {
pack project(':LauncherAPI')
pack project(':LauncherModernCore')
bundle group: 'me.tongfei', name: 'progressbar', version: '0.9.2'
bundle group: 'com.github.Marcono1234', name: 'gson-record-type-adapter-factory', version: 'v0.2.0'
bundle group: 'org.fusesource.jansi', name: 'jansi', version: rootProject['verJansi']
@ -84,13 +78,15 @@ pack project(':LauncherModernCore')
bundle group: 'org.jline', name: 'jline-terminal', version: rootProject['verJline']
bundle group: 'org.bouncycastle', name: 'bcpkix-jdk15on', version: rootProject['verBcpkix']
bundle group: 'org.ow2.asm', name: 'asm-commons', version: rootProject['verAsm']
bundle group: 'io.netty', name: 'netty-all', version: rootProject['verNetty']
bundle group: 'io.netty', name: 'netty-codec-http', version: rootProject['verNetty']
bundle group: 'io.netty', name: 'netty-transport-classes-epoll', version: rootProject['verNetty']
bundle group: 'io.netty', name: 'netty-transport-native-epoll', version: rootProject['verNetty'], classifier: 'linux-x86_64'
bundle group: 'org.slf4j', name: 'slf4j-api', version: rootProject['verSlf4j']
bundle group: 'com.mysql', name: 'mysql-connector-j', version: rootProject['verMySQLConn']
bundle group: 'org.postgresql', name: 'postgresql', version: rootProject['verPostgreSQLConn']
bundle group: 'com.guardsquare', name: 'proguard-base', version: rootProject['verProguard']
bundle group: 'org.apache.logging.log4j', name: 'log4j-core', version: rootProject['verLog4j']
bundle group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: rootProject['verLog4j']
bundle group: 'org.apache.logging.log4j', name: 'log4j-slf4j2-impl', version: rootProject['verLog4j']
bundle group: 'io.jsonwebtoken', name: 'jjwt-api', version: rootProject['verJwt']
bundle group: 'io.jsonwebtoken', name: 'jjwt-impl', version: rootProject['verJwt']
bundle group: 'io.jsonwebtoken', name: 'jjwt-gson', version: rootProject['verJwt']
@ -104,16 +100,6 @@ pack project(':LauncherModernCore')
exclude group: 'org.slf4j'
}
launch4j('net.sf.launch4j:launch4j:' + rootProject['verLaunch4j']) {
exclude group: 'org.apache.ant'
exclude group: 'net.java.abeille'
exclude group: 'foxtrot'
exclude group: 'com.jgoodies'
exclude group: 'org.slf4j'
}
launch4j('net.sf.launch4j:launch4j:' + rootProject['verLaunch4j'] + ':workdir-win32') { transitive = false }
launch4j('net.sf.launch4j:launch4j:' + rootProject['verLaunch4j'] + ':workdir-linux64') { transitive = false }
compileOnlyA group: 'com.google.guava', name: 'guava', version: rootProject['verGuavaC']
// Do not update (laggy deps).
compileOnlyA 'log4j:log4j:1.2.17'
@ -126,27 +112,9 @@ pack project(':LauncherModernCore')
from configurations.hikari
}
tasks.register('launch4j', Copy) {
duplicatesStrategy = 'EXCLUDE'
into "$buildDir/libs/libraries/launch4j"
from(configurations.launch4j.collect {
it.isDirectory() ? it : ((it.getName().startsWith("launch4j") && it.getName().contains("workdir")) ? zipTree(it) : it)
})
includeEmptyDirs false
eachFile { FileCopyDetails fcp ->
if (fcp.relativePath.pathString.startsWith("launch4j-") &&
fcp.relativePath.pathString.contains("workdir")) {
def segments = fcp.relativePath.segments
def pathSegments = segments[1..-1] as String[]
fcp.relativePath = new RelativePath(!fcp.file.isDirectory(), pathSegments)
} else if (fcp.relativePath.pathString.contains("META-INF")) fcp.exclude()
fcp.mode = 0755
}
}
tasks.register('dumpLibs', Copy) {
duplicatesStrategy = 'EXCLUDE'
dependsOn tasks.hikari, tasks.launch4j
dependsOn tasks.hikari
into "$buildDir/libs/libraries"
from configurations.bundleOnly
}

View file

@ -1,7 +1,7 @@
package pro.gravit.launchserver;
import com.google.gson.JsonElement;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launchserver.helper.HttpHelper;
import java.io.IOException;

View file

@ -2,15 +2,13 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.events.RequestEvent;
import pro.gravit.launcher.events.request.ProfilesRequestEvent;
import pro.gravit.launcher.managers.ConfigManager;
import pro.gravit.launcher.modules.events.ClosePhase;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.events.RequestEvent;
import pro.gravit.launcher.base.events.request.ProfilesRequestEvent;
import pro.gravit.launcher.base.modules.events.ClosePhase;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.auth.core.RejectAuthCoreProvider;
import pro.gravit.launchserver.binary.EXEL4JLauncherBinary;
import pro.gravit.launchserver.binary.EXELauncherBinary;
import pro.gravit.launchserver.binary.JARLauncherBinary;
import pro.gravit.launchserver.binary.LauncherBinary;
@ -36,7 +34,6 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.KeyStore;
@ -117,11 +114,12 @@ public final class LaunchServer implements Runnable, AutoCloseable, Reconfigurab
public final AtomicBoolean started = new AtomicBoolean(false);
public final LauncherModuleLoader launcherModuleLoader;
private final Logger logger = LogManager.getLogger();
public final int shardId;
public LaunchServerConfig config;
// Updates and profiles
private volatile Set<ClientProfile> profilesList;
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, int shardId) throws IOException {
this.dir = directories.dir;
this.tmpDir = directories.tmpDir;
this.env = env;
@ -138,6 +136,7 @@ public LaunchServer(LaunchServerDirectories directories, LaunchServerEnv env, La
launcherLibraries = directories.launcherLibrariesDir;
launcherLibrariesCompile = directories.launcherLibrariesCompileDir;
launcherPack = directories.launcherPackDir;
this.shardId = shardId;
if(!Files.isDirectory(launcherPack)) {
Files.createDirectories(launcherPack);
}
@ -268,7 +267,7 @@ public void invoke(String... args) throws Exception {
}
pair.core.close();
pair.core = new RejectAuthCoreProvider();
pair.core.init(instance);
pair.core.init(instance, pair);
}
};
commands.put("resetauth", resetauth);
@ -300,12 +299,6 @@ private LauncherBinary binary() {
if(event.binary != null) {
return event.binary;
}
try {
Class.forName("net.sf.launch4j.Builder");
if (config.launch4j.enabled) return new EXEL4JLauncherBinary(this);
} catch (ClassNotFoundException ignored) {
logger.warn("Launch4J isn't in classpath.");
}
return new EXELauncherBinary(this);
}
@ -393,7 +386,7 @@ public void syncLauncherBinaries() throws IOException {
// Syncing launcher EXE binary
logger.info("Syncing launcher EXE binary file");
if (!launcherEXEBinary.sync() && config.launch4j.enabled)
if (!launcherEXEBinary.sync())
logger.warn("Missing launcher EXE binary file");
}
@ -430,21 +423,6 @@ public void syncUpdatesDir(Collection<String> dirs) throws IOException {
updatesManager.syncUpdatesDir(dirs);
}
public void restart() {
ProcessBuilder builder = new ProcessBuilder();
if (config.startScript != null) builder.command(Collections.singletonList(config.startScript));
else throw new IllegalArgumentException("Please create start script and link it as startScript in config.");
builder.directory(this.dir.toFile());
builder.inheritIO();
builder.redirectErrorStream(true);
builder.redirectOutput(Redirect.PIPE);
try {
builder.start();
} catch (IOException e) {
logger.error("Restart failed", e);
}
}
public void registerObject(String name, Object object) {
if (object instanceof Reconfigurable) {
reconfigurableManager.registerReconfigurable(name, (Reconfigurable) object);
@ -457,11 +435,6 @@ public void unregisterObject(String name, Object object) {
}
}
public void fullyRestart() {
restart();
JVMHelper.RUNTIME.exit(0);
}
public enum ReloadType {
NO_AUTH,
@ -504,6 +477,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
profile = Launcher.gsonManager.gson.fromJson(reader, ClientProfile.class);
}
profile.verify();
profile.setProfileFilePath(file);
// Add SIGNED profile to result list
result.add(profile);

View file

@ -19,6 +19,7 @@ public class LaunchServerBuilder {
private KeyAgreementManager keyAgreementManager;
private CertificateManager certificateManager;
private LaunchServer.LaunchServerConfigManager launchServerConfigManager;
private Integer shardId;
public LaunchServerBuilder setConfig(LaunchServerConfig config) {
this.config = config;
@ -55,6 +56,11 @@ public LaunchServerBuilder setDir(Path dir) {
return this;
}
public LaunchServerBuilder setShardId(Integer shardId) {
this.shardId = shardId;
return this;
}
public LaunchServerBuilder setLaunchServerConfigManager(LaunchServer.LaunchServerConfigManager launchServerConfigManager) {
this.launchServerConfigManager = launchServerConfigManager;
return this;
@ -63,32 +69,15 @@ public LaunchServerBuilder setLaunchServerConfigManager(LaunchServer.LaunchServe
public LaunchServer build() throws Exception {
directories.collect();
if (launchServerConfigManager == null) {
launchServerConfigManager = new LaunchServer.LaunchServerConfigManager() {
@Override
public LaunchServerConfig readConfig() {
throw new UnsupportedOperationException();
}
@Override
public LaunchServerRuntimeConfig readRuntimeConfig() {
throw new UnsupportedOperationException();
}
@Override
public void writeConfig(LaunchServerConfig config) {
throw new UnsupportedOperationException();
}
@Override
public void writeRuntimeConfig(LaunchServerRuntimeConfig config) {
throw new UnsupportedOperationException();
}
};
launchServerConfigManager = new NullLaunchServerConfigManager();
}
if (keyAgreementManager == null) {
keyAgreementManager = new KeyAgreementManager(directories.keyDirectory);
}
return new LaunchServer(directories, env, config, runtimeConfig, launchServerConfigManager, modulesManager, keyAgreementManager, commandHandler, certificateManager);
if(shardId == null) {
shardId = Integer.parseInt(System.getProperty("launchserver.shardId", "0"));
}
return new LaunchServer(directories, env, config, runtimeConfig, launchServerConfigManager, modulesManager, keyAgreementManager, commandHandler, certificateManager, shardId);
}
public LaunchServerBuilder setCertificateManager(CertificateManager certificateManager) {
@ -99,4 +88,26 @@ public LaunchServerBuilder setCertificateManager(CertificateManager certificateM
public void setKeyAgreementManager(KeyAgreementManager keyAgreementManager) {
this.keyAgreementManager = keyAgreementManager;
}
private static class NullLaunchServerConfigManager implements LaunchServer.LaunchServerConfigManager {
@Override
public LaunchServerConfig readConfig() {
throw new UnsupportedOperationException();
}
@Override
public LaunchServerRuntimeConfig readRuntimeConfig() {
throw new UnsupportedOperationException();
}
@Override
public void writeConfig(LaunchServerConfig config) {
throw new UnsupportedOperationException();
}
@Override
public void writeRuntimeConfig(LaunchServerRuntimeConfig config) {
throw new UnsupportedOperationException();
}
}
}

View file

@ -3,13 +3,13 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.LauncherTrustManager;
import pro.gravit.launcher.modules.events.PreConfigPhase;
import pro.gravit.launcher.profiles.optional.actions.OptionalAction;
import pro.gravit.launcher.profiles.optional.triggers.OptionalTrigger;
import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.request.auth.GetAvailabilityAuthRequest;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.core.LauncherTrustManager;
import pro.gravit.launcher.base.modules.events.PreConfigPhase;
import pro.gravit.launcher.base.profiles.optional.actions.OptionalAction;
import pro.gravit.launcher.base.profiles.optional.triggers.OptionalTrigger;
import pro.gravit.launcher.base.request.auth.AuthRequest;
import pro.gravit.launcher.base.request.auth.GetAvailabilityAuthRequest;
import pro.gravit.launchserver.auth.core.AuthCoreProvider;
import pro.gravit.launchserver.auth.mix.MixProvider;
import pro.gravit.launchserver.auth.password.PasswordVerifier;
@ -42,15 +42,10 @@ public class LaunchServerStarter {
private static final Logger logger = LogManager.getLogger();
public static void main(String[] args) throws Exception {
JVMHelper.checkStackTrace(LaunchServerStarter.class);
JVMHelper.verifySystemProperties(LaunchServer.class, true);
JVMHelper.verifySystemProperties(LaunchServer.class, false);
//LogHelper.addOutput(IOHelper.WORKING_DIR.resolve("LaunchServer.log"));
LogHelper.printVersion("LaunchServer");
LogHelper.printLicense("LaunchServer");
if (!StarterAgent.isAgentStarted()) {
LogHelper.error("StarterAgent is not started!");
LogHelper.error("You should add to JVM options this option: `-javaagent:LaunchServer.jar`");
}
Path dir = IOHelper.WORKING_DIR;
Path configFile, runtimeConfigFile;
try {
@ -127,57 +122,7 @@ public static void main(String[] args) throws Exception {
}
}
LaunchServer.LaunchServerConfigManager launchServerConfigManager = new LaunchServer.LaunchServerConfigManager() {
@Override
public LaunchServerConfig readConfig() throws IOException {
LaunchServerConfig config1;
try (BufferedReader reader = IOHelper.newReader(configFile)) {
config1 = Launcher.gsonManager.gson.fromJson(reader, LaunchServerConfig.class);
}
return config1;
}
@Override
public LaunchServerRuntimeConfig readRuntimeConfig() throws IOException {
LaunchServerRuntimeConfig config1;
try (BufferedReader reader = IOHelper.newReader(runtimeConfigFile)) {
config1 = Launcher.gsonManager.gson.fromJson(reader, LaunchServerRuntimeConfig.class);
}
return config1;
}
@Override
public void writeConfig(LaunchServerConfig config) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (Writer writer = IOHelper.newWriter(output)) {
if (Launcher.gsonManager.configGson != null) {
Launcher.gsonManager.configGson.toJson(config, writer);
} else {
logger.error("Error writing LaunchServer config file. Gson is null");
}
}
byte[] bytes = output.toByteArray();
if(bytes.length > 0) {
IOHelper.write(configFile, bytes);
}
}
@Override
public void writeRuntimeConfig(LaunchServerRuntimeConfig config) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (Writer writer = IOHelper.newWriter(output)) {
if (Launcher.gsonManager.configGson != null) {
Launcher.gsonManager.configGson.toJson(config, writer);
} else {
logger.error("Error writing LaunchServer runtime config file. Gson is null");
}
}
byte[] bytes = output.toByteArray();
if(bytes.length > 0) {
IOHelper.write(runtimeConfigFile, bytes);
}
}
};
LaunchServer.LaunchServerConfigManager launchServerConfigManager = new BasicLaunchServerConfigManager(configFile, runtimeConfigFile);
LaunchServer.LaunchServerDirectories directories = new LaunchServer.LaunchServerDirectories();
directories.dir = dir;
LaunchServer server = new LaunchServerBuilder()
@ -289,4 +234,64 @@ public static void generateConfigIfNotExists(Path configFile, CommandHandler com
Launcher.gsonManager.configGson.toJson(newConfig, writer);
}
}
private static class BasicLaunchServerConfigManager implements LaunchServer.LaunchServerConfigManager {
private final Path configFile;
private final Path runtimeConfigFile;
public BasicLaunchServerConfigManager(Path configFile, Path runtimeConfigFile) {
this.configFile = configFile;
this.runtimeConfigFile = runtimeConfigFile;
}
@Override
public LaunchServerConfig readConfig() throws IOException {
LaunchServerConfig config1;
try (BufferedReader reader = IOHelper.newReader(configFile)) {
config1 = Launcher.gsonManager.gson.fromJson(reader, LaunchServerConfig.class);
}
return config1;
}
@Override
public LaunchServerRuntimeConfig readRuntimeConfig() throws IOException {
LaunchServerRuntimeConfig config1;
try (BufferedReader reader = IOHelper.newReader(runtimeConfigFile)) {
config1 = Launcher.gsonManager.gson.fromJson(reader, LaunchServerRuntimeConfig.class);
}
return config1;
}
@Override
public void writeConfig(LaunchServerConfig config) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (Writer writer = IOHelper.newWriter(output)) {
if (Launcher.gsonManager.configGson != null) {
Launcher.gsonManager.configGson.toJson(config, writer);
} else {
logger.error("Error writing LaunchServer config file. Gson is null");
}
}
byte[] bytes = output.toByteArray();
if(bytes.length > 0) {
IOHelper.write(configFile, bytes);
}
}
@Override
public void writeRuntimeConfig(LaunchServerRuntimeConfig config) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (Writer writer = IOHelper.newWriter(output)) {
if (Launcher.gsonManager.configGson != null) {
Launcher.gsonManager.configGson.toJson(config, writer);
} else {
logger.error("Error writing LaunchServer runtime config file. Gson is null");
}
}
byte[] bytes = output.toByteArray();
if(bytes.length > 0) {
IOHelper.write(runtimeConfigFile, bytes);
}
}
}
}

View file

@ -0,0 +1,83 @@
package pro.gravit.launchserver;
import pro.gravit.launchserver.holder.LaunchServerControlHolder;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.launch.ClassLoaderControl;
import pro.gravit.utils.launch.LaunchOptions;
import pro.gravit.utils.launch.ModuleLaunch;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Main {
private static final List<String> classpathOnly = List.of("proguard", "jline", "kotlin", "epoll");
private static final String LOG4J_PROPERTY = "log4j2.configurationFile";
private static boolean isClasspathOnly(Path path) {
var fileName = path.getFileName().toString();
for(var e : classpathOnly) {
if(fileName.contains(e)) {
return true;
}
}
return false;
}
private static void unpackLog4j() {
String log4jConfigurationFile = System.getProperty(LOG4J_PROPERTY);
if(log4jConfigurationFile == null) {
Path log4jConfigPath = Path.of("log4j2.xml");
if(!Files.exists(log4jConfigPath)) {
try(FileOutputStream output = new FileOutputStream(log4jConfigPath.toFile())) {
try(InputStream input = Main.class.getResourceAsStream("/log4j2.xml")) {
if(input == null) {
return;
}
input.transferTo(output);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
System.setProperty(LOG4J_PROPERTY, log4jConfigPath.toAbsolutePath().toString());
}
}
public static void main(String[] args) throws Throwable {
unpackLog4j();
ModuleLaunch launch = new ModuleLaunch();
LaunchOptions options = new LaunchOptions();
options.moduleConf = new LaunchOptions.ModuleConf();
List<Path> libraries;
try(Stream<Path> files = Files.walk(Path.of("libraries"), FileVisitOption.FOLLOW_LINKS)) {
libraries = new ArrayList<>(files.filter(e -> e.getFileName().toString().endsWith(".jar")).toList());
}
List<Path> classpath = new ArrayList<>();
List<String> modulepath = new ArrayList<>();
for(var l : libraries) {
if(isClasspathOnly(l)) {
classpath.add(l);
} else {
modulepath.add(l.toAbsolutePath().toString());
}
}
classpath.add(IOHelper.getCodeSource(LaunchServerStarter.class));
options.moduleConf.modulePath.addAll(modulepath);
options.moduleConf.modules.add("ALL-MODULE-PATH");
ClassLoaderControl control = launch.init(classpath, "natives", options);
control.clearLauncherPackages();
control.addLauncherPackage("pro.gravit.utils.launch");
control.addLauncherPackage("pro.gravit.launchserver.holder");
ModuleLayer.Controller controller = (ModuleLayer.Controller) control.getJava9ModuleController();
LaunchServerControlHolder.setControl(control);
LaunchServerControlHolder.setController(controller);
launch.launch("pro.gravit.launchserver.LaunchServerStarter", null, Arrays.asList(args));
}
}

View file

@ -1,13 +1,7 @@
package pro.gravit.launchserver;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.util.*;
import java.util.jar.JarFile;
public final class StarterAgent {
@ -20,47 +14,6 @@ public static boolean isAgentStarted() {
}
public static void premain(String agentArgument, Instrumentation inst) {
StarterAgent.inst = inst;
libraries = Paths.get(Optional.ofNullable(agentArgument).map(String::trim).filter(e -> !e.isEmpty()).orElse("libraries"));
isStarted = true;
try {
Files.walkFileTree(libraries, Collections.singleton(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new StarterVisitor());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
private static final class StarterVisitor extends SimpleFileVisitor<Path> {
private static final Set<PosixFilePermission> DPERMS;
static {
Set<PosixFilePermission> perms = new HashSet<>(Arrays.asList(PosixFilePermission.values()));
perms.remove(PosixFilePermission.OTHERS_WRITE);
perms.remove(PosixFilePermission.GROUP_WRITE);
DPERMS = Collections.unmodifiableSet(perms);
}
private final boolean fixLib;
private StarterVisitor() {
Path filef = StarterAgent.libraries.resolve(".libraries_chmoded");
this.fixLib = !Files.exists(filef) && !Boolean.getBoolean("launcher.noLibrariesPosixPermsFix");
if (fixLib) {
try {
Files.deleteIfExists(filef);
Files.createFile(filef);
} catch (Throwable ignored) {
}
}
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (fixLib && Files.getFileAttributeView(file, PosixFileAttributeView.class) != null)
Files.setPosixFilePermissions(file, DPERMS);
if (file.toFile().getName().endsWith(".jar"))
inst.appendToSystemClassLoaderSearch(new JarFile(file.toFile()));
return super.visitFile(file, attrs);
}
throw new UnsupportedOperationException("Please remove -javaagent option from start.sh");
}
}

View file

@ -4,8 +4,8 @@
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;
import pro.gravit.launcher.LauncherInject;
import pro.gravit.launcher.LauncherInjectionConstructor;
import pro.gravit.launcher.core.LauncherInject;
import pro.gravit.launcher.core.LauncherInjectionConstructor;
import pro.gravit.launchserver.binary.BuildContext;
import pro.gravit.launchserver.binary.tasks.MainBuildTask;

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.auth;
import pro.gravit.launcher.events.request.AuthRequestEvent;
import pro.gravit.launcher.base.events.request.AuthRequestEvent;
import java.io.IOException;
import java.io.Serial;

View file

@ -57,7 +57,7 @@ public static void getFeatures(Class<?> clazz, Set<String> list) {
}
}
public final <T> T isSupport(Class<T> clazz) {
public <T> T isSupport(Class<T> clazz) {
if (core == null) return null;
T result = core.isSupport(clazz);
if (result == null && mixes != null) {
@ -71,10 +71,10 @@ public final <T> T isSupport(Class<T> clazz) {
return result;
}
public final void init(LaunchServer srv, String name) {
public void init(LaunchServer srv, String name) {
this.name = name;
if (links != null) link(srv);
core.init(srv);
core.init(srv, this);
features = new HashSet<>();
getFeatures(core.getClass(), features);
if(mixes != null) {
@ -85,7 +85,7 @@ public final void init(LaunchServer srv, String name) {
}
}
public final void link(LaunchServer srv) {
public void link(LaunchServer srv) {
links.forEach((k, v) -> {
AuthProviderPair pair = srv.config.getAuthProviderPair(v);
if (pair == null) {
@ -99,7 +99,7 @@ public final void link(LaunchServer srv) {
});
}
public final void close() throws IOException {
public void close() throws IOException {
core.close();
if (textureProvider != null) {
textureProvider.close();

View file

@ -4,13 +4,15 @@
import io.jsonwebtoken.JwtException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.ClientPermissions;
import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.request.auth.password.AuthPlainPassword;
import pro.gravit.launcher.base.ClientPermissions;
import pro.gravit.launcher.base.request.auth.AuthRequest;
import pro.gravit.launcher.base.request.auth.password.AuthPlainPassword;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthException;
import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.auth.MySQLSourceConfig;
import pro.gravit.launchserver.auth.SQLSourceConfig;
import pro.gravit.launchserver.auth.core.interfaces.provider.AuthSupportSudo;
import pro.gravit.launchserver.auth.password.PasswordVerifier;
import pro.gravit.launchserver.helper.LegacySessionHelper;
import pro.gravit.launchserver.manangers.AuthManager;
@ -32,7 +34,7 @@
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.SECONDS;
public abstract class AbstractSQLCoreProvider extends AuthCoreProvider {
public abstract class AbstractSQLCoreProvider extends AuthCoreProvider implements AuthSupportSudo {
public final transient Logger logger = LogManager.getLogger();
public long expireSeconds = HOURS.toSeconds(1);
public String uuidColumn;
@ -66,7 +68,6 @@ public abstract class AbstractSQLCoreProvider extends AuthCoreProvider {
public transient String updateAuthSQL;
public transient String updateServerIDSQL;
public transient LaunchServer server;
public abstract SQLSourceConfig getSQLConfig();
@ -142,14 +143,12 @@ public AuthManager.AuthReport authorize(String login, AuthResponse.AuthContext c
if (user == null) {
throw AuthException.userNotFound();
}
if (context != null) {
AuthPlainPassword plainPassword = (AuthPlainPassword) password;
if (plainPassword == null) {
throw AuthException.wrongPassword();
}
if (!passwordVerifier.check(user.password, plainPassword.password)) {
throw AuthException.wrongPassword();
}
AuthPlainPassword plainPassword = (AuthPlainPassword) password;
if (plainPassword == null) {
throw AuthException.wrongPassword();
}
if (!passwordVerifier.check(user.password, plainPassword.password)) {
throw AuthException.wrongPassword();
}
SQLUserSession session = createSession(user);
var accessToken = LegacySessionHelper.makeAccessJwtTokenFromString(user, LocalDateTime.now(Clock.systemUTC()).plusSeconds(expireSeconds), server.keyAgreementManager.ecdsaPrivateKey);
@ -163,6 +162,17 @@ public AuthManager.AuthReport authorize(String login, AuthResponse.AuthContext c
}
}
@Override
public AuthManager.AuthReport sudo(User user, boolean shadow) throws IOException {
SQLUser sqlUser = (SQLUser) user;
SQLUserSession session = createSession(sqlUser);
var accessToken = LegacySessionHelper.makeAccessJwtTokenFromString(sqlUser, LocalDateTime.now(Clock.systemUTC()).plusSeconds(expireSeconds), server.keyAgreementManager.ecdsaPrivateKey);
var refreshToken = sqlUser.username.concat(".").concat(LegacySessionHelper.makeRefreshTokenFromPassword(sqlUser.username, sqlUser.password, server.keyAgreementManager.legacySalt));
String minecraftAccessToken = SecurityHelper.randomStringToken();
updateAuth(user, minecraftAccessToken);
return AuthManager.AuthReport.ofOAuthWithMinecraft(minecraftAccessToken, accessToken, refreshToken, SECONDS.toMillis(expireSeconds), session);
}
@Override
public User checkServer(Client client, String username, String serverID) throws IOException {
SQLUser user = (SQLUser) getUserByUsername(username);
@ -183,8 +193,8 @@ public boolean joinServer(Client client, String username, UUID uuid, String acce
}
@Override
public void init(LaunchServer server) {
this.server = server;
public void init(LaunchServer server, AuthProviderPair pair) {
super.init(server, pair);
if (getSQLConfig() == null) logger.error("SQLHolder cannot be null");
if (uuidColumn == null) logger.error("uuidColumn cannot be null");
if (usernameColumn == null) logger.error("usernameColumn cannot be null");

View file

@ -3,19 +3,24 @@
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.events.request.GetAvailabilityAuthRequestEvent;
import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.request.auth.details.AuthPasswordDetails;
import pro.gravit.launcher.request.auth.password.AuthPlainPassword;
import pro.gravit.launcher.request.secure.HardwareReportRequest;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.events.RequestEvent;
import pro.gravit.launcher.base.events.request.AuthRequestEvent;
import pro.gravit.launcher.base.events.request.GetAvailabilityAuthRequestEvent;
import pro.gravit.launcher.base.profiles.PlayerProfile;
import pro.gravit.launcher.base.request.auth.AuthRequest;
import pro.gravit.launcher.base.request.auth.details.AuthPasswordDetails;
import pro.gravit.launcher.base.request.auth.password.AuthPlainPassword;
import pro.gravit.launcher.base.request.secure.HardwareReportRequest;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.Reconfigurable;
import pro.gravit.launchserver.auth.AuthException;
import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.auth.core.interfaces.UserHardware;
import pro.gravit.launchserver.auth.core.interfaces.provider.AuthSupportGetAllUsers;
import pro.gravit.launchserver.auth.core.interfaces.provider.AuthSupportHardware;
import pro.gravit.launchserver.auth.core.interfaces.provider.AuthSupportRegistration;
import pro.gravit.launchserver.auth.core.interfaces.provider.AuthSupportSudo;
import pro.gravit.launchserver.manangers.AuthManager;
import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.response.auth.AuthResponse;
@ -29,6 +34,7 @@
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
/*
All-In-One provider
@ -37,6 +43,8 @@ public abstract class AuthCoreProvider implements AutoCloseable, Reconfigurable
public static final ProviderMap<AuthCoreProvider> providers = new ProviderMap<>("AuthCoreProvider");
private static final Logger logger = LogManager.getLogger();
private static boolean registredProviders = false;
protected transient LaunchServer server;
protected transient AuthProviderPair pair;
public static void registerProviders() {
if (!registredProviders) {
@ -71,7 +79,10 @@ public AuthManager.AuthReport authorize(User user, AuthResponse.AuthContext cont
return authorize(user.getUsername(), context, password, minecraftAccess);
}
public abstract void init(LaunchServer server);
public void init(LaunchServer server, AuthProviderPair pair) {
this.server = server;
this.pair = pair;
}
public List<GetAvailabilityAuthRequestEvent.AuthAvailabilityDetails> getDetails(Client client) {
return List.of(new AuthPasswordDetails());
@ -260,6 +271,72 @@ public void invoke(String... args) throws Exception {
});
}
}
{
var instance = isSupport(AuthSupportSudo.class);
if(instance != null) {
map.put("sudo", new SubCommand("[connectUUID] [username/uuid] [isShadow] (CLIENT/API)", "Authorize connectUUID as another user without password") {
@Override
public void invoke(String... args) throws Exception {
verifyArgs(args, 3);
UUID connectUUID = UUID.fromString(args[0]);
String login = args[1];
boolean isShadow = Boolean.parseBoolean(args[2]);
AuthResponse.ConnectTypes type;
if(args.length > 3) {
type = AuthResponse.ConnectTypes.valueOf(args[3]);
} else {
type = AuthResponse.ConnectTypes.CLIENT;
}
User user;
if(login.length() == 36) {
UUID uuid = UUID.fromString(login);
user = getUserByUUID(uuid);
} else {
user = getUserByUsername(login);
}
if(user == null) {
logger.error("User {} not found", login);
return;
}
AtomicBoolean founded = new AtomicBoolean();
server.nettyServerSocketHandler.nettyServer.service.forEachActiveChannels((ch, fh) -> {
var client = fh.getClient();
if(client == null || !connectUUID.equals(fh.getConnectUUID())) {
return;
}
logger.info("Found connectUUID {} with IP {}", fh.getConnectUUID(), fh.context == null ? "null" : fh.context.ip);
var lock = server.config.netty.performance.disableThreadSafeClientObject ? null : client.writeLock();
if(lock != null) {
lock.lock();
}
try {
var report = instance.sudo(user, isShadow);
User user1 = report.session().getUser();
server.authManager.internalAuth(client, type, pair, user1.getUsername(), user1.getUUID(), user1.getPermissions(), true);
client.sessionObject = report.session();
client.coreObject = report.session().getUser();
PlayerProfile playerProfile = server.authManager.getPlayerProfile(client);
AuthRequestEvent request = new AuthRequestEvent(user1.getPermissions(), playerProfile,
report.minecraftAccessToken(), null, null,
new AuthRequestEvent.OAuthRequestEvent(report.oauthAccessToken(), report.oauthRefreshToken(), report.oauthExpire()));
request.requestUUID = RequestEvent.eventUUID;
server.nettyServerSocketHandler.nettyServer.service.sendObject(ch, request);
} catch (Throwable e) {
logger.error("Sudo error", e);
} finally {
if(lock != null) {
lock.unlock();
}
founded.set(true);
}
});
if(!founded.get()) {
logger.error("ConnectUUID {} not found", connectUUID);
}
}
});
}
}
return map;
}

View file

@ -1,11 +1,11 @@
package pro.gravit.launchserver.auth.core;
import pro.gravit.launcher.ClientPermissions;
import pro.gravit.launcher.events.request.GetAvailabilityAuthRequestEvent;
import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.request.auth.details.AuthLoginOnlyDetails;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launcher.base.ClientPermissions;
import pro.gravit.launcher.base.events.request.GetAvailabilityAuthRequestEvent;
import pro.gravit.launcher.base.request.auth.AuthRequest;
import pro.gravit.launcher.base.request.auth.details.AuthLoginOnlyDetails;
import pro.gravit.launchserver.auth.AuthException;
import pro.gravit.launchserver.auth.core.interfaces.provider.AuthSupportSudo;
import pro.gravit.launchserver.manangers.AuthManager;
import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.response.auth.AuthResponse;
@ -18,7 +18,7 @@
import java.util.Objects;
import java.util.UUID;
public class MemoryAuthCoreProvider extends AuthCoreProvider {
public class MemoryAuthCoreProvider extends AuthCoreProvider implements AuthSupportSudo {
private transient final List<MemoryUser> memory = new ArrayList<>(16);
@Override
@ -114,13 +114,13 @@ public boolean joinServer(Client client, String username, UUID uuid, String acce
}
@Override
public void init(LaunchServer server) {
public void close() {
}
@Override
public void close() {
public AuthManager.AuthReport sudo(User user, boolean shadow) throws IOException {
return authorize(user.getUsername(), null, null, true);
}
public static class MemoryUser implements User {

View file

@ -2,9 +2,10 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.base.request.auth.AuthRequest;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthException;
import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.manangers.AuthManager;
import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.response.auth.AuthResponse;
@ -72,7 +73,7 @@ public boolean joinServer(Client client, String username, UUID uuid, String acce
}
@Override
public void init(LaunchServer server) {
public void init(LaunchServer server, AuthProviderPair pair1) {
for(var e : list) {
var pair = server.config.auth.get(e);
if(pair != null) {

View file

@ -1,8 +1,9 @@
package pro.gravit.launchserver.auth.core;
import pro.gravit.launcher.ClientPermissions;
import pro.gravit.launcher.request.secure.HardwareReportRequest;
import pro.gravit.launcher.base.ClientPermissions;
import pro.gravit.launcher.base.request.secure.HardwareReportRequest;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.auth.MySQLSourceConfig;
import pro.gravit.launchserver.auth.SQLSourceConfig;
import pro.gravit.launchserver.auth.core.interfaces.UserHardware;
@ -41,8 +42,8 @@ public SQLSourceConfig getSQLConfig() {
}
@Override
public void init(LaunchServer server) {
super.init(server);
public void init(LaunchServer server, AuthProviderPair pair) {
super.init(server, pair);
String userInfoCols = makeUserCols();
String hardwareInfoCols = "id, hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, graphicCard, banned, publicKey";
if (sqlFindHardwareByPublicKey == null)
@ -332,7 +333,7 @@ public String toString() {
}
}
public class MySQLUser extends SQLUser {
public static class MySQLUser extends SQLUser {
protected long hwidId;
public MySQLUser(UUID uuid, String username, String accessToken, String serverId, String password, ClientPermissions permissions, long hwidId) {

View file

@ -1,7 +1,6 @@
package pro.gravit.launchserver.auth.core;
import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launcher.base.request.auth.AuthRequest;
import pro.gravit.launchserver.auth.AuthException;
import pro.gravit.launchserver.manangers.AuthManager;
import pro.gravit.launchserver.socket.Client;
@ -41,11 +40,6 @@ public AuthManager.AuthReport authorize(String login, AuthResponse.AuthContext c
throw new AuthException("Please configure AuthCoreProvider");
}
@Override
public void init(LaunchServer server) {
}
@Override
public User checkServer(Client client, String username, String serverID) throws IOException {
return null;

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.auth.core;
import pro.gravit.launcher.ClientPermissions;
import pro.gravit.launcher.base.ClientPermissions;
import java.util.UUID;

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.auth.core.interfaces;
import pro.gravit.launcher.request.secure.HardwareReportRequest;
import pro.gravit.launcher.base.request.secure.HardwareReportRequest;
public interface UserHardware {
HardwareReportRequest.HardwareInfo getHardwareInfo();

View file

@ -1,8 +1,8 @@
package pro.gravit.launchserver.auth.core.interfaces.provider;
import pro.gravit.launcher.events.request.AssetUploadInfoRequestEvent;
import pro.gravit.launcher.events.request.AuthRequestEvent;
import pro.gravit.launcher.events.request.GetAssetUploadUrlRequestEvent;
import pro.gravit.launcher.base.events.request.AssetUploadInfoRequestEvent;
import pro.gravit.launcher.base.events.request.AuthRequestEvent;
import pro.gravit.launcher.base.events.request.GetAssetUploadUrlRequestEvent;
import pro.gravit.launchserver.auth.Feature;
import pro.gravit.launchserver.auth.core.User;

View file

@ -1,6 +1,5 @@
package pro.gravit.launchserver.auth.core.interfaces.provider;
import pro.gravit.launchserver.auth.core.User;
import pro.gravit.launchserver.auth.core.UserSession;
import pro.gravit.launchserver.socket.Client;

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.auth.core.interfaces.provider;
import pro.gravit.launcher.request.secure.HardwareReportRequest;
import pro.gravit.launcher.base.request.secure.HardwareReportRequest;
import pro.gravit.launchserver.auth.core.User;
import pro.gravit.launchserver.auth.core.UserSession;
import pro.gravit.launchserver.auth.core.interfaces.UserHardware;

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.auth.core.interfaces.provider;
import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.base.request.auth.AuthRequest;
import pro.gravit.launchserver.auth.Feature;
import pro.gravit.launchserver.auth.core.User;

View file

@ -0,0 +1,10 @@
package pro.gravit.launchserver.auth.core.interfaces.provider;
import pro.gravit.launchserver.auth.core.User;
import pro.gravit.launchserver.manangers.AuthManager;
import java.io.IOException;
public interface AuthSupportSudo {
AuthManager.AuthReport sudo(User user, boolean shadow) throws IOException;
}

View file

@ -1,7 +1,7 @@
package pro.gravit.launchserver.auth.core.interfaces.user;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.profiles.Texture;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launcher.base.profiles.Texture;
import java.util.HashMap;
import java.util.Map;

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.auth.mix;
import pro.gravit.launcher.events.request.AssetUploadInfoRequestEvent;
import pro.gravit.launcher.base.events.request.AssetUploadInfoRequestEvent;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.core.AuthCoreProvider;
import pro.gravit.launchserver.auth.core.User;

View file

@ -2,7 +2,7 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.base.Launcher;
import java.io.InputStream;
import java.io.InputStreamReader;

View file

@ -4,9 +4,9 @@
import io.jsonwebtoken.Jwts;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.events.request.GetSecureLevelInfoRequestEvent;
import pro.gravit.launcher.events.request.HardwareReportRequestEvent;
import pro.gravit.launcher.events.request.VerifySecureLevelKeyRequestEvent;
import pro.gravit.launcher.base.events.request.GetSecureLevelInfoRequestEvent;
import pro.gravit.launcher.base.events.request.HardwareReportRequestEvent;
import pro.gravit.launcher.base.events.request.VerifySecureLevelKeyRequestEvent;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.auth.core.interfaces.UserHardware;
@ -132,9 +132,9 @@ public static class HardwareInfoTokenVerifier implements RestoreResponse.Extende
private final JwtParser parser;
public HardwareInfoTokenVerifier(LaunchServer server) {
this.parser = Jwts.parserBuilder()
this.parser = Jwts.parser()
.requireIssuer("LaunchServer")
.setSigningKey(server.keyAgreementManager.ecdsaPublicKey)
.verifyWith(server.keyAgreementManager.ecdsaPublicKey)
.build();
}
@ -164,9 +164,9 @@ public static class PublicKeyTokenVerifier implements RestoreResponse.ExtendedTo
private final JwtParser parser;
public PublicKeyTokenVerifier(LaunchServer server) {
this.parser = Jwts.parserBuilder()
this.parser = Jwts.parser()
.requireIssuer("LaunchServer")
.setSigningKey(server.keyAgreementManager.ecdsaPublicKey)
.verifyWith(server.keyAgreementManager.ecdsaPublicKey)
.build();
}

View file

@ -2,7 +2,7 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.protect.interfaces.ProfilesProtectHandler;
import pro.gravit.launchserver.socket.Client;
@ -22,7 +22,7 @@ public boolean allowGetAccessToken(AuthResponse.AuthContext context) {
@Override
public void init(LaunchServer server) {
if (profileWhitelist != null && profileWhitelist.size() > 0) {
if (profileWhitelist != null && !profileWhitelist.isEmpty()) {
logger.warn("profileWhitelist deprecated. Please use permission 'launchserver.profile.PROFILE_UUID.show' and 'launchserver.profile.PROFILE_UUID.enter'");
}
}

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.auth.protect.interfaces;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.socket.Client;
public interface ProfilesProtectHandler {

View file

@ -1,8 +1,8 @@
package pro.gravit.launchserver.auth.protect.interfaces;
import pro.gravit.launcher.events.request.GetSecureLevelInfoRequestEvent;
import pro.gravit.launcher.events.request.SecurityReportRequestEvent;
import pro.gravit.launcher.events.request.VerifySecureLevelKeyRequestEvent;
import pro.gravit.launcher.base.events.request.GetSecureLevelInfoRequestEvent;
import pro.gravit.launcher.base.events.request.SecurityReportRequestEvent;
import pro.gravit.launcher.base.events.request.VerifySecureLevelKeyRequestEvent;
import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.response.secure.SecurityReportResponse;
import pro.gravit.utils.helper.SecurityHelper;

View file

@ -3,7 +3,7 @@
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.profiles.Texture;
import pro.gravit.launcher.base.profiles.Texture;
import pro.gravit.launchserver.HttpRequester;
import pro.gravit.utils.helper.SecurityHelper;

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.auth.texture;
import pro.gravit.launcher.profiles.Texture;
import pro.gravit.launcher.base.profiles.Texture;
import pro.gravit.utils.helper.VerifyHelper;
import java.io.IOException;

View file

@ -1,7 +1,7 @@
package pro.gravit.launchserver.auth.texture;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.profiles.Texture;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.profiles.Texture;
import pro.gravit.utils.helper.CommonHelper;
import pro.gravit.utils.helper.IOHelper;

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.auth.texture;
import pro.gravit.launcher.profiles.Texture;
import pro.gravit.launcher.base.profiles.Texture;
import pro.gravit.utils.ProviderMap;
import java.io.IOException;

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.auth.texture;
import pro.gravit.launcher.profiles.Texture;
import pro.gravit.launcher.base.profiles.Texture;
import java.util.UUID;

View file

@ -7,12 +7,10 @@
import pro.gravit.utils.helper.IOHelper;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Predicate;
import java.util.stream.Collectors;

View file

@ -2,9 +2,9 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.serialize.HOutput;
import pro.gravit.launcher.serialize.stream.StreamObject;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.core.serialize.HOutput;
import pro.gravit.launcher.core.serialize.stream.StreamObject;
import pro.gravit.launchserver.binary.tasks.MainBuildTask;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.SecurityHelper;
@ -46,11 +46,14 @@ public class BuildContext {
public final HashSet<String> fileList;
public final HashSet<String> clientModules;
public final HashSet<String> legacyClientModules;
private Path runtimeDir;
private boolean deleteRuntimeDir;
public BuildContext(ZipOutputStream output, List<JarFile> readerClassPath, MainBuildTask task) {
public BuildContext(ZipOutputStream output, List<JarFile> readerClassPath, MainBuildTask task, Path runtimeDir) {
this.output = output;
this.readerClassPath = readerClassPath;
this.task = task;
this.runtimeDir = runtimeDir;
fileList = new HashSet<>(1024);
clientModules = new HashSet<>();
legacyClientModules = new HashSet<>();
@ -103,6 +106,14 @@ public void pushJarFile(Path jarfile, Predicate<ZipEntry> filter, Predicate<Stri
pushJarFile(jarfile.toUri().toURL(), filter, needTransform);
}
public Path getRuntimeDir() {
return runtimeDir;
}
public void setRuntimeDir(Path runtimeDir) {
this.runtimeDir = runtimeDir;
}
public void pushJarFile(URL jarfile, Predicate<ZipEntry> filter, Predicate<String> needTransform) throws IOException {
try (ZipInputStream input = new ZipInputStream(IOHelper.newInput(jarfile))) {
ZipEntry e = input.getNextEntry();
@ -129,6 +140,16 @@ public void pushJarFile(URL jarfile, Predicate<ZipEntry> filter, Predicate<Strin
e = input.getNextEntry();
}
}
}
public boolean isDeleteRuntimeDir() {
return deleteRuntimeDir;
}
public void setDeleteRuntimeDir(boolean deleteRuntimeDir) {
this.deleteRuntimeDir = deleteRuntimeDir;
}
private final static class RuntimeDirVisitor extends SimpleFileVisitor<Path> {

View file

@ -1,17 +0,0 @@
package pro.gravit.launchserver.binary;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.binary.tasks.exe.Launch4JTask;
public final class EXEL4JLauncherBinary extends LauncherBinary {
public EXEL4JLauncherBinary(LaunchServer server) {
super(server, LauncherBinary.resolve(server, ".exe"), "Launcher-%s.exe");
}
@Override
public void init() {
tasks.add(new Launch4JTask(server));
}
}

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.binary;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.binary.tasks.*;

View file

@ -8,8 +8,8 @@
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.LauncherConfig;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.LauncherConfig;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.asm.ClassMetadataReader;
import pro.gravit.launchserver.asm.InjectClassAcceptor;
@ -53,7 +53,7 @@ public String getName() {
public Path process(Path inputJar) throws IOException {
Path outputJar = server.launcherBinary.nextPath(this);
try (ZipOutputStream output = new ZipOutputStream(IOHelper.newOutput(outputJar))) {
BuildContext context = new BuildContext(output, reader.getCp(), this);
BuildContext context = new BuildContext(output, reader.getCp(), this, server.launcherBinary.runtimeDir);
initProps();
preBuildHook.hook(context);
properties.put("launcher.legacymodules", context.legacyClientModules.stream().map(e -> Type.getObjectType(e.replace('.', '/'))).collect(Collectors.toList()));
@ -69,9 +69,12 @@ public Path process(Path inputJar) throws IOException {
Map<String, byte[]> runtime = new HashMap<>(256);
// Write launcher guard dir
if (server.config.launcher.encryptRuntime) {
context.pushEncryptedDir(server.launcherBinary.runtimeDir, Launcher.RUNTIME_DIR, server.runtime.runtimeEncryptKey, runtime, false);
context.pushEncryptedDir(context.getRuntimeDir(), Launcher.RUNTIME_DIR, server.runtime.runtimeEncryptKey, runtime, false);
} else {
context.pushDir(server.launcherBinary.runtimeDir, Launcher.RUNTIME_DIR, runtime, false);
context.pushDir(context.getRuntimeDir(), Launcher.RUNTIME_DIR, runtime, false);
}
if(context.isDeleteRuntimeDir()) {
IOHelper.deleteDir(context.getRuntimeDir(), true);
}
LauncherConfig launcherConfig = new LauncherConfig(server.config.netty.address, server.keyAgreementManager.ecdsaPublicKey, server.keyAgreementManager.rsaPublicKey, runtime, server.config.projectName);

View file

@ -1,125 +0,0 @@
package pro.gravit.launchserver.binary.tasks.exe;
import net.sf.launch4j.Builder;
import net.sf.launch4j.Log;
import net.sf.launch4j.config.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.binary.tasks.LauncherBuildTask;
import pro.gravit.utils.Version;
import pro.gravit.utils.helper.IOHelper;
import java.io.IOException;
import java.nio.file.Path;
public class Launch4JTask implements LauncherBuildTask, BuildExeMainTask {
public static final String DOWNLOAD_URL = "https://bell-sw.com/pages/downloads/?version=java-8-lts&os=Windows&package=jre-full"; // BellSoft
private static final String VERSION = Version.getVersion().getVersionString();
private static final int BUILD = Version.getVersion().build;
private final Path faviconFile;
private final LaunchServer server;
private transient final Logger logger = LogManager.getLogger();
public Launch4JTask(LaunchServer launchServer) {
this.server = launchServer;
faviconFile = launchServer.dir.resolve("favicon.ico");
}
public static String formatVars(String mask) {
return mask.formatted(VERSION, BUILD);
}
@Override
public String getName() {
return "launch4j";
}
@Override
public Path process(Path inputFile) throws IOException {
logger.info("Building launcher EXE binary file (Using Launch4J)");
Path output = setConfig();
// Set favicon path
Config config = ConfigPersister.getInstance().getConfig();
if (IOHelper.isFile(faviconFile))
config.setIcon(faviconFile.toFile());
else {
config.setIcon(null);
logger.warn("Missing favicon.ico file");
}
// Start building
Builder builder = new Builder(Launch4JLog.INSTANCE);
try {
builder.build();
} catch (Throwable e) {
throw new IOException(e);
}
return output;
}
private Path setConfig() {
Path path = server.launcherEXEBinary.nextPath(getName());
Config config = new Config();
// Set file options
config.setChdir(".");
config.setErrTitle("JVM Error");
config.setDownloadUrl(server.config.launch4j.downloadUrl);
if (server.config.launch4j.supportURL != null) config.setSupportUrl(server.config.launch4j.supportURL);
// Set boolean options
config.setPriorityIndex(0);
config.setHeaderType(Config.GUI_HEADER);
config.setStayAlive(false);
config.setRestartOnCrash(false);
// Prepare JRE
Jre jre = new Jre();
jre.setMinVersion(server.config.launch4j.minVersion);
if (server.config.launch4j.setMaxVersion)
jre.setMaxVersion(server.config.launch4j.maxVersion);
jre.setPath(System.getProperty("java.home"));
config.setJre(jre);
// Prepare version info (product)
VersionInfo info = new VersionInfo();
info.setProductName(server.config.launch4j.productName);
info.setProductVersion(formatVars(server.config.launch4j.productVer));
info.setFileDescription(server.config.launch4j.fileDesc);
info.setFileVersion(formatVars(server.config.launch4j.fileVer));
info.setCopyright(server.config.launch4j.copyright);
info.setTrademarks(server.config.launch4j.trademarks);
info.setInternalName(formatVars(server.config.launch4j.internalName));
// Prepare version info (file)
info.setTxtFileVersion(formatVars(server.config.launch4j.txtFileVersion));
info.setTxtProductVersion(formatVars(server.config.launch4j.txtProductVersion));
// Prepare version info (misc)
info.setOriginalFilename(path.getFileName().toString());
info.setLanguage(LanguageID.RUSSIAN);
config.setVersionInfo(info);
// Set JAR wrapping options
config.setDontWrapJar(false);
config.setJar(server.launcherBinary.syncBinaryFile.toFile());
config.setOutfile(path.toFile());
// Return prepared config
ConfigPersister.getInstance().setAntConfig(config, null);
return path;
}
private final static class Launch4JLog extends Log {
private static final Launch4JLog INSTANCE = new Launch4JLog();
private static final Logger logger = LogManager.getLogger();
@Override
public void append(String s) {
logger.info(s);
}
@Override
public void clear() {
// Do nothing
}
}
}

View file

@ -3,9 +3,9 @@
import me.tongfei.progressbar.ProgressBar;
import me.tongfei.progressbar.ProgressBarBuilder;
import me.tongfei.progressbar.ProgressBarStyle;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.modern.Downloader;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.Downloader;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.utils.command.CommandException;
@ -47,6 +47,9 @@ protected boolean showApplyDialog(String text) throws IOException {
protected Downloader downloadWithProgressBar(String taskName, List<Downloader.SizedFile> list, String baseUrl, Path targetDir) throws Exception {
long total = 0;
for (Downloader.SizedFile file : list) {
if(file.size < 0) {
continue;
}
total += file.size;
}
long totalFiles = list.size();

View file

@ -1,25 +0,0 @@
package pro.gravit.launchserver.command.basic;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
public final class RestartCommand extends Command {
public RestartCommand(LaunchServer server) {
super(server);
}
@Override
public String getArgsDescription() {
return null;
}
@Override
public String getUsageDescription() {
return "Restart LaunchServer";
}
@Override
public void invoke(String... args) {
server.fullyRestart();
}
}

View file

@ -5,7 +5,11 @@
import pro.gravit.launchserver.command.hash.*;
import pro.gravit.launchserver.command.modules.LoadModuleCommand;
import pro.gravit.launchserver.command.modules.ModulesCommand;
import pro.gravit.launchserver.command.profiles.ProfilesCommand;
import pro.gravit.launchserver.command.service.*;
import pro.gravit.launchserver.command.sync.*;
import pro.gravit.launchserver.command.tools.SignDirCommand;
import pro.gravit.launchserver.command.tools.SignJarCommand;
import pro.gravit.utils.command.BaseCommandCategory;
import pro.gravit.utils.command.basic.ClearCommand;
import pro.gravit.utils.command.basic.GCCommand;
@ -19,7 +23,6 @@ public static void registerCommands(pro.gravit.utils.command.CommandHandler hand
basic.registerCommand("version", new VersionCommand(server));
basic.registerCommand("build", new BuildCommand(server));
basic.registerCommand("stop", new StopCommand(server));
basic.registerCommand("restart", new RestartCommand(server));
basic.registerCommand("debug", new DebugCommand(server));
basic.registerCommand("clear", new ClearCommand(handler));
basic.registerCommand("gc", new GCCommand());
@ -34,12 +37,8 @@ public static void registerCommands(pro.gravit.utils.command.CommandHandler hand
updates.registerCommand("unindexAsset", new UnindexAssetCommand(server));
updates.registerCommand("downloadAsset", new DownloadAssetCommand(server));
updates.registerCommand("downloadClient", new DownloadClientCommand(server));
updates.registerCommand("syncBinaries", new SyncBinariesCommand(server));
updates.registerCommand("syncUpdates", new SyncUpdatesCommand(server));
updates.registerCommand("syncProfiles", new SyncProfilesCommand(server));
updates.registerCommand("syncUP", new SyncUPCommand(server));
updates.registerCommand("saveProfiles", new SaveProfilesCommand(server));
updates.registerCommand("makeProfile", new MakeProfileCommand(server));
updates.registerCommand("sync", new SyncCommand(server));
updates.registerCommand("profile", new ProfilesCommand(server));
Category updatesCategory = new Category(updates, "updates", "Update and Sync Management");
handler.registerCategory(updatesCategory);
@ -50,11 +49,16 @@ public static void registerCommands(pro.gravit.utils.command.CommandHandler hand
service.registerCommand("notify", new NotifyCommand(server));
service.registerCommand("component", new ComponentCommand(server));
service.registerCommand("clients", new ClientsCommand(server));
service.registerCommand("signJar", new SignJarCommand(server));
service.registerCommand("signDir", new SignDirCommand(server));
service.registerCommand("securitycheck", new SecurityCheckCommand(server));
service.registerCommand("token", new TokenCommand(server));
Category serviceCategory = new Category(service, "service", "Managing LaunchServer Components");
handler.registerCategory(serviceCategory);
//Register tools commands
BaseCommandCategory tools = new BaseCommandCategory();
tools.registerCommand("signJar", new SignJarCommand(server));
tools.registerCommand("signDir", new SignDirCommand(server));
Category toolsCategory = new Category(tools, "tools", "Other tools");
handler.registerCategory(toolsCategory);
}
}

View file

@ -3,8 +3,8 @@
import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.modern.Downloader;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.Downloader;
import pro.gravit.launchserver.HttpRequester;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;

View file

@ -3,9 +3,9 @@
import com.google.gson.JsonElement;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.profiles.ClientProfileVersions;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launcher.base.profiles.ClientProfileVersions;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.helper.MakeProfileHelper;

View file

@ -3,7 +3,7 @@
import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.command.CommandException;

View file

@ -2,9 +2,9 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.LauncherTrustManager;
import pro.gravit.launcher.modules.LauncherModule;
import pro.gravit.launcher.modules.LauncherModuleInfo;
import pro.gravit.launcher.core.LauncherTrustManager;
import pro.gravit.launcher.base.modules.LauncherModule;
import pro.gravit.launcher.base.modules.LauncherModuleInfo;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.launchermodules.LauncherModuleLoader;

View file

@ -0,0 +1,73 @@
package pro.gravit.launchserver.command.profiles;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.IOHelper;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;
public class CloneProfileCommand extends Command {
private final transient Logger logger = LogManager.getLogger(CloneProfileCommand.class);
public CloneProfileCommand(LaunchServer server) {
super(server);
}
@Override
public String getArgsDescription() {
return "[profile file name] [new profile title]";
}
@Override
public String getUsageDescription() {
return "clone profile and profile dir";
}
@Override
public void invoke(String... args) throws Exception {
verifyArgs(args, 2);
var profilePath = server.profilesDir.resolve(args[0].concat(".json"));
if(!Files.exists(profilePath)) {
logger.error("File {} not found", profilePath);
}
ClientProfile profile;
try(Reader reader = IOHelper.newReader(profilePath)) {
profile = Launcher.gsonManager.gson.fromJson(reader, ClientProfile.class);
}
profile.setTitle(args[1]);
profile.setUUID(UUID.randomUUID());
if(profile.getServers().size() == 1) {
profile.getServers().getFirst().name = args[1];
}
logger.info("Copy {} to {}", profile.getDir(), args[1]);
var src = server.updatesDir.resolve(profile.getDir());
var dest = server.updatesDir.resolve(args[1]);
try (Stream<Path> stream = Files.walk(src)) {
stream.forEach(source -> {
try {
IOHelper.copy(source, dest.resolve(src.relativize(source)));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
profile.setDir(args[1]);
var targetPath = server.profilesDir.resolve(args[1].concat(".json"));
try(Writer writer = IOHelper.newWriter(targetPath)) {
Launcher.gsonManager.gson.toJson(profile, writer);
}
logger.info("Profile {} cloned from {}", args[1], args[0]);
server.syncProfilesDir();
server.syncUpdatesDir(List.of(args[1]));
}
}

View file

@ -0,0 +1,56 @@
package pro.gravit.launchserver.command.profiles;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.IOHelper;
import java.nio.file.Files;
public class DeleteProfileCommand extends Command {
private final transient Logger logger = LogManager.getLogger(ListProfilesCommand.class);
public DeleteProfileCommand(LaunchServer server) {
super(server);
}
@Override
public String getArgsDescription() {
return "[uuid/title]";
}
@Override
public String getUsageDescription() {
return "permanently delete profile";
}
@Override
public void invoke(String... args) throws Exception {
verifyArgs(args, 1);
ClientProfile profile = null;
for(var p : server.getProfiles()) {
if(p.getUUID().toString().equals(args[0]) || p.getTitle().equals(args[0])) {
profile = p;
break;
}
}
if(profile == null) {
logger.error("Profile {} not found", args[0]);
return;
}
var clientDir = server.updatesDir.resolve(profile.getDir()).toAbsolutePath();
logger.warn("THIS ACTION DELETE PROFILE AND ALL FILES IN {}", clientDir);
if(!showApplyDialog("Continue?")) {
return;
}
logger.info("Delete {}", clientDir);
IOHelper.deleteDir(clientDir, true);
var profileFile = profile.getProfileFilePath();
if(profileFile == null) {
profileFile = server.profilesDir.resolve(profile.getTitle().concat(".json"));
}
logger.info("Delete {}", profileFile);
Files.deleteIfExists(profileFile);
}
}

View file

@ -0,0 +1,30 @@
package pro.gravit.launchserver.command.profiles;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
public class ListProfilesCommand extends Command {
private final transient Logger logger = LogManager.getLogger(ListProfilesCommand.class);
public ListProfilesCommand(LaunchServer server) {
super(server);
}
@Override
public String getArgsDescription() {
return null;
}
@Override
public String getUsageDescription() {
return "show all profiles";
}
@Override
public void invoke(String... args) throws Exception {
for(var profile : server.getProfiles()) {
logger.info("{} ({}) {}", profile.getTitle(), profile.getVersion().toString(), profile.isLimited() ? "limited" : "");
}
}
}

View file

@ -1,9 +1,9 @@
package pro.gravit.launchserver.command.hash;
package pro.gravit.launchserver.command.profiles;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.helper.MakeProfileHelper;

View file

@ -0,0 +1,30 @@
package pro.gravit.launchserver.command.profiles;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
public class ProfilesCommand extends Command {
public ProfilesCommand(LaunchServer server) {
super(server);
this.childCommands.put("make", new MakeProfileCommand(server));
this.childCommands.put("save", new SaveProfilesCommand(server));
this.childCommands.put("clone", new CloneProfileCommand(server));
this.childCommands.put("list", new ListProfilesCommand(server));
this.childCommands.put("delete", new DeleteProfileCommand(server));
}
@Override
public String getArgsDescription() {
return "[subcommand] [args...]";
}
@Override
public String getUsageDescription() {
return "manage profiles";
}
@Override
public void invoke(String... args) throws Exception {
invokeSubcommands(args);
}
}

View file

@ -1,9 +1,9 @@
package pro.gravit.launchserver.command.hash;
package pro.gravit.launchserver.command.profiles;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.utils.helper.IOHelper;
@ -24,7 +24,7 @@ public SaveProfilesCommand(LaunchServer server) {
public static void saveProfile(ClientProfile profile, Path path) throws IOException {
if (profile.getUUID() == null) profile.setUUID(UUID.randomUUID());
if (profile.getServers().size() == 0) {
if (profile.getServers().isEmpty()) {
ClientProfile.ServerProfile serverProfile = new ClientProfile.ServerProfile();
serverProfile.isDefault = true;
serverProfile.name = profile.getTitle();

View file

@ -2,7 +2,7 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.components.Component;
@ -37,7 +37,6 @@ public void printHelp() {
logger.info("Print help for component:");
logger.info("component unload [componentName]");
logger.info("component load [componentName] [filename]");
logger.info("component gc [componentName]");
}
@Override

View file

@ -1,7 +1,7 @@
package pro.gravit.launchserver.command.service;
import pro.gravit.launcher.events.NotificationEvent;
import pro.gravit.launcher.request.WebSocketEvent;
import pro.gravit.launcher.base.events.NotificationEvent;
import pro.gravit.launcher.base.request.WebSocketEvent;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.socket.WebSocketService;

View file

@ -2,7 +2,7 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.protect.AdvancedProtectHandler;
import pro.gravit.launchserver.auth.protect.NoProtectHandler;
@ -60,19 +60,19 @@ public void invoke(String... args) {
LaunchServerConfig config = server.config;
config.auth.forEach((name, pair) -> {
});
if (config.protectHandler instanceof NoProtectHandler) {
printCheckResult("protectHandler", "protectHandler none", false);
} else if (config.protectHandler instanceof AdvancedProtectHandler) {
printCheckResult("protectHandler", "", true);
if (!((AdvancedProtectHandler) config.protectHandler).enableHardwareFeature) {
printCheckResult("protectHandler.hardwareId", "you can improve security by using hwid provider", null);
} else {
printCheckResult("protectHandler.hardwareId", "", true);
switch (config.protectHandler) {
case NoProtectHandler noProtectHandler -> printCheckResult("protectHandler", "protectHandler none", false);
case AdvancedProtectHandler advancedProtectHandler -> {
printCheckResult("protectHandler", "", true);
if (!advancedProtectHandler.enableHardwareFeature) {
printCheckResult("protectHandler.hardwareId", "you can improve security by using hwid provider", null);
} else {
printCheckResult("protectHandler.hardwareId", "", true);
}
}
} else if (config.protectHandler instanceof StdProtectHandler) {
printCheckResult("protectHandler", "you can improve security by using advanced", null);
} else {
printCheckResult("protectHandler", "unknown protectHandler", null);
case StdProtectHandler stdProtectHandler ->
printCheckResult("protectHandler", "you can improve security by using advanced", null);
case null, default -> printCheckResult("protectHandler", "unknown protectHandler", null);
}
if (config.netty.address.startsWith("ws://")) {
if (config.netty.ipForwarding)
@ -110,7 +110,7 @@ public void invoke(String... args) {
KeyStore keyStore = SignHelper.getStore(new File(config.sign.keyStore).toPath(), config.sign.keyStorePass, config.sign.keyStoreType);
Certificate[] certChainPlain = keyStore.getCertificateChain(config.sign.keyAlias);
List<X509Certificate> certChain = Arrays.stream(certChainPlain).map(e -> (X509Certificate) e).toList();
X509Certificate cert = certChain.get(0);
X509Certificate cert = certChain.getFirst();
cert.checkValidity();
if (certChain.size() == 1) {
printCheckResult("sign", "certificate chain contains <2 element(recommend 2 and more)", false);

View file

@ -3,7 +3,7 @@
import io.jsonwebtoken.Jwts;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.command.Command;
@ -18,15 +18,16 @@ public TokenCommand(LaunchServer server) {
@Override
public void invoke(String... args) throws Exception {
verifyArgs(args, 1);
var parser = Jwts.parserBuilder().setSigningKey(server.keyAgreementManager.ecdsaPublicKey).build();
var claims = parser.parseClaimsJws(args[0]);
logger.info("Token: {}", claims.getBody());
var parser = Jwts.parser().verifyWith(server.keyAgreementManager.ecdsaPublicKey).build();
var claims = parser.parseSignedClaims(args[0]);
logger.info("Token: {}", claims.getPayload());
}
});
this.childCommands.put("server", new SubCommand("[profileName] (authId)", "generate new server token") {
this.childCommands.put("server", new SubCommand("[profileName] (authId) (public only)", "generate new server token") {
@Override
public void invoke(String... args) {
AuthProviderPair pair = args.length > 1 ? server.config.getAuthProviderPair(args[1]) : server.config.getAuthProviderPair();
boolean publicOnly = args.length <= 2 || Boolean.parseBoolean(args[2]);
ClientProfile profile = null;
for (ClientProfile p : server.getProfiles()) {
if (p.getTitle().equals(args[0]) || p.getUUID().toString().equals(args[0])) {
@ -41,7 +42,7 @@ public void invoke(String... args) {
logger.error("AuthId {} not found", args[1]);
return;
}
String token = server.authManager.newCheckServerToken(profile != null ? profile.getUUID().toString() : args[0], pair.name);
String token = server.authManager.newCheckServerToken(profile != null ? profile.getUUID().toString() : args[0], pair.name, publicOnly);
logger.info("Server token {} authId {}: {}", args[0], pair.name, token);
}
});

View file

@ -1,4 +1,4 @@
package pro.gravit.launchserver.command.hash;
package pro.gravit.launchserver.command.sync;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

View file

@ -0,0 +1,31 @@
package pro.gravit.launchserver.command.sync;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
public class SyncCommand extends Command {
public SyncCommand(LaunchServer server) {
super(server);
this.childCommands.put("profiles", new SyncProfilesCommand(server));
this.childCommands.put("binaries", new SyncBinariesCommand(server));
this.childCommands.put("updates", new SyncUpdatesCommand(server));
this.childCommands.put("up", new SyncUPCommand(server));
this.childCommands.put("launchermodules", new SyncLauncherModulesCommand(server));
this.childCommands.put("updatescache", new SyncUpdatesCacheCommand(server));
}
@Override
public String getArgsDescription() {
return "[updates/profiles/up/binaries/launchermodules/updatescache] [args...]";
}
@Override
public String getUsageDescription() {
return "sync specified objects";
}
@Override
public void invoke(String... args) throws Exception {
invokeSubcommands(args);
}
}

View file

@ -1,31 +1,31 @@
package pro.gravit.launchserver.launchermodules;
package pro.gravit.launchserver.command.sync;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.utils.command.Command;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
public class SyncLauncherModulesCommand extends Command {
private final LauncherModuleLoader mod;
private transient final Logger logger = LogManager.getLogger();
public SyncLauncherModulesCommand(LauncherModuleLoader mod) {
this.mod = mod;
public SyncLauncherModulesCommand(LaunchServer server) {
super(server);
}
@Override
public String getArgsDescription() {
return "Resync launcher modules";
return null;
}
@Override
public String getUsageDescription() {
return "[]";
return "Resync launcher modules";
}
@Override
public void invoke(String... args) throws Exception {
mod.syncModules();
server.launcherModuleLoader.syncModules();
logger.info("Launcher Modules synced");
}
}

View file

@ -1,4 +1,4 @@
package pro.gravit.launchserver.command.hash;
package pro.gravit.launchserver.command.sync;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

View file

@ -1,4 +1,4 @@
package pro.gravit.launchserver.command.hash;
package pro.gravit.launchserver.command.sync;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

View file

@ -0,0 +1,25 @@
package pro.gravit.launchserver.command.sync;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
public class SyncUpdatesCacheCommand extends Command {
public SyncUpdatesCacheCommand(LaunchServer server) {
super(server);
}
@Override
public String getArgsDescription() {
return null;
}
@Override
public String getUsageDescription() {
return "sync updates cache";
}
@Override
public void invoke(String... args) throws Exception {
server.updatesManager.readUpdatesFromCache();
}
}

View file

@ -1,4 +1,4 @@
package pro.gravit.launchserver.command.hash;
package pro.gravit.launchserver.command.sync;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

View file

@ -1,4 +1,4 @@
package pro.gravit.launchserver.command.service;
package pro.gravit.launchserver.command.tools;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

View file

@ -1,4 +1,4 @@
package pro.gravit.launchserver.command.service;
package pro.gravit.launchserver.command.tools;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

View file

@ -90,7 +90,7 @@ public boolean check(T address) {
}
}
static class LimitEntry {
protected static class LimitEntry {
long time;
int trys;

View file

@ -11,7 +11,6 @@ public abstract class Component {
public static void registerComponents() {
if (!registredComp) {
providers.register("authLimiter", AuthLimiterComponent.class);
providers.register("regLimiter", RegLimiterComponent.class);
providers.register("commandRemover", CommandRemoverComponent.class);
providers.register("proguard", ProGuardComponent.class);
providers.register("whitelist", WhitelistComponent.class);

View file

@ -9,7 +9,6 @@
import pro.gravit.utils.command.SubCommand;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.JVMHelper;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper;
import pro.gravit.utils.helper.UnpackHelper;
@ -20,7 +19,6 @@
import java.nio.file.Paths;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

View file

@ -1,34 +0,0 @@
package pro.gravit.launchserver.components;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.manangers.hook.AuthHookManager;
import pro.gravit.utils.HookException;
import java.util.ArrayList;
import java.util.List;
public class RegLimiterComponent extends IPLimiter implements AutoCloseable {
public transient LaunchServer launchServer;
public String message;
public List<String> excludeIps = new ArrayList<>();
@Override
public void init(LaunchServer launchServer) {
this.launchServer = launchServer;
launchServer.authHookManager.registraion.registerHook(this::registerHook);
}
public boolean registerHook(AuthHookManager.RegContext context) {
if (!check(context.ip)) {
throw new HookException(message);
}
return false;
}
@Override
public void close() {
launchServer.authHookManager.registraion.unregisterHook(this::registerHook);
}
}

View file

@ -4,30 +4,27 @@
import io.netty.handler.logging.LogLevel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.LauncherConfig;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.LauncherConfig;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.auth.core.RejectAuthCoreProvider;
import pro.gravit.launchserver.auth.protect.ProtectHandler;
import pro.gravit.launchserver.auth.protect.StdProtectHandler;
import pro.gravit.launchserver.auth.texture.RequestTextureProvider;
import pro.gravit.launchserver.binary.tasks.exe.Launch4JTask;
import pro.gravit.launchserver.components.AuthLimiterComponent;
import pro.gravit.launchserver.components.Component;
import pro.gravit.launchserver.components.ProGuardComponent;
import pro.gravit.launchserver.components.RegLimiterComponent;
import pro.gravit.utils.Version;
import pro.gravit.utils.helper.JVMHelper;
import java.io.File;
import java.util.*;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.SECONDS;
public final class LaunchServerConfig {
private final static List<String> oldMirrorList = List.of("https://mirror.gravit.pro/5.2.x/", "https://mirror.gravit.pro/5.3.x/", "https://mirror.gravitlauncher.com/5.2.x/", "https://mirror.gravitlauncher.com/5.3.x/", "https://mirror.gravitlauncher.com/5.4.x/");
private final static List<String> oldMirrorList = List.of("https://mirror.gravit.pro/5.2.x/", "https://mirror.gravit.pro/5.3.x/",
"https://mirror.gravitlauncher.com/5.2.x/", "https://mirror.gravitlauncher.com/5.3.x/", "https://mirror.gravitlauncher.com/5.4.x/",
"https://mirror.gravitlauncher.com/5.5.x/");
private transient final Logger logger = LogManager.getLogger();
public String projectName;
public String[] mirrors;
@ -39,31 +36,16 @@ public final class LaunchServerConfig {
// Handlers & Providers
public ProtectHandler protectHandler;
public Map<String, Component> components;
public ExeConf launch4j;
public NettyConfig netty;
public LauncherConf launcher;
public JarSignerConf sign;
public String startScript;
private transient LaunchServer server = null;
private transient AuthProviderPair authDefault;
public static LaunchServerConfig getDefault(LaunchServer.LaunchServerEnv env) {
LaunchServerConfig newConfig = new LaunchServerConfig();
newConfig.mirrors = new String[]{"https://mirror.gravitlauncher.com/5.5.x/", "https://gravit-launcher-mirror.storage.googleapis.com/"};
newConfig.launch4j = new LaunchServerConfig.ExeConf();
newConfig.launch4j.enabled = false;
newConfig.launch4j.copyright = "© GravitLauncher Team";
newConfig.launch4j.fileDesc = "GravitLauncher ".concat(Version.getVersion().getVersionString());
newConfig.launch4j.fileVer = Version.getVersion().getVersionString().concat(".").concat(String.valueOf(Version.getVersion().patch));
newConfig.launch4j.internalName = "Launcher";
newConfig.launch4j.trademarks = "This product is licensed under GPLv3";
newConfig.launch4j.txtFileVersion = "%s, build %d";
newConfig.launch4j.txtProductVersion = "%s, build %d";
newConfig.launch4j.productName = "GravitLauncher";
newConfig.launch4j.productVer = newConfig.launch4j.fileVer;
newConfig.launch4j.maxVersion = "99.0.0";
newConfig.mirrors = new String[]{"https://mirror.gravitlauncher.com/5.6.x/", "https://gravit-launcher-mirror.storage.googleapis.com/"};
newConfig.env = LauncherConfig.LauncherEnvironment.STD;
newConfig.startScript = JVMHelper.OS_TYPE.equals(JVMHelper.OS.MUSTDIE) ? "." + File.separator + "start.bat" : "." + File.separator + "start.sh";
newConfig.auth = new HashMap<>();
AuthProviderPair a = new AuthProviderPair(new RejectAuthCoreProvider(),
new RequestTextureProvider("http://example.com/skins/%username%.png", "http://example.com/cloaks/%username%.png")
@ -91,6 +73,7 @@ public static LaunchServerConfig getDefault(LaunchServer.LaunchServerEnv env) {
newConfig.launcher.compress = true;
newConfig.launcher.deleteTempFiles = true;
newConfig.launcher.stripLineNumbers = true;
newConfig.launcher.customJvmOptions.add("-Dfile.encoding=UTF-8");
newConfig.sign = new JarSignerConf();
@ -100,11 +83,6 @@ public static LaunchServerConfig getDefault(LaunchServer.LaunchServerEnv env) {
authLimiterComponent.rateLimitMillis = SECONDS.toMillis(8);
authLimiterComponent.message = "Превышен лимит авторизаций";
newConfig.components.put("authLimiter", authLimiterComponent);
RegLimiterComponent regLimiterComponent = new RegLimiterComponent();
regLimiterComponent.rateLimit = 3;
regLimiterComponent.rateLimitMillis = HOURS.toMillis(10);
regLimiterComponent.message = "Превышен лимит регистраций";
newConfig.components.put("regLimiter", regLimiterComponent);
ProGuardComponent proGuardComponent = new ProGuardComponent();
newConfig.components.put("proguard", proGuardComponent);
return newConfig;
@ -142,7 +120,7 @@ public void setEnv(LauncherConfig.LauncherEnvironment env) {
}
public void verify() {
if (auth == null || auth.size() < 1) {
if (auth == null || auth.isEmpty()) {
throw new NullPointerException("AuthProviderPair`s count should be at least one");
}
@ -171,8 +149,8 @@ public void verify() {
if (!updateMirror) {
for (int i = 0; i < mirrors.length; ++i) {
if (mirrors[i] != null && oldMirrorList.contains(mirrors[i])) {
logger.warn("Replace mirror '{}' to 'https://mirror.gravitlauncher.com/5.5.x/'. If you really need to use original url, use '-Dlaunchserver.config.disableUpdateMirror=true'", mirrors[i]);
mirrors[i] = "https://mirror.gravitlauncher.com/5.5.x/";
logger.warn("Replace mirror '{}' to 'https://mirror.gravitlauncher.com/5.6.x/'. If you really need to use original url, use '-Dlaunchserver.config.disableUpdateMirror=true'", mirrors[i]);
mirrors[i] = "https://mirror.gravitlauncher.com/5.6.x/";
}
}
}
@ -230,25 +208,6 @@ public void close(LaunchServer.ReloadType type) {
}
}
public static class ExeConf {
public boolean enabled;
public boolean setMaxVersion;
public String maxVersion;
public String minVersion = "17.0.0";
public String supportURL = null;
public String downloadUrl = Launch4JTask.DOWNLOAD_URL;
public String productName;
public String productVer;
public String fileDesc;
public String fileVer;
public String internalName;
public String copyright;
public String trademarks;
public String txtFileVersion;
public String txtProductVersion;
}
public static class JarSignerConf {
public boolean enabled = false;
public String keyStore = "pathToKey";
@ -301,6 +260,12 @@ public static class NettyPerformanceConfig {
public int workerThread;
public int schedulerThread;
public int maxWebSocketRequestBytes = 1024 * 1024;
public boolean disableThreadSafeClientObject;
public NettyExecutorType executorType = NettyExecutorType.VIRTUAL_THREADS;
public enum NettyExecutorType {
NONE, DEFAULT, WORK_STEAL, VIRTUAL_THREADS
}
}
public static class NettyBindAddress {

View file

@ -3,8 +3,8 @@
import com.google.gson.JsonElement;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.request.RequestException;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.request.RequestException;
import java.io.IOException;
import java.io.InputStream;

View file

@ -25,14 +25,14 @@ public static String makeAccessJwtTokenFromString(User user, LocalDateTime expir
}
public static JwtTokenInfo getJwtInfoFromAccessToken(String token, ECPublicKey publicKey) {
var parser = Jwts.parserBuilder()
var parser = Jwts.parser()
.requireIssuer("LaunchServer")
.setClock(() -> new Date(Clock.systemUTC().millis()))
.setSigningKey(publicKey)
.clock(() -> new Date(Clock.systemUTC().millis()))
.verifyWith(publicKey)
.build();
var claims = parser.parseClaimsJws(token);
var uuid = UUID.fromString(claims.getBody().get("uuid", String.class));
var username = claims.getBody().getSubject();
var claims = parser.parseSignedClaims(token);
var uuid = UUID.fromString(claims.getPayload().get("uuid", String.class));
var username = claims.getPayload().getSubject();
return new JwtTokenInfo(username, uuid);
}

View file

@ -1,12 +1,12 @@
package pro.gravit.launchserver.helper;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.profiles.ClientProfileBuilder;
import pro.gravit.launcher.profiles.ClientProfileVersions;
import pro.gravit.launcher.profiles.optional.OptionalFile;
import pro.gravit.launcher.profiles.optional.actions.OptionalActionFile;
import pro.gravit.launcher.profiles.optional.actions.OptionalActionJvmArgs;
import pro.gravit.launcher.profiles.optional.triggers.OSTrigger;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launcher.base.profiles.ClientProfileBuilder;
import pro.gravit.launcher.base.profiles.ClientProfileVersions;
import pro.gravit.launcher.base.profiles.optional.OptionalFile;
import pro.gravit.launcher.base.profiles.optional.actions.OptionalActionFile;
import pro.gravit.launcher.base.profiles.optional.actions.OptionalActionJvmArgs;
import pro.gravit.launcher.base.profiles.optional.triggers.OSTrigger;
import pro.gravit.utils.helper.JVMHelper;
import java.io.IOException;
@ -27,6 +27,7 @@ public static ClientProfile makeProfile(ClientProfile.Version version, String ti
builder.setMainClass(getMainClassByVersion(version, options));
builder.setServers(List.of(new ClientProfile.ServerProfile(title, "localhost", 25565)));
// ------------
var lwjgl3ify = findOption(options, Lwjgl3ifyOption.class);
builder.setUpdateVerify(List.of("libraries", "natives", "mods", "minecraft.jar", "forge.jar", "liteloader.jar"));
{
List<String> classPath = new ArrayList<>(5);
@ -44,8 +45,40 @@ public static ClientProfile makeProfile(ClientProfile.Version version, String ti
jvmArgs.add("-XX:+DisableAttachMechanism");
// Official Mojang launcher java arguments
if (version.compareTo(ClientProfileVersions.MINECRAFT_1_12_2) <= 0) {
jvmArgs.add("-XX:+UseConcMarkSweepGC");
jvmArgs.add("-XX:+CMSIncrementalMode");
// lwjgl3ify arguments https://github.com/GTNewHorizons/lwjgl3ify
jvmArgs.add("-Djava.security.manager=allow");
jvmArgs.add("--add-opens");
jvmArgs.add("java.base/jdk.internal.loader=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.base/java.net=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.base/java.nio=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.base/java.io=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.base/java.lang=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.base/java.lang.reflect=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.base/java.text=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.base/java.util=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.base/jdk.internal.reflect=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.base/sun.nio.ch=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming");
jvmArgs.add("--add-opens");
jvmArgs.add("java.desktop/sun.awt=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.desktop/sun.awt.image=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.desktop/com.sun.imageio.plugins.png=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED");
jvmArgs.add("--add-opens");
jvmArgs.add("java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED");
} else if (version.compareTo(ClientProfileVersions.MINECRAFT_1_18) <= 0) { // 1.13 - 1.16.5
jvmArgs.add("-XX:+UseG1GC");
jvmArgs.add("-XX:+UnlockExperimentalVMOptions");
@ -116,14 +149,8 @@ public static ClientProfile makeProfile(ClientProfile.Version version, String ti
}
}
}
if (version.compareTo(ClientProfileVersions.MINECRAFT_1_17) >= 0 && version.compareTo(ClientProfileVersions.MINECRAFT_1_18) < 0) {
builder.setMinJavaVersion(16);
builder.setRecommendJavaVersion(16);
}
if (version.compareTo(ClientProfileVersions.MINECRAFT_1_18) >= 0) {
builder.setMinJavaVersion(17);
builder.setRecommendJavaVersion(17);
}
builder.setMinJavaVersion(17);
builder.setRecommendJavaVersion(17);
if(version.compareTo(ClientProfileVersions.MINECRAFT_1_20_3) >= 0) {
builder.setMinJavaVersion(21);
builder.setRecommendJavaVersion(21);
@ -133,7 +160,10 @@ public static ClientProfile makeProfile(ClientProfile.Version version, String ti
builder.setJvmArgs(jvmArgs);
builder.setUpdateOptional(optionals);
List<String> clientArgs = new ArrayList<>();
if (findOption(options, MakeProfileOptionLaunchWrapper.class).isPresent()) {
if(version.compareTo(ClientProfileVersions.MINECRAFT_1_7_10) == 0) {
jvmArgs.add("-Drfb.skipClassLoaderCheck=true");
}
if (findOption(options, MakeProfileOptionLaunchWrapper.class).isPresent() || findOption(options, MakeProfileRfbOption.class).isPresent()) {
if (findOption(options, MakeProfileOptionLiteLoader.class).isPresent()) {
clientArgs.add("--tweakClass");
clientArgs.add("com.mumfrey.liteloader.launch.LiteLoaderTweaker");
@ -145,20 +175,9 @@ public static ClientProfile makeProfile(ClientProfile.Version version, String ti
} else {
clientArgs.add("cpw.mods.fml.common.launcher.FMLTweaker");
}
if (version.compareTo(ClientProfileVersions.MINECRAFT_1_12_2) <= 0) {
builder.setMinJavaVersion(8);
builder.setRecommendJavaVersion(8);
builder.setMaxJavaVersion(8);
}
}
} else if (version.compareTo(ClientProfileVersions.MINECRAFT_1_12_2) > 0) {
if (forge.isPresent()) {
clientArgs.addAll(forge.get().makeClientArgs());
builder.setClassLoaderConfig(ClientProfile.ClassLoaderConfig.SYSTEM_ARGS);
if (version.compareTo(ClientProfileVersions.MINECRAFT_1_16_5) <= 0) {
builder.setMaxJavaVersion(15);
}
}
forge.ifPresent(makeProfileOptionForge -> clientArgs.addAll(makeProfileOptionForge.makeClientArgs()));
}
builder.setClientArgs(clientArgs);
@ -171,6 +190,9 @@ private static <T> Optional<T> findOption(MakeProfileOption[] options, Class<T>
}
public static String getMainClassByVersion(ClientProfile.Version version, MakeProfileOption... options) {
if(version.compareTo(ClientProfileVersions.MINECRAFT_1_7_10) == 0) {
return "com.gtnewhorizons.retrofuturabootstrap.Main";
}
if (findOption(options, MakeProfileOptionLaunchWrapper.class).isPresent()) {
return "net.minecraft.launchwrapper.Launch";
}
@ -320,6 +342,13 @@ public static class MakeProfileOptionLaunchWrapper implements MakeProfileOption
}
public static class MakeProfileRfbOption implements MakeProfileOption {
}
public record Lwjgl3ifyOption(String lwjgl3ifyForgePatches) implements MakeProfileOption {
}
public static class MakeProfileOptionFabric implements MakeProfileOption {
public String jimfsPath;
public String guavaPath;

View file

@ -0,0 +1,24 @@
package pro.gravit.launchserver.holder;
import pro.gravit.utils.launch.ClassLoaderControl;
public class LaunchServerControlHolder {
private static ClassLoaderControl control;
private static ModuleLayer.Controller controller;
public static ClassLoaderControl getControl() {
return control;
}
public static void setControl(ClassLoaderControl control) {
LaunchServerControlHolder.control = control;
}
public static ModuleLayer.Controller getController() {
return controller;
}
public static void setController(ModuleLayer.Controller controller) {
LaunchServerControlHolder.controller = controller;
}
}

View file

@ -2,8 +2,8 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.LauncherTrustManager;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.core.LauncherTrustManager;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.asm.InjectClassAcceptor;
import pro.gravit.launchserver.binary.tasks.MainBuildTask;
@ -44,7 +44,6 @@ public void init() {
logger.error(e);
}
}
server.commandHandler.registerCommand("syncLauncherModules", new SyncLauncherModulesCommand(this));
MainBuildTask mainTask = server.launcherBinary.getTaskByClass(MainBuildTask.class).get();
mainTask.preBuildHook.registerHook((buildContext) -> {
for (ModuleEntity e : launcherModules) {

View file

@ -4,12 +4,12 @@
import io.jsonwebtoken.Jwts;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.ClientPermissions;
import pro.gravit.launcher.events.request.AuthRequestEvent;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.profiles.PlayerProfile;
import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.request.auth.password.*;
import pro.gravit.launcher.base.ClientPermissions;
import pro.gravit.launcher.base.events.request.AuthRequestEvent;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launcher.base.profiles.PlayerProfile;
import pro.gravit.launcher.base.request.auth.AuthRequest;
import pro.gravit.launcher.base.request.auth.password.*;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthException;
import pro.gravit.launchserver.auth.AuthProviderPair;
@ -38,19 +38,20 @@ public class AuthManager {
public AuthManager(LaunchServer server) {
this.server = server;
this.checkServerTokenParser = Jwts.parserBuilder()
this.checkServerTokenParser = Jwts.parser()
.requireIssuer("LaunchServer")
.require("tokenType", "checkServer")
.setSigningKey(server.keyAgreementManager.ecdsaPublicKey)
.verifyWith(server.keyAgreementManager.ecdsaPublicKey)
.build();
}
public String newCheckServerToken(String serverName, String authId) {
public String newCheckServerToken(String serverName, String authId, boolean publicOnly) {
return Jwts.builder()
.setIssuer("LaunchServer")
.issuer("LaunchServer")
.claim("serverName", serverName)
.claim("authId", authId)
.claim("tokenType", "checkServer")
.claim("isPublic", publicOnly)
.signWith(server.keyAgreementManager.ecdsaPrivateKey)
.compact();
}
@ -58,7 +59,8 @@ public String newCheckServerToken(String serverName, String authId) {
public CheckServerTokenInfo parseCheckServerToken(String token) {
try {
var jwt = checkServerTokenParser.parseClaimsJws(token).getBody();
return new CheckServerTokenInfo(jwt.get("serverName", String.class), jwt.get("authId", String.class));
var isPublicClaim = jwt.get("isPublic", Boolean.class);
return new CheckServerTokenInfo(jwt.get("serverName", String.class), jwt.get("authId", String.class), isPublicClaim == null || isPublicClaim);
} catch (Exception e) {
return null;
}
@ -301,7 +303,7 @@ private AuthRequest.AuthPasswordInterface tryDecryptPasswordPlain(AuthRequest.Au
return password;
}
public record CheckServerTokenInfo(String serverName, String authId) {
public record CheckServerTokenInfo(String serverName, String authId, boolean isPublic) {
}
public static class CheckServerVerifier implements RestoreResponse.ExtendedTokenProvider {
@ -321,7 +323,10 @@ public boolean accept(Client client, AuthProviderPair pair, String extendedToken
client.auth = server.config.getAuthProviderPair(info.authId);
if (client.permissions == null) client.permissions = new ClientPermissions();
client.permissions.addPerm("launchserver.checkserver");
client.permissions.addPerm("launchserver.profile.%s.show".formatted(info.serverName));
if(!info.isPublic) {
client.permissions.addPerm("launchserver.checkserver.extended");
client.permissions.addPerm("launchserver.profile.%s.show".formatted(info.serverName));
}
client.setProperty("launchserver.serverName", info.serverName);
return true;
}

View file

@ -11,7 +11,7 @@
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.bouncycastle.util.io.pem.PemWriter;
import pro.gravit.launcher.LauncherTrustManager;
import pro.gravit.launcher.core.LauncherTrustManager;
import pro.gravit.utils.helper.IOHelper;
import pro.gravit.utils.helper.JVMHelper;

View file

@ -1,6 +1,6 @@
package pro.gravit.launcher.managers;
package pro.gravit.launchserver.manangers;
import pro.gravit.launcher.config.JsonConfigurable;
import pro.gravit.launcher.base.config.JsonConfigurable;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.VerifyHelper;

View file

@ -2,16 +2,16 @@
import com.google.gson.GsonBuilder;
import marcono1234.gson.recordadapter.RecordTypeAdapterFactory;
import pro.gravit.launcher.events.request.GetAvailabilityAuthRequestEvent;
import pro.gravit.launcher.managers.GsonManager;
import pro.gravit.launcher.modules.events.PreGsonPhase;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.profiles.optional.actions.OptionalAction;
import pro.gravit.launcher.profiles.optional.triggers.OptionalTrigger;
import pro.gravit.launcher.request.JsonResultSerializeAdapter;
import pro.gravit.launcher.request.WebSocketEvent;
import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.request.auth.GetAvailabilityAuthRequest;
import pro.gravit.launcher.base.events.request.GetAvailabilityAuthRequestEvent;
import pro.gravit.launcher.core.managers.GsonManager;
import pro.gravit.launcher.base.modules.events.PreGsonPhase;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launcher.base.profiles.optional.actions.OptionalAction;
import pro.gravit.launcher.base.profiles.optional.triggers.OptionalTrigger;
import pro.gravit.launcher.base.request.JsonResultSerializeAdapter;
import pro.gravit.launcher.base.request.WebSocketEvent;
import pro.gravit.launcher.base.request.auth.AuthRequest;
import pro.gravit.launcher.base.request.auth.GetAvailabilityAuthRequest;
import pro.gravit.launchserver.auth.core.AuthCoreProvider;
import pro.gravit.launchserver.auth.mix.MixProvider;
import pro.gravit.launchserver.auth.password.PasswordVerifier;

View file

@ -3,7 +3,7 @@
import com.google.gson.JsonElement;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.utils.helper.IOHelper;
import java.io.IOException;

View file

@ -2,9 +2,9 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.hasher.HashedDir;
import pro.gravit.launcher.serialize.HInput;
import pro.gravit.launcher.serialize.HOutput;
import pro.gravit.launcher.core.hasher.HashedDir;
import pro.gravit.launcher.core.serialize.HInput;
import pro.gravit.launcher.core.serialize.HOutput;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.modules.events.LaunchServerUpdatesSyncEvent;
import pro.gravit.utils.helper.IOHelper;
@ -52,6 +52,10 @@ private void readCache(Path file) throws IOException {
this.updatesDirMap = Collections.unmodifiableMap(updatesDirMap);
}
public void readUpdatesFromCache() throws IOException {
readCache(cacheFile);
}
public void readUpdatesDir() throws IOException {
if (server.config.cacheUpdates) {
if (Files.exists(cacheFile)) {

View file

@ -7,7 +7,6 @@
import pro.gravit.launchserver.socket.response.auth.JoinServerResponse;
import pro.gravit.launchserver.socket.response.auth.SetProfileResponse;
import pro.gravit.utils.BiHookSet;
import pro.gravit.utils.HookSet;
public class AuthHookManager {
public final BiHookSet<AuthResponse.AuthContext, Client> preHook = new BiHookSet<>();
@ -16,19 +15,4 @@ public class AuthHookManager {
public final BiHookSet<AuthManager.CheckServerReport, Client> postCheckServerHook = new BiHookSet<>();
public final BiHookSet<JoinServerResponse, Client> joinServerHook = new BiHookSet<>();
public final BiHookSet<SetProfileResponse, Client> setProfileHook = new BiHookSet<>();
public final HookSet<RegContext> registraion = new HookSet<>();
public static class RegContext {
public final String login;
public final String password;
public final String ip;
public final boolean trustContext;
public RegContext(String login, String password, String ip, boolean trustContext) {
this.login = login;
this.password = password;
this.ip = ip;
this.trustContext = trustContext;
}
}
}

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.modules.events;
import pro.gravit.launcher.modules.LauncherModule;
import pro.gravit.launcher.base.modules.LauncherModule;
import pro.gravit.launchserver.LaunchServer;
public class LaunchServerFullInitEvent extends LauncherModule.Event {

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.modules.events;
import pro.gravit.launcher.modules.events.InitPhase;
import pro.gravit.launcher.base.modules.events.InitPhase;
import pro.gravit.launchserver.LaunchServer;
public class LaunchServerInitPhase extends InitPhase {

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.modules.events;
import pro.gravit.launcher.modules.LauncherModule;
import pro.gravit.launcher.base.modules.LauncherModule;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.binary.LauncherBinary;

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.modules.events;
import pro.gravit.launcher.modules.LauncherModule;
import pro.gravit.launcher.base.modules.LauncherModule;
import pro.gravit.launchserver.LaunchServer;
public class LaunchServerNettyFullInitEvent extends LauncherModule.Event {

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.modules.events;
import pro.gravit.launcher.modules.events.PostInitPhase;
import pro.gravit.launcher.base.modules.events.PostInitPhase;
import pro.gravit.launchserver.LaunchServer;
public class LaunchServerPostInitPhase extends PostInitPhase {

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.modules.events;
import pro.gravit.launcher.modules.LauncherModule;
import pro.gravit.launcher.base.modules.LauncherModule;
import pro.gravit.launchserver.LaunchServer;
public class LaunchServerProfilesSyncEvent extends LauncherModule.Event {

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.modules.events;
import pro.gravit.launcher.modules.LauncherModule;
import pro.gravit.launcher.base.modules.LauncherModule;
import pro.gravit.launchserver.LaunchServer;
public class LaunchServerUpdatesSyncEvent extends LauncherModule.Event {

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.modules.events;
import pro.gravit.launcher.modules.LauncherModule;
import pro.gravit.launcher.base.modules.LauncherModule;
import pro.gravit.launchserver.LaunchServer;
public class NewLaunchServerInstanceEvent extends LauncherModule.Event {

View file

@ -1,7 +1,7 @@
package pro.gravit.launchserver.modules.events.security;
import pro.gravit.launcher.events.request.SecurityReportRequestEvent;
import pro.gravit.launcher.modules.LauncherModule;
import pro.gravit.launcher.base.events.request.SecurityReportRequestEvent;
import pro.gravit.launcher.base.modules.LauncherModule;
import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.response.secure.SecurityReportResponse;

View file

@ -1,9 +1,9 @@
package pro.gravit.launchserver.modules.impl;
import pro.gravit.launcher.modules.LauncherInitContext;
import pro.gravit.launcher.modules.LauncherModule;
import pro.gravit.launcher.modules.LauncherModuleInfo;
import pro.gravit.launcher.modules.events.InitPhase;
import pro.gravit.launcher.base.modules.LauncherInitContext;
import pro.gravit.launcher.base.modules.LauncherModule;
import pro.gravit.launcher.base.modules.LauncherModuleInfo;
import pro.gravit.launcher.base.modules.events.InitPhase;
import pro.gravit.utils.Version;
public class LaunchServerCoreModule extends LauncherModule {

View file

@ -1,6 +1,6 @@
package pro.gravit.launchserver.modules.impl;
import pro.gravit.launcher.modules.LauncherInitContext;
import pro.gravit.launcher.base.modules.LauncherInitContext;
import pro.gravit.launchserver.LaunchServer;
public class LaunchServerInitContext implements LauncherInitContext {

View file

@ -1,8 +1,8 @@
package pro.gravit.launchserver.modules.impl;
import pro.gravit.launcher.LauncherTrustManager;
import pro.gravit.launcher.modules.LauncherModule;
import pro.gravit.launcher.modules.impl.SimpleModuleManager;
import pro.gravit.launcher.core.LauncherTrustManager;
import pro.gravit.launcher.base.modules.LauncherModule;
import pro.gravit.launcher.base.modules.impl.SimpleModuleManager;
import pro.gravit.launchserver.LaunchServer;
import java.nio.file.Path;

View file

@ -1,8 +1,7 @@
package pro.gravit.launchserver.socket;
import pro.gravit.launcher.ClientPermissions;
import pro.gravit.launcher.profiles.ClientProfile;
import pro.gravit.launcher.request.secure.HardwareReportRequest;
import pro.gravit.launcher.base.ClientPermissions;
import pro.gravit.launcher.base.profiles.ClientProfile;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.auth.core.interfaces.UserHardware;
@ -11,8 +10,12 @@
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Client {
ReadWriteLock lock = new ReentrantReadWriteLock();
public String auth_id;
public long timestamp;
public AuthResponse.ConnectTypes type;
@ -84,6 +87,14 @@ public pro.gravit.launchserver.auth.core.User getUser() {
return coreObject;
}
public Lock readLock() {
return lock.readLock();
}
public Lock writeLock() {
return lock.writeLock();
}
public static class TrustLevel {
public byte[] verifySecureKey;
public boolean keyChecked;

View file

@ -8,11 +8,11 @@
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.events.RequestEvent;
import pro.gravit.launcher.events.request.ErrorRequestEvent;
import pro.gravit.launcher.events.request.ExitRequestEvent;
import pro.gravit.launcher.request.WebSocketEvent;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launcher.base.events.RequestEvent;
import pro.gravit.launcher.base.events.request.ErrorRequestEvent;
import pro.gravit.launcher.base.events.request.ExitRequestEvent;
import pro.gravit.launcher.base.request.WebSocketEvent;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.socket.handlers.WebSocketFrameHandler;
import pro.gravit.launchserver.socket.response.SimpleResponse;
@ -21,6 +21,7 @@
import pro.gravit.launchserver.socket.response.cabinet.AssetUploadInfoResponse;
import pro.gravit.launchserver.socket.response.cabinet.GetAssetUploadInfoResponse;
import pro.gravit.launchserver.socket.response.management.FeaturesResponse;
import pro.gravit.launchserver.socket.response.management.GetConnectUUIDResponse;
import pro.gravit.launchserver.socket.response.management.GetPublicKeyResponse;
import pro.gravit.launchserver.socket.response.profile.BatchProfileByUsername;
import pro.gravit.launchserver.socket.response.profile.ProfileByUUIDResponse;
@ -39,6 +40,8 @@
import java.lang.reflect.Type;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.BiConsumer;
public class WebSocketService {
@ -51,11 +54,18 @@ public class WebSocketService {
private final LaunchServer server;
private final Gson gson;
private transient final Logger logger = LogManager.getLogger();
private ExecutorService executors;
public WebSocketService(ChannelGroup channels, LaunchServer server) {
this.channels = channels;
this.server = server;
this.gson = Launcher.gsonManager.gson;
executors = switch (server.config.netty.performance.executorType) {
case NONE -> null;
case DEFAULT -> Executors.newCachedThreadPool();
case WORK_STEAL -> Executors.newWorkStealingPool();
case VIRTUAL_THREADS -> Executors.newVirtualThreadPerTaskExecutor();
};
}
public static void registerResponses() {
@ -85,6 +95,7 @@ public static void registerResponses() {
providers.register("getPublicKey", GetPublicKeyResponse.class);
providers.register("getAssetUploadUrl", GetAssetUploadInfoResponse.class);
providers.register("assetUploadInfo", AssetUploadInfoResponse.class);
providers.register("getConnectUUID", GetConnectUUIDResponse.class);
}
public static String getIPFromContext(ChannelHandlerContext ctx) {
@ -112,9 +123,9 @@ public void forEachActiveChannels(BiConsumer<Channel, WebSocketFrameHandler> cal
}
}
public void process(ChannelHandlerContext ctx, TextWebSocketFrame frame, Client client, String ip) {
public void process(ChannelHandlerContext ctx, TextWebSocketFrame frame, Client client, String ip, UUID connectUUID) {
String request = frame.text();
WebSocketRequestContext context = new WebSocketRequestContext(ctx, request, client, ip);
WebSocketRequestContext context = new WebSocketRequestContext(ctx, request, client, ip, connectUUID);
if(hookBeforeParsing.hook(context)) {
return;
}
@ -126,7 +137,39 @@ public void process(ChannelHandlerContext ctx, TextWebSocketFrame frame, Client
sendObject(ctx.channel(), event, WebSocketEvent.class);
return;
}
process(context, response, client, ip);
var safeStatus = server.config.netty.performance.disableThreadSafeClientObject ?
WebSocketServerResponse.ThreadSafeStatus.NONE : response.getThreadSafeStatus();
if(executors == null) {
process(safeStatus, client, ip, context, response);
} else {
executors.submit(() -> process(safeStatus, client, ip, context, response));
}
}
private void process(WebSocketServerResponse.ThreadSafeStatus safeStatus, Client client, String ip, WebSocketRequestContext context, WebSocketServerResponse response) {
switch (safeStatus) {
case NONE -> {
process(context, response, client, ip);
}
case READ -> {
var lock = client.lock.readLock();
lock.lock();
try {
process(context, response, client, ip);
} finally {
lock.unlock();
}
}
case READ_WRITE -> {
var lock = client.lock.writeLock();
lock.lock();
try {
process(context, response, client, ip);
} finally {
lock.unlock();
}
}
}
}
void process(WebSocketRequestContext context, WebSocketServerResponse response, Client client, String ip) {
@ -140,6 +183,7 @@ void process(WebSocketRequestContext context, WebSocketServerResponse response,
simpleResponse.ctx = ctx;
if (ip != null) simpleResponse.ip = ip;
else simpleResponse.ip = IOHelper.getIP(ctx.channel().remoteAddress());
simpleResponse.connectUUID = context.connectUUID;
}
try {
response.execute(ctx, client);
@ -290,14 +334,16 @@ public static class WebSocketRequestContext {
public final String text;
public final Client client;
public final String ip;
public final UUID connectUUID;
public WebSocketServerResponse response;
public Throwable exception;
public WebSocketRequestContext(ChannelHandlerContext context, String text, Client client, String ip) {
public WebSocketRequestContext(ChannelHandlerContext context, String text, Client client, String ip, UUID connectUUID) {
this.context = context;
this.text = text;
this.client = client;
this.ip = ip;
this.connectUUID = connectUUID;
}
}

View file

@ -7,7 +7,7 @@
import io.netty.handler.codec.http.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher;
import pro.gravit.launcher.base.Launcher;
import pro.gravit.launchserver.socket.NettyConnectContext;
import pro.gravit.utils.helper.IOHelper;

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