[ANY] IDEA Reformat code

This commit is contained in:
Gravit 2019-04-03 20:27:40 +07:00
parent f1ccfbf58e
commit bda1c3658b
No known key found for this signature in database
GPG key ID: 061981E1E85D3216
126 changed files with 1031 additions and 1101 deletions

View file

@ -4,140 +4,140 @@
evaluationDependsOn(':Launcher') evaluationDependsOn(':Launcher')
repositories { repositories {
maven { maven {
url "https://oss.sonatype.org/content/repositories/snapshots" url "https://oss.sonatype.org/content/repositories/snapshots"
} }
maven { maven {
url "http://maven.geomajas.org/" url "http://maven.geomajas.org/"
} }
} }
sourceCompatibility = '1.8' sourceCompatibility = '1.8'
targetCompatibility = '1.8' targetCompatibility = '1.8'
configurations { configurations {
compileOnlyA compileOnlyA
bundleOnly bundleOnly
bundle bundle
hikari hikari
pack pack
launch4j launch4j
launch4jCJ launch4jCJ
bundleOnly.extendsFrom bundle bundleOnly.extendsFrom bundle
compile.extendsFrom bundle, hikari, pack, launch4jCJ, launch4j compile.extendsFrom bundle, hikari, pack, launch4jCJ, launch4j
} }
jar { jar {
dependsOn parent.childProjects.Launcher.tasks.build dependsOn parent.childProjects.Launcher.tasks.build
from { configurations.pack.collect { it.isDirectory() ? it : zipTree(it) } } from { configurations.pack.collect { it.isDirectory() ? it : zipTree(it) } }
from(parent.childProjects.Launcher.tasks.jar.archivePath, parent.childProjects.Launcher.tasks.genRuntimeJS.archivePath) from(parent.childProjects.Launcher.tasks.jar.archivePath, parent.childProjects.Launcher.tasks.genRuntimeJS.archivePath)
manifest.attributes("Main-Class": mainClassName, manifest.attributes("Main-Class": mainClassName,
"Premain-Class": mainAgentName, "Premain-Class": mainAgentName,
"Can-Redefine-Classes": "true", "Can-Redefine-Classes": "true",
"Can-Retransform-Classes": "true", "Can-Retransform-Classes": "true",
"Can-Set-Native-Method-Prefix": "true" "Can-Set-Native-Method-Prefix": "true"
) )
} }
dependencies { dependencies {
pack project(':libLauncher') pack project(':libLauncher')
bundle project(':Radon') bundle project(':Radon')
bundle 'mysql:mysql-connector-java:8.0.13' bundle 'mysql:mysql-connector-java:8.0.13'
bundle 'jline:jline:2.14.6' bundle 'jline:jline:2.14.6'
bundle 'net.sf.proguard:proguard-base:6.0.3' bundle 'net.sf.proguard:proguard-base:6.0.3'
bundle 'org.fusesource.jansi:jansi:1.17.1' bundle 'org.fusesource.jansi:jansi:1.17.1'
bundle 'commons-io:commons-io:2.6' bundle 'commons-io:commons-io:2.6'
bundle 'commons-codec:commons-codec:1.11' bundle 'commons-codec:commons-codec:1.11'
bundle 'org.javassist:javassist:3.24.1-GA' bundle 'org.javassist:javassist:3.24.1-GA'
bundle 'io.netty:netty-all:4.1.32.Final' bundle 'io.netty:netty-all:4.1.32.Final'
bundle 'org.slf4j:slf4j-simple:1.7.25' bundle 'org.slf4j:slf4j-simple:1.7.25'
bundle 'org.slf4j:slf4j-api:1.7.25' bundle 'org.slf4j:slf4j-api:1.7.25'
hikari 'io.micrometer:micrometer-core:1.0.6' hikari 'io.micrometer:micrometer-core:1.0.6'
hikari('com.zaxxer:HikariCP:3.2.0') { hikari('com.zaxxer:HikariCP:3.2.0') {
exclude group: 'javassist' exclude group: 'javassist'
exclude group: 'io.micrometer' exclude group: 'io.micrometer'
exclude group: 'org.slf4j' exclude group: 'org.slf4j'
} }
launch4j('net.sf.launch4j:launch4j:3.12') { launch4j('net.sf.launch4j:launch4j:3.12') {
exclude group: 'org.apache.ant' exclude group: 'org.apache.ant'
exclude group: 'net.java.abeille' exclude group: 'net.java.abeille'
exclude group: 'foxtrot' exclude group: 'foxtrot'
exclude group: 'com.jgoodies' exclude group: 'com.jgoodies'
} }
launch4jCJ('net.sf.launch4j:launch4j:3.12:workdir-win32') { launch4jCJ('net.sf.launch4j:launch4j:3.12:workdir-win32') {
exclude group: '*' exclude group: '*'
} }
launch4jCJ('net.sf.launch4j:launch4j:3.12:workdir-linux') { launch4jCJ('net.sf.launch4j:launch4j:3.12:workdir-linux') {
exclude group: '*' exclude group: '*'
} }
compileOnlyA 'com.google.guava:guava:26.0-jre' compileOnlyA 'com.google.guava:guava:26.0-jre'
compileOnlyA 'org.apache.logging.log4j:log4j-core:2.11.2' compileOnlyA 'org.apache.logging.log4j:log4j-core:2.11.2'
} }
task hikari(type: Copy) { task hikari(type: Copy) {
into "$buildDir/libs/libraries/hikaricp" into "$buildDir/libs/libraries/hikaricp"
from configurations.hikari from configurations.hikari
} }
task launch4jM(type: Copy) { task launch4jM(type: Copy) {
into "$buildDir/libs/libraries/launch4j" into "$buildDir/libs/libraries/launch4j"
from(configurations.launch4jCJ.collect { it.isDirectory() ? it : zipTree(it) }) from(configurations.launch4jCJ.collect { it.isDirectory() ? it : zipTree(it) })
includeEmptyDirs false includeEmptyDirs false
eachFile { FileCopyDetails fcp -> eachFile { FileCopyDetails fcp ->
if (fcp.relativePath.pathString.startsWith("launch4j-")) { if (fcp.relativePath.pathString.startsWith("launch4j-")) {
def segments = fcp.relativePath.segments def segments = fcp.relativePath.segments
def pathSegments = segments[1..-1] as String[] def pathSegments = segments[1..-1] as String[]
fcp.relativePath = new RelativePath(!fcp.file.isDirectory(), pathSegments) fcp.relativePath = new RelativePath(!fcp.file.isDirectory(), pathSegments)
fcp.mode = 0755 fcp.mode = 0755
} else { } else {
fcp.exclude() fcp.exclude()
} }
} }
} }
task launch4jA(type: Copy) { task launch4jA(type: Copy) {
into "$buildDir/libs/libraries/launch4j" into "$buildDir/libs/libraries/launch4j"
from(configurations.launch4j) from(configurations.launch4j)
includeEmptyDirs false includeEmptyDirs false
eachFile { FileCopyDetails fcp -> eachFile { FileCopyDetails fcp ->
if (fcp.name.startsWith("launch4j")) { if (fcp.name.startsWith("launch4j")) {
fcp.name = "launch4j.jar" fcp.name = "launch4j.jar"
} }
fcp.mode = 0755 fcp.mode = 0755
} }
} }
task dumpLibs(type: Copy) { task dumpLibs(type: Copy) {
dependsOn tasks.hikari, tasks.launch4jM, tasks.launch4jA dependsOn tasks.hikari, tasks.launch4jM, tasks.launch4jA
into "$buildDir/libs/libraries" into "$buildDir/libs/libraries"
from configurations.bundleOnly from configurations.bundleOnly
} }
task dumpCompileOnlyLibs(type: Copy) { task dumpCompileOnlyLibs(type: Copy) {
into "$buildDir/libs/launcher-libraries-compile" into "$buildDir/libs/launcher-libraries-compile"
from configurations.compileOnlyA from configurations.compileOnlyA
} }
task bundle(type: Zip) { task bundle(type: Zip) {
dependsOn parent.childProjects.Launcher.tasks.build, tasks.dumpLibs, tasks.dumpCompileOnlyLibs, tasks.jar dependsOn parent.childProjects.Launcher.tasks.build, tasks.dumpLibs, tasks.dumpCompileOnlyLibs, tasks.jar
archiveName 'LaunchServer.zip' archiveName 'LaunchServer.zip'
destinationDir file("$buildDir") destinationDir file("$buildDir")
from(tasks.dumpLibs.destinationDir) { into 'libraries' } from(tasks.dumpLibs.destinationDir) { into 'libraries' }
from(tasks.dumpCompileOnlyLibs.destinationDir) { into 'launcher-libraries-compile' } from(tasks.dumpCompileOnlyLibs.destinationDir) { into 'launcher-libraries-compile' }
from tasks.jar.archivePath from tasks.jar.archivePath
from(parent.childProjects.Launcher.tasks.dumpLibs) { into 'launcher-libraries' } from(parent.childProjects.Launcher.tasks.dumpLibs) { into 'launcher-libraries' }
} }
task dumpClientLibs(type: Copy) { task dumpClientLibs(type: Copy) {
dependsOn parent.childProjects.Launcher.tasks.build dependsOn parent.childProjects.Launcher.tasks.build
into "$buildDir/libs/launcher-libraries" into "$buildDir/libs/launcher-libraries"
from parent.childProjects.Launcher.tasks.dumpLibs.destinationDir from parent.childProjects.Launcher.tasks.dumpLibs.destinationDir
} }
build.dependsOn tasks.dumpLibs, tasks.dumpCompileOnlyLibs, tasks.dumpClientLibs, tasks.bundle build.dependsOn tasks.dumpLibs, tasks.dumpCompileOnlyLibs, tasks.dumpClientLibs, tasks.bundle

View file

@ -11,24 +11,20 @@
import ru.gravit.launcher.profiles.ClientProfile; import ru.gravit.launcher.profiles.ClientProfile;
import ru.gravit.launcher.serialize.signed.SignedObjectHolder; import ru.gravit.launcher.serialize.signed.SignedObjectHolder;
import ru.gravit.launchserver.auth.AuthProviderPair; import ru.gravit.launchserver.auth.AuthProviderPair;
import ru.gravit.launchserver.auth.protect.NoProtectHandler;
import ru.gravit.launchserver.auth.protect.ProtectHandler;
import ru.gravit.launchserver.components.AuthLimiterComponent;
import ru.gravit.launchserver.auth.handler.AuthHandler; import ru.gravit.launchserver.auth.handler.AuthHandler;
import ru.gravit.launchserver.auth.handler.MemoryAuthHandler; import ru.gravit.launchserver.auth.handler.MemoryAuthHandler;
import ru.gravit.launchserver.auth.hwid.AcceptHWIDHandler; import ru.gravit.launchserver.auth.hwid.AcceptHWIDHandler;
import ru.gravit.launchserver.auth.hwid.HWIDHandler; import ru.gravit.launchserver.auth.hwid.HWIDHandler;
import ru.gravit.launchserver.auth.permissions.JsonFilePermissionsHandler; import ru.gravit.launchserver.auth.permissions.JsonFilePermissionsHandler;
import ru.gravit.launchserver.auth.permissions.PermissionsHandler; import ru.gravit.launchserver.auth.permissions.PermissionsHandler;
import ru.gravit.launchserver.auth.protect.NoProtectHandler;
import ru.gravit.launchserver.auth.protect.ProtectHandler;
import ru.gravit.launchserver.auth.provider.AuthProvider; import ru.gravit.launchserver.auth.provider.AuthProvider;
import ru.gravit.launchserver.auth.provider.RejectAuthProvider; import ru.gravit.launchserver.auth.provider.RejectAuthProvider;
import ru.gravit.launchserver.binary.*; import ru.gravit.launchserver.binary.*;
import ru.gravit.launchserver.components.AuthLimiterComponent;
import ru.gravit.launchserver.components.Component; import ru.gravit.launchserver.components.Component;
import ru.gravit.utils.config.JsonConfigurable;
import ru.gravit.launchserver.config.adapter.*; import ru.gravit.launchserver.config.adapter.*;
import ru.gravit.utils.command.CommandHandler;
import ru.gravit.utils.command.JLineCommandHandler;
import ru.gravit.utils.command.StdCommandHandler;
import ru.gravit.launchserver.manangers.*; import ru.gravit.launchserver.manangers.*;
import ru.gravit.launchserver.manangers.hook.AuthHookManager; import ru.gravit.launchserver.manangers.hook.AuthHookManager;
import ru.gravit.launchserver.manangers.hook.BuildHookManager; import ru.gravit.launchserver.manangers.hook.BuildHookManager;
@ -38,6 +34,10 @@
import ru.gravit.launchserver.socket.ServerSocketHandler; import ru.gravit.launchserver.socket.ServerSocketHandler;
import ru.gravit.launchserver.texture.RequestTextureProvider; import ru.gravit.launchserver.texture.RequestTextureProvider;
import ru.gravit.launchserver.texture.TextureProvider; import ru.gravit.launchserver.texture.TextureProvider;
import ru.gravit.utils.command.CommandHandler;
import ru.gravit.utils.command.JLineCommandHandler;
import ru.gravit.utils.command.StdCommandHandler;
import ru.gravit.utils.config.JsonConfigurable;
import ru.gravit.utils.helper.*; import ru.gravit.utils.helper.*;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -96,25 +96,21 @@ public static final class Config {
private transient AuthProviderPair authDefault; private transient AuthProviderPair authDefault;
public AuthProviderPair getAuthProviderPair(String name) public AuthProviderPair getAuthProviderPair(String name) {
{ for (AuthProviderPair pair : auth) {
for(AuthProviderPair pair : auth) if (pair.name.equals(name)) return pair;
{
if(pair.name.equals(name)) return pair;
} }
return null; return null;
} }
public ProtectHandler protectHandler; public ProtectHandler protectHandler;
public PermissionsHandler permissionsHandler; public PermissionsHandler permissionsHandler;
public AuthProviderPair getAuthProviderPair() public AuthProviderPair getAuthProviderPair() {
{ if (authDefault != null) return authDefault;
if(authDefault != null) return authDefault; for (AuthProviderPair pair : auth) {
for(AuthProviderPair pair : auth) if (pair.isDefault) {
{
if(pair.isDefault)
{
authDefault = pair; authDefault = pair;
return pair; return pair;
} }
@ -190,18 +186,16 @@ public void verify() {
throw new NullPointerException("AuthHandler must not be null"); throw new NullPointerException("AuthHandler must not be null");
} }
boolean isOneDefault = false; boolean isOneDefault = false;
for(AuthProviderPair pair : auth) { for (AuthProviderPair pair : auth) {
if (pair.isDefault) { if (pair.isDefault) {
isOneDefault = true; isOneDefault = true;
break; break;
} }
} }
if(protectHandler == null) if (protectHandler == null) {
{
throw new NullPointerException("ProtectHandler must not be null"); throw new NullPointerException("ProtectHandler must not be null");
} }
if(!isOneDefault) if (!isOneDefault) {
{
throw new IllegalStateException("No auth pairs declared by default."); throw new IllegalStateException("No auth pairs declared by default.");
} }
if (permissionsHandler == null) { if (permissionsHandler == null) {
@ -210,13 +204,12 @@ public void verify() {
if (env == null) { if (env == null) {
throw new NullPointerException("Env must not be null"); throw new NullPointerException("Env must not be null");
} }
if(netty == null) if (netty == null) {
{
throw new NullPointerException("Netty must not be null"); throw new NullPointerException("Netty must not be null");
} }
} }
public void close()
{ public void close() {
try { try {
for (AuthProviderPair p : auth) p.close(); for (AuthProviderPair p : auth) p.close();
} catch (IOException e) { } catch (IOException e) {
@ -248,8 +241,8 @@ public static class ExeConf {
public String txtFileVersion; public String txtFileVersion;
public String txtProductVersion; public String txtProductVersion;
} }
public class NettyConfig
{ public class NettyConfig {
public String bindAddress; public String bindAddress;
public int port; public int port;
public boolean clientEnabled; public boolean clientEnabled;
@ -257,8 +250,8 @@ public class NettyConfig
public String launcherEXEURL; public String launcherEXEURL;
public String address; public String address;
} }
public class GuardLicenseConf
{ public class GuardLicenseConf {
public String name; public String name;
public String key; public String key;
public String encryptKey; public String encryptKey;
@ -299,10 +292,10 @@ public static void main(String... args) throws Throwable {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
try { try {
@SuppressWarnings("resource") @SuppressWarnings("resource")
LaunchServer launchserver = new LaunchServer(IOHelper.WORKING_DIR, args); LaunchServer launchserver = new LaunchServer(IOHelper.WORKING_DIR, args);
if(args.length == 0) launchserver.run(); if (args.length == 0) launchserver.run();
else { //Обработка команды else { //Обработка команды
launchserver.commandHandler.eval(args,false); launchserver.commandHandler.eval(args, false);
} }
} catch (Throwable exc) { } catch (Throwable exc) {
LogHelper.error(exc); LogHelper.error(exc);
@ -318,7 +311,7 @@ public static void main(String... args) throws Throwable {
public final Path launcherLibraries; public final Path launcherLibraries;
public final Path launcherLibrariesCompile; public final Path launcherLibrariesCompile;
public final List<String> args; public final List<String> args;
@ -383,7 +376,7 @@ public static void main(String... args) throws Throwable {
private volatile List<ClientProfile> profilesList; private volatile List<ClientProfile> profilesList;
public volatile Map<String, SignedObjectHolder<HashedDir>> updatesDirMap; public volatile Map<String, SignedObjectHolder<HashedDir>> updatesDirMap;
public final Timer taskPool; public final Timer taskPool;
public static Gson gson; public static Gson gson;
public static GsonBuilder gsonBuilder; public static GsonBuilder gsonBuilder;
@ -469,14 +462,12 @@ public LaunchServer(Path dir, String[] args) throws IOException, InvalidKeySpecE
} }
config.permissionsHandler.init(); config.permissionsHandler.init();
config.hwidHandler.init(); config.hwidHandler.init();
if(config.protectHandler != null) if (config.protectHandler != null) {
{
config.protectHandler.checkLaunchServerLicense(); config.protectHandler.checkLaunchServerLicense();
} }
if(config.components != null) if (config.components != null) {
{
LogHelper.debug("PreInit components"); LogHelper.debug("PreInit components");
config.components.forEach((k,v) -> { config.components.forEach((k, v) -> {
LogHelper.subDebug("PreInit component %s", k); LogHelper.subDebug("PreInit component %s", k);
v.preInit(this); v.preInit(this);
}); });
@ -507,12 +498,11 @@ public LaunchServer(Path dir, String[] args) throws IOException, InvalidKeySpecE
// init modules // init modules
modulesManager.initModules(); modulesManager.initModules();
if(config.components != null) if (config.components != null) {
{
LogHelper.debug("Init components"); LogHelper.debug("Init components");
config.components.forEach((k,v) -> { config.components.forEach((k, v) -> {
LogHelper.subDebug("Init component %s", k); LogHelper.subDebug("Init component %s", k);
registerObject("component.".concat(k),v); registerObject("component.".concat(k), v);
v.init(this); v.init(this);
}); });
LogHelper.debug("Init components successful"); LogHelper.debug("Init components successful");
@ -542,17 +532,16 @@ public LaunchServer(Path dir, String[] args) throws IOException, InvalidKeySpecE
// post init modules // post init modules
modulesManager.postInitModules(); modulesManager.postInitModules();
if(config.components != null) if (config.components != null) {
{
LogHelper.debug("PostInit components"); LogHelper.debug("PostInit components");
config.components.forEach((k,v) -> { config.components.forEach((k, v) -> {
LogHelper.subDebug("PostInit component %s", k); LogHelper.subDebug("PostInit component %s", k);
v.postInit(this); v.postInit(this);
}); });
LogHelper.debug("PostInit components successful"); LogHelper.debug("PostInit components successful");
} }
// start updater // start updater
if(config.netty != null) if (config.netty != null)
nettyServerSocketHandler = new NettyServerSocketHandler(this); nettyServerSocketHandler = new NettyServerSocketHandler(this);
else else
nettyServerSocketHandler = null; nettyServerSocketHandler = null;
@ -616,7 +605,7 @@ private void generateConfigIfNotExists() throws IOException {
// Create new config // Create new config
LogHelper.info("Creating LaunchServer config"); LogHelper.info("Creating LaunchServer config");
Config newConfig = new Config(); Config newConfig = new Config();
newConfig.mirrors = new String[]{"http://mirror.gravitlauncher.ml/","https://mirror.gravit.pro/"}; newConfig.mirrors = new String[]{"http://mirror.gravitlauncher.ml/", "https://mirror.gravit.pro/"};
newConfig.launch4j = new ExeConf(); newConfig.launch4j = new ExeConf();
newConfig.launch4j.copyright = "© GravitLauncher Team"; newConfig.launch4j.copyright = "© GravitLauncher Team";
newConfig.launch4j.fileDesc = "GravitLauncher ".concat(Launcher.getVersion().getVersionString()); newConfig.launch4j.fileDesc = "GravitLauncher ".concat(Launcher.getVersion().getVersionString());
@ -630,10 +619,10 @@ private void generateConfigIfNotExists() throws IOException {
newConfig.env = LauncherConfig.LauncherEnvironment.STD; newConfig.env = LauncherConfig.LauncherEnvironment.STD;
newConfig.startScript = JVMHelper.OS_TYPE.equals(JVMHelper.OS.MUSTDIE) ? "." + File.separator + "start.bat" : "." + File.separator + "start.sh"; newConfig.startScript = JVMHelper.OS_TYPE.equals(JVMHelper.OS.MUSTDIE) ? "." + File.separator + "start.bat" : "." + File.separator + "start.sh";
newConfig.hwidHandler = new AcceptHWIDHandler(); newConfig.hwidHandler = new AcceptHWIDHandler();
newConfig.auth = new AuthProviderPair[]{ new AuthProviderPair(new RejectAuthProvider("Настройте authProvider"), newConfig.auth = new AuthProviderPair[]{new AuthProviderPair(new RejectAuthProvider("Настройте authProvider"),
new MemoryAuthHandler(), new MemoryAuthHandler(),
new RequestTextureProvider("http://example.com/skins/%username%.png", "http://example.com/cloaks/%username%.png") new RequestTextureProvider("http://example.com/skins/%username%.png", "http://example.com/cloaks/%username%.png")
, "std") }; , "std")};
newConfig.protectHandler = new NoProtectHandler(); newConfig.protectHandler = new NoProtectHandler();
newConfig.permissionsHandler = new JsonFilePermissionsHandler(); newConfig.permissionsHandler = new JsonFilePermissionsHandler();
newConfig.port = 7240; newConfig.port = 7240;
@ -709,7 +698,7 @@ public void run() {
JVMHelper.RUNTIME.addShutdownHook(CommonHelper.newThread(null, false, this::close)); JVMHelper.RUNTIME.addShutdownHook(CommonHelper.newThread(null, false, this::close));
CommonHelper.newThread("Command Thread", true, commandHandler).start(); CommonHelper.newThread("Command Thread", true, commandHandler).start();
rebindServerSocket(); rebindServerSocket();
if(config.netty != null) if (config.netty != null)
rebindNettyServerSocket(); rebindNettyServerSocket();
modulesManager.finishModules(); modulesManager.finishModules();
} }
@ -789,22 +778,17 @@ public void restart() {
} }
} }
public void registerObject(String name, Object object) public void registerObject(String name, Object object) {
{ if (object instanceof Reloadable) {
if(object instanceof Reloadable)
{
reloadManager.registerReloadable(name, (Reloadable) object); reloadManager.registerReloadable(name, (Reloadable) object);
} }
if(object instanceof Reconfigurable) if (object instanceof Reconfigurable) {
{
reconfigurableManager.registerReconfigurable(name, (Reconfigurable) object); reconfigurableManager.registerReconfigurable(name, (Reconfigurable) object);
} }
if(object instanceof NeedGarbageCollection) if (object instanceof NeedGarbageCollection) {
{
GarbageManager.registerNeedGC((NeedGarbageCollection) object); GarbageManager.registerNeedGC((NeedGarbageCollection) object);
} }
if(object instanceof JsonConfigurable) if (object instanceof JsonConfigurable) {
{
} }
} }

View file

@ -20,8 +20,7 @@ public AuthProviderPair(AuthProvider provider, AuthHandler handler, TextureProvi
this.name = name; this.name = name;
} }
public void init() public void init() {
{
provider.init(); provider.init();
handler.init(); handler.init();
} }

View file

@ -80,8 +80,7 @@ public synchronized Connection getConnection() throws SQLException {
hikari = false; hikari = false;
// Try using HikariCP // Try using HikariCP
source = mysqlSource; source = mysqlSource;
if(enableHikari) if (enableHikari) {
{
try { try {
Class.forName("com.zaxxer.hikari.HikariDataSource"); Class.forName("com.zaxxer.hikari.HikariDataSource");
hikari = true; // Used for shutdown. Not instanceof because of possible classpath error hikari = true; // Used for shutdown. Not instanceof because of possible classpath error

View file

@ -65,7 +65,7 @@ protected Entry fetchEntry(UUID uuid) throws IOException {
} }
private Entry query(String sql, String value) throws IOException { private Entry query(String sql, String value) throws IOException {
try(Connection c = mySQLHolder.getConnection()) { try (Connection c = mySQLHolder.getConnection()) {
PreparedStatement s = c.prepareStatement(sql); PreparedStatement s = c.prepareStatement(sql);
s.setString(1, value); s.setString(1, value);
s.setQueryTimeout(MySQLSourceConfig.TIMEOUT); s.setQueryTimeout(MySQLSourceConfig.TIMEOUT);
@ -79,7 +79,7 @@ private Entry query(String sql, String value) throws IOException {
@Override @Override
protected boolean updateAuth(UUID uuid, String username, String accessToken) throws IOException { protected boolean updateAuth(UUID uuid, String username, String accessToken) throws IOException {
try(Connection c = mySQLHolder.getConnection()) { try (Connection c = mySQLHolder.getConnection()) {
PreparedStatement s = c.prepareStatement(updateAuthSQL); PreparedStatement s = c.prepareStatement(updateAuthSQL);
s.setString(1, username); // Username case s.setString(1, username); // Username case
s.setString(2, accessToken); s.setString(2, accessToken);
@ -93,7 +93,7 @@ protected boolean updateAuth(UUID uuid, String username, String accessToken) thr
@Override @Override
protected boolean updateServerID(UUID uuid, String serverID) throws IOException { protected boolean updateServerID(UUID uuid, String serverID) throws IOException {
try(Connection c = mySQLHolder.getConnection()) { try (Connection c = mySQLHolder.getConnection()) {
PreparedStatement s = c.prepareStatement(updateServerIDSQL); PreparedStatement s = c.prepareStatement(updateServerIDSQL);
s.setString(1, serverID); s.setString(1, serverID);
s.setString(2, uuid.toString()); s.setString(2, uuid.toString());

View file

@ -1,7 +1,6 @@
package ru.gravit.launchserver.auth.hwid; package ru.gravit.launchserver.auth.hwid;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import ru.gravit.launcher.ClientPermissions;
import ru.gravit.launcher.HWID; import ru.gravit.launcher.HWID;
import ru.gravit.launcher.Launcher; import ru.gravit.launcher.Launcher;
import ru.gravit.launchserver.LaunchServer; import ru.gravit.launchserver.LaunchServer;
@ -16,12 +15,10 @@
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
public class JsonFileHWIDHandler extends HWIDHandler { public class JsonFileHWIDHandler extends HWIDHandler {
public class Entry public class Entry {
{
public HWID hwid; public HWID hwid;
public String username; public String username;
public boolean isBanned = false; public boolean isBanned = false;
@ -43,22 +40,22 @@ public int hashCode() {
return Objects.hash(hwid); return Objects.hash(hwid);
} }
} }
public String filename = "hwids.json"; public String filename = "hwids.json";
public transient LinkedList<Entry> list = new LinkedList<>(); public transient LinkedList<Entry> list = new LinkedList<>();
public String banMessage = "You banned"; public String banMessage = "You banned";
@Override @Override
public void ban(List<HWID> hwid) throws HWIDException { public void ban(List<HWID> hwid) throws HWIDException {
for(Entry e : list) for (Entry e : list) {
{ for (HWID banHWID : hwid) {
for(HWID banHWID : hwid) if (e.hwid.equals(banHWID)) e.isBanned = true;
{
if(e.hwid.equals(banHWID)) e.isBanned = true;
} }
} }
} }
@Override @Override
public void init() public void init() {
{
Path path = Paths.get(filename); Path path = Paths.get(filename);
Type type = new TypeToken<LinkedList<Entry>>() { Type type = new TypeToken<LinkedList<Entry>>() {
}.getType(); }.getType();
@ -72,16 +69,13 @@ public void init()
@Override @Override
public void check0(HWID hwid, String username) throws HWIDException { public void check0(HWID hwid, String username) throws HWIDException {
boolean isOne = false; boolean isOne = false;
for(Entry e : list) for (Entry e : list) {
{ if (e.hwid.equals(hwid)) {
if(e.hwid.equals(hwid))
{
isOne = true; isOne = true;
if(e.isBanned) throw new HWIDException(banMessage); if (e.isBanned) throw new HWIDException(banMessage);
} }
} }
if(!isOne) if (!isOne) {
{
list.add(new Entry(hwid)); list.add(new Entry(hwid));
} }
} }
@ -89,8 +83,7 @@ public void check0(HWID hwid, String username) throws HWIDException {
@Override @Override
public void close() throws Exception { public void close() throws Exception {
Path path = Paths.get(filename); Path path = Paths.get(filename);
try(Writer writer = IOHelper.newWriter(path)) try (Writer writer = IOHelper.newWriter(path)) {
{
LaunchServer.gson.toJson(list, writer); LaunchServer.gson.toJson(list, writer);
} }
} }
@ -98,20 +91,17 @@ public void close() throws Exception {
@Override @Override
public List<HWID> getHwid(String username) throws HWIDException { public List<HWID> getHwid(String username) throws HWIDException {
LinkedList<HWID> hwids = new LinkedList<>(); LinkedList<HWID> hwids = new LinkedList<>();
for(Entry e : list) for (Entry e : list) {
{ if (e.username.equals(username)) hwids.add(e.hwid);
if(e.username.equals(username)) hwids.add(e.hwid);
} }
return hwids; return hwids;
} }
@Override @Override
public void unban(List<HWID> hwid) throws HWIDException { public void unban(List<HWID> hwid) throws HWIDException {
for(Entry e : list) for (Entry e : list) {
{ for (HWID banHWID : hwid) {
for(HWID banHWID : hwid) if (e.hwid.equals(banHWID)) e.isBanned = false;
{
if(e.hwid.equals(banHWID)) e.isBanned = false;
} }
} }
} }

View file

@ -7,8 +7,7 @@
import java.util.Objects; import java.util.Objects;
public class MemoryHWIDHandler extends HWIDHandler { public class MemoryHWIDHandler extends HWIDHandler {
public class Entry public class Entry {
{
public HWID hwid; public HWID hwid;
public String username; public String username;
public boolean isBanned = false; public boolean isBanned = false;
@ -30,15 +29,15 @@ public int hashCode() {
return Objects.hash(hwid); return Objects.hash(hwid);
} }
} }
public transient LinkedList<Entry> list = new LinkedList<>(); public transient LinkedList<Entry> list = new LinkedList<>();
public String banMessage = "You banned"; public String banMessage = "You banned";
@Override @Override
public void ban(List<HWID> hwid) throws HWIDException { public void ban(List<HWID> hwid) throws HWIDException {
for(Entry e : list) for (Entry e : list) {
{ for (HWID banHWID : hwid) {
for(HWID banHWID : hwid) if (e.hwid.equals(banHWID)) e.isBanned = true;
{
if(e.hwid.equals(banHWID)) e.isBanned = true;
} }
} }
} }
@ -46,16 +45,13 @@ public void ban(List<HWID> hwid) throws HWIDException {
@Override @Override
public void check0(HWID hwid, String username) throws HWIDException { public void check0(HWID hwid, String username) throws HWIDException {
boolean isOne = false; boolean isOne = false;
for(Entry e : list) for (Entry e : list) {
{ if (e.hwid.equals(hwid)) {
if(e.hwid.equals(hwid))
{
isOne = true; isOne = true;
if(e.isBanned) throw new HWIDException(banMessage); if (e.isBanned) throw new HWIDException(banMessage);
} }
} }
if(!isOne) if (!isOne) {
{
list.add(new Entry(hwid)); list.add(new Entry(hwid));
} }
} }
@ -73,20 +69,17 @@ public void init() {
@Override @Override
public List<HWID> getHwid(String username) throws HWIDException { public List<HWID> getHwid(String username) throws HWIDException {
LinkedList<HWID> hwids = new LinkedList<>(); LinkedList<HWID> hwids = new LinkedList<>();
for(Entry e : list) for (Entry e : list) {
{ if (e.username.equals(username)) hwids.add(e.hwid);
if(e.username.equals(username)) hwids.add(e.hwid);
} }
return hwids; return hwids;
} }
@Override @Override
public void unban(List<HWID> hwid) throws HWIDException { public void unban(List<HWID> hwid) throws HWIDException {
for(Entry e : list) for (Entry e : list) {
{ for (HWID banHWID : hwid) {
for(HWID banHWID : hwid) if (e.hwid.equals(banHWID)) e.isBanned = false;
{
if(e.hwid.equals(banHWID)) e.isBanned = false;
} }
} }
} }

View file

@ -63,7 +63,7 @@ public class MysqlHWIDHandler extends HWIDHandler {
public void check0(HWID hwid, String username) throws HWIDException { public void check0(HWID hwid, String username) throws HWIDException {
if (hwid instanceof OshiHWID) { if (hwid instanceof OshiHWID) {
OshiHWID oshiHWID = (OshiHWID) hwid; OshiHWID oshiHWID = (OshiHWID) hwid;
try(Connection c = mySQLHolder.getConnection()) { try (Connection c = mySQLHolder.getConnection()) {
PreparedStatement s = c.prepareStatement(String.format("SELECT %s, %s FROM `%s` WHERE `%s` = ? LIMIT 1", PreparedStatement s = c.prepareStatement(String.format("SELECT %s, %s FROM `%s` WHERE `%s` = ? LIMIT 1",
userFieldHwid, userFieldLogin, tableUsers, userFieldLogin)); userFieldHwid, userFieldLogin, tableUsers, userFieldLogin));
@ -141,10 +141,9 @@ public void onCheckInfo(OshiHWID hwid, String username, Connection c) throws HWI
} }
ResultSet set = a.executeQuery(); ResultSet set = a.executeQuery();
boolean isOne = false; boolean isOne = false;
while(set.next()) { while (set.next()) {
if(!oneCompareMode) isOne = true; if (!oneCompareMode) isOne = true;
if(compareMode) if (compareMode) {
{
OshiHWID db_hwid = new OshiHWID(); OshiHWID db_hwid = new OshiHWID();
db_hwid.serialNumber = set.getString(hwidFieldSerialNumber); db_hwid.serialNumber = set.getString(hwidFieldSerialNumber);
db_hwid.processorID = set.getString(hwidFieldProcessorID); db_hwid.processorID = set.getString(hwidFieldProcessorID);
@ -153,19 +152,18 @@ public void onCheckInfo(OshiHWID hwid, String username, Connection c) throws HWI
db_hwid.macAddr = ""; db_hwid.macAddr = "";
LogHelper.dev("Compare HWID: %s vs %s", hwid.getSerializeString(), db_hwid.getSerializeString()); LogHelper.dev("Compare HWID: %s vs %s", hwid.getSerializeString(), db_hwid.getSerializeString());
int compare_point = hwid.compare(db_hwid); int compare_point = hwid.compare(db_hwid);
if(compare_point < compare) continue; if (compare_point < compare) continue;
else else {
{
LogHelper.debug("User %s hwid check: found compare %d in %d", username, compare_point, set.getInt("id")); LogHelper.debug("User %s hwid check: found compare %d in %d", username, compare_point, set.getInt("id"));
} }
} }
if(oneCompareMode) isOne = true; if (oneCompareMode) isOne = true;
boolean isBanned = set.getBoolean(hwidFieldBanned); boolean isBanned = set.getBoolean(hwidFieldBanned);
if (isBanned) { if (isBanned) {
throw new HWIDException(banMessage); throw new HWIDException(banMessage);
} }
} }
if(isOne) { if (isOne) {
onUpdateInfo(hwid, username, c); onUpdateInfo(hwid, username, c);
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -177,7 +175,7 @@ public void setIsBanned(HWID hwid, boolean isBanned) {
LogHelper.debug("%s Request HWID: %s", isBanned ? "Ban" : "UnBan", hwid.toString()); LogHelper.debug("%s Request HWID: %s", isBanned ? "Ban" : "UnBan", hwid.toString());
if (hwid instanceof OshiHWID) { if (hwid instanceof OshiHWID) {
OshiHWID oshiHWID = (OshiHWID) hwid; OshiHWID oshiHWID = (OshiHWID) hwid;
try(Connection c = mySQLHolder.getConnection()) { try (Connection c = mySQLHolder.getConnection()) {
try (PreparedStatement a = c.prepareStatement(queryBan)) { try (PreparedStatement a = c.prepareStatement(queryBan)) {
String[] replaceParamsUpd = {"totalMemory", String.valueOf(oshiHWID.totalMemory), "serialNumber", oshiHWID.serialNumber, "HWDiskSerial", oshiHWID.HWDiskSerial, "processorID", oshiHWID.processorID, "isBanned", isBanned ? "1" : "0"}; String[] replaceParamsUpd = {"totalMemory", String.valueOf(oshiHWID.totalMemory), "serialNumber", oshiHWID.serialNumber, "HWDiskSerial", oshiHWID.HWDiskSerial, "processorID", oshiHWID.processorID, "isBanned", isBanned ? "1" : "0"};
for (int i = 0; i < paramsBan.length; i++) { for (int i = 0; i < paramsBan.length; i++) {
@ -212,7 +210,7 @@ public void unban(List<HWID> list) {
@Override @Override
public List<HWID> getHwid(String username) { public List<HWID> getHwid(String username) {
ArrayList<HWID> list = new ArrayList<>(); ArrayList<HWID> list = new ArrayList<>();
try(Connection c = mySQLHolder.getConnection()) { try (Connection c = mySQLHolder.getConnection()) {
LogHelper.debug("Try find HWID from username %s", username); LogHelper.debug("Try find HWID from username %s", username);
PreparedStatement s = c.prepareStatement(String.format("SELECT %s, %s FROM `%s` WHERE `%s` = ? LIMIT 1", userFieldHwid, userFieldLogin, tableUsers, userFieldLogin)); PreparedStatement s = c.prepareStatement(String.format("SELECT %s, %s FROM `%s` WHERE `%s` = ? LIMIT 1", userFieldHwid, userFieldLogin, tableUsers, userFieldLogin));
s.setString(1, username); s.setString(1, username);
@ -248,7 +246,7 @@ public List<HWID> getHwid(String username) {
@Override @Override
public void close() { public void close() {
mySQLHolder.close(); mySQLHolder.close();
} }
@Override @Override

View file

@ -37,8 +37,7 @@ public static void registerProviders() {
public abstract AuthProviderResult auth(String login, String password, String ip) throws Exception; public abstract AuthProviderResult auth(String login, String password, String ip) throws Exception;
public void preAuth(String login, String password, String customText, String ip) throws Exception public void preAuth(String login, String password, String customText, String ip) throws Exception {
{
return; return;
} }

View file

@ -29,8 +29,7 @@ public void init() {
@Override @Override
public AuthProviderResult auth(String login, String password, String ip) throws SQLException, AuthException { public AuthProviderResult auth(String login, String password, String ip) throws SQLException, AuthException {
try(Connection c = mySQLHolder.getConnection()) try (Connection c = mySQLHolder.getConnection()) {
{
PreparedStatement s = c.prepareStatement(query); PreparedStatement s = c.prepareStatement(query);
String[] replaceParams = {"login", login, "password", password, "ip", ip}; String[] replaceParams = {"login", login, "password", password, "ip", ip};
for (int i = 0; i < queryParams.length; i++) for (int i = 0; i < queryParams.length; i++)
@ -47,6 +46,6 @@ public AuthProviderResult auth(String login, String password, String ip) throws
@Override @Override
public void close() { public void close() {
mySQLHolder.close(); mySQLHolder.close();
} }
} }

View file

@ -70,6 +70,7 @@ public void setAddress(String address) {
body.append(address); body.append(address);
body.append("\";"); body.append("\";");
} }
public void setNettyAddress(String address) { public void setNettyAddress(String address) {
body.append("this.nettyAddress = \""); body.append("this.nettyAddress = \"");
body.append(address); body.append(address);
@ -139,6 +140,7 @@ public void setDownloadJava(boolean b) {
body.append(b ? "true" : "false"); body.append(b ? "true" : "false");
body.append(";"); body.append(";");
} }
public void setNettyEnabled(boolean b) { public void setNettyEnabled(boolean b) {
body.append("this.isNettyEnabled = "); body.append("this.isNettyEnabled = ");
body.append(b ? "true" : "false"); body.append(b ? "true" : "false");
@ -151,8 +153,7 @@ public void setWarningMissArchJava(boolean b) {
body.append(";"); body.append(";");
} }
public void setGuardLicense(String name, String key, String encryptKey) public void setGuardLicense(String name, String key, String encryptKey) {
{
body.append("this.guardLicenseName = \""); body.append("this.guardLicenseName = \"");
body.append(name); body.append(name);
body.append("\";"); body.append("\";");

View file

@ -21,7 +21,7 @@ public final class JARLauncherBinary extends LauncherBinary {
public final Path buildDir; public final Path buildDir;
public List<LauncherBuildTask> tasks; public List<LauncherBuildTask> tasks;
public List<Path> coreLibs; public List<Path> coreLibs;
public List<Path> addonLibs; public List<Path> addonLibs;
public JARLauncherBinary(LaunchServer server) throws IOException { public JARLauncherBinary(LaunchServer server) throws IOException {
super(server); super(server);

View file

@ -6,7 +6,9 @@
import ru.gravit.utils.helper.SecurityHelper; import ru.gravit.utils.helper.SecurityHelper;
import ru.gravit.utils.helper.UnpackHelper; import ru.gravit.utils.helper.UnpackHelper;
import java.io.*; import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.security.SecureRandom; import java.security.SecureRandom;
@ -18,8 +20,7 @@ public class ProguardConf {
private static String generateString(SecureRandom rand, String lowString, String upString, int il) { private static String generateString(SecureRandom rand, String lowString, String upString, int il) {
StringBuilder sb = new StringBuilder(il + lowString.length()); StringBuilder sb = new StringBuilder(il + lowString.length());
for(int i = 0;i<lowString.length();++i) for (int i = 0; i < lowString.length(); ++i) {
{
sb.append(rand.nextBoolean() ? lowString.charAt(i) : upString.charAt(i)); sb.append(rand.nextBoolean() ? lowString.charAt(i) : upString.charAt(i));
} }
for (int i = 0; i < il - 1; i++) sb.append(chars.charAt(rand.nextInt(chars.length()))); for (int i = 0; i < il - 1; i++) sb.append(chars.charAt(rand.nextInt(chars.length())));
@ -51,8 +52,8 @@ public String[] buildConfig(Path inputJar, Path outputJar) {
.map(e -> "-libraryjars \'" + e.toAbsolutePath().toString() + "\'") .map(e -> "-libraryjars \'" + e.toAbsolutePath().toString() + "\'")
.forEach(confStrs::add); .forEach(confStrs::add);
srv.launcherBinary.addonLibs.stream() srv.launcherBinary.addonLibs.stream()
.map(e -> "-libraryjars \'" + e.toAbsolutePath().toString() + "\'") .map(e -> "-libraryjars \'" + e.toAbsolutePath().toString() + "\'")
.forEach(confStrs::add); .forEach(confStrs::add);
confStrs.add("-classobfuscationdictionary \'" + words.toFile().getName() + "\'"); confStrs.add("-classobfuscationdictionary \'" + words.toFile().getName() + "\'");
confStrs.add(readConf()); confStrs.add(readConf());
return confStrs.toArray(new String[0]); return confStrs.toArray(new String[0]);

View file

@ -131,12 +131,11 @@ public Path process(Path inputJar) throws IOException {
jaConfigurator.setAddress(server.config.getAddress()); jaConfigurator.setAddress(server.config.getAddress());
jaConfigurator.setPort(server.config.port); jaConfigurator.setPort(server.config.port);
jaConfigurator.setNettyEnabled(server.config.netty.clientEnabled); jaConfigurator.setNettyEnabled(server.config.netty.clientEnabled);
if(server.config.netty.clientEnabled) if (server.config.netty.clientEnabled) {
{
jaConfigurator.setNettyPort(server.config.netty.port); jaConfigurator.setNettyPort(server.config.netty.port);
jaConfigurator.setNettyAddress(server.config.netty.address); jaConfigurator.setNettyAddress(server.config.netty.address);
} }
if(server.config.guardLicense != null) if (server.config.guardLicense != null)
jaConfigurator.setGuardLicense(server.config.guardLicense.name, server.config.guardLicense.key, server.config.guardLicense.encryptKey); jaConfigurator.setGuardLicense(server.config.guardLicense.name, server.config.guardLicense.key, server.config.guardLicense.encryptKey);
jaConfigurator.setProjectName(server.config.projectName); jaConfigurator.setProjectName(server.config.projectName);
jaConfigurator.setSecretKey(SecurityHelper.randomStringAESKey()); jaConfigurator.setSecretKey(SecurityHelper.randomStringAESKey());

View file

@ -1,5 +1,8 @@
package ru.gravit.launchserver.binary.tasks; package ru.gravit.launchserver.binary.tasks;
import me.itzsomebody.radon.Radon;
import me.itzsomebody.radon.SessionInfo;
import me.itzsomebody.radon.config.ConfigurationParser;
import ru.gravit.launchserver.LaunchServer; import ru.gravit.launchserver.LaunchServer;
import ru.gravit.utils.helper.IOHelper; import ru.gravit.utils.helper.IOHelper;
import ru.gravit.utils.helper.UnpackHelper; import ru.gravit.utils.helper.UnpackHelper;
@ -10,10 +13,6 @@
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import me.itzsomebody.radon.Radon;
import me.itzsomebody.radon.SessionInfo;
import me.itzsomebody.radon.config.ConfigurationParser;
public class RadonBuildTask implements LauncherBuildTask { public class RadonBuildTask implements LauncherBuildTask {
private final LaunchServer srv; private final LaunchServer srv;
public final Path config; public final Path config;
@ -31,19 +30,20 @@ public String getName() {
@Override @Override
public Path process(Path inputFile) throws IOException { public Path process(Path inputFile) throws IOException {
Path outputFile = srv.launcherBinary.nextLowerPath(this); Path outputFile = srv.launcherBinary.nextLowerPath(this);
if (srv.config.enabledRadon) { if (srv.config.enabledRadon) {
if (!IOHelper.isFile(config)) UnpackHelper.unpack(IOHelper.getResourceURL("ru/gravit/launchserver/defaults/radon.cfg"), config); if (!IOHelper.isFile(config))
ConfigurationParser p = new ConfigurationParser(IOHelper.newInput(config)); UnpackHelper.unpack(IOHelper.getResourceURL("ru/gravit/launchserver/defaults/radon.cfg"), config);
SessionInfo info = p.createSessionFromConfig(); ConfigurationParser p = new ConfigurationParser(IOHelper.newInput(config));
info.setInput(inputFile.toFile()); SessionInfo info = p.createSessionFromConfig();
info.setOutput(outputFile.toFile()); info.setInput(inputFile.toFile());
List<File> libs = srv.launcherBinary.coreLibs.stream().map(e -> e.toFile()).collect(Collectors.toList()); info.setOutput(outputFile.toFile());
libs.addAll(srv.launcherBinary.addonLibs.stream().map(e -> e.toFile()).collect(Collectors.toList())); List<File> libs = srv.launcherBinary.coreLibs.stream().map(e -> e.toFile()).collect(Collectors.toList());
info.setLibraries(libs); libs.addAll(srv.launcherBinary.addonLibs.stream().map(e -> e.toFile()).collect(Collectors.toList()));
Radon r = new Radon(info); info.setLibraries(libs);
r.run(); Radon r = new Radon(info);
} else r.run();
} else
IOHelper.copy(inputFile, outputFile); IOHelper.copy(inputFile, outputFile);
return outputFile; return outputFile;
} }

View file

@ -28,9 +28,9 @@ public String getUsageDescription() {
public void invoke(String... args) throws Exception { public void invoke(String... args) throws Exception {
verifyArgs(args, 2); verifyArgs(args, 2);
AuthProviderPair pair; AuthProviderPair pair;
if(args.length > 2) pair = server.config.getAuthProviderPair(args[2]); if (args.length > 2) pair = server.config.getAuthProviderPair(args[2]);
else pair = server.config.getAuthProviderPair(); else pair = server.config.getAuthProviderPair();
if(pair == null) throw new IllegalStateException(String.format("Auth %s not found", args[1])); if (pair == null) throw new IllegalStateException(String.format("Auth %s not found", args[1]));
String login = args[0]; String login = args[0];
String password = args[1]; String password = args[1];

View file

@ -28,9 +28,9 @@ public String getUsageDescription() {
public void invoke(String... args) throws CommandException, IOException { public void invoke(String... args) throws CommandException, IOException {
verifyArgs(args, 1); verifyArgs(args, 1);
AuthProviderPair pair; AuthProviderPair pair;
if(args.length > 1) pair = server.config.getAuthProviderPair(args[1]); if (args.length > 1) pair = server.config.getAuthProviderPair(args[1]);
else pair = server.config.getAuthProviderPair(); else pair = server.config.getAuthProviderPair();
if(pair == null) throw new IllegalStateException(String.format("Auth %s not found", args[1])); if (pair == null) throw new IllegalStateException(String.format("Auth %s not found", args[1]));
UUID uuid = parseUUID(args[0]); UUID uuid = parseUUID(args[0]);

View file

@ -28,9 +28,9 @@ public String getUsageDescription() {
public void invoke(String... args) throws CommandException, IOException { public void invoke(String... args) throws CommandException, IOException {
verifyArgs(args, 1); verifyArgs(args, 1);
AuthProviderPair pair; AuthProviderPair pair;
if(args.length > 1) pair = server.config.getAuthProviderPair(args[1]); if (args.length > 1) pair = server.config.getAuthProviderPair(args[1]);
else pair = server.config.getAuthProviderPair(); else pair = server.config.getAuthProviderPair();
if(pair == null) throw new IllegalStateException(String.format("Auth %s not found", args[1])); if (pair == null) throw new IllegalStateException(String.format("Auth %s not found", args[1]));
String username = parseUsername(args[0]); String username = parseUsername(args[0]);
// Get UUID by username // Get UUID by username

View file

@ -32,7 +32,7 @@ public String getUsageDescription() {
public void invoke(String... args) throws Exception { public void invoke(String... args) throws Exception {
verifyArgs(args, 3); verifyArgs(args, 3);
AuthProviderPair pair = server.config.getAuthProviderPair(args[1]); AuthProviderPair pair = server.config.getAuthProviderPair(args[1]);
if(pair == null) throw new IllegalStateException(String.format("Auth %s not found", args[1])); if (pair == null) throw new IllegalStateException(String.format("Auth %s not found", args[1]));
if (!(pair.handler instanceof CachedAuthHandler)) if (!(pair.handler instanceof CachedAuthHandler))
throw new UnsupportedOperationException("This command used only CachedAuthHandler"); throw new UnsupportedOperationException("This command used only CachedAuthHandler");
CachedAuthHandler authHandler = (CachedAuthHandler) pair.handler; CachedAuthHandler authHandler = (CachedAuthHandler) pair.handler;

View file

@ -13,8 +13,7 @@
import ru.gravit.launchserver.command.service.*; import ru.gravit.launchserver.command.service.*;
public abstract class CommandHandler extends ru.gravit.utils.command.CommandHandler { public abstract class CommandHandler extends ru.gravit.utils.command.CommandHandler {
public static void registerCommands(ru.gravit.utils.command.CommandHandler handler) public static void registerCommands(ru.gravit.utils.command.CommandHandler handler) {
{
LaunchServer server = LaunchServer.server; LaunchServer server = LaunchServer.server;
// Register basic commands // Register basic commands
handler.registerCommand("help", new HelpCommand(server)); handler.registerCommand("help", new HelpCommand(server));

View file

@ -4,8 +4,8 @@
import ru.gravit.launcher.profiles.ClientProfile.Version; import ru.gravit.launcher.profiles.ClientProfile.Version;
import ru.gravit.launchserver.LaunchServer; import ru.gravit.launchserver.LaunchServer;
import ru.gravit.launchserver.command.Command; import ru.gravit.launchserver.command.Command;
import ru.gravit.utils.command.CommandException;
import ru.gravit.utils.HttpDownloader; import ru.gravit.utils.HttpDownloader;
import ru.gravit.utils.command.CommandException;
import ru.gravit.utils.helper.IOHelper; import ru.gravit.utils.helper.IOHelper;
import ru.gravit.utils.helper.LogHelper; import ru.gravit.utils.helper.LogHelper;

View file

@ -20,8 +20,7 @@ public String getUsageDescription() {
@Override @Override
public void invoke(String... args) throws Exception { public void invoke(String... args) throws Exception {
for(String arg : args) for (String arg : args) {
{
server.commandHandler.eval(arg, false); server.commandHandler.eval(arg, false);
} }
} }

View file

@ -25,8 +25,7 @@ public String getUsageDescription() {
return "component manager"; return "component manager";
} }
public void printHelp() public void printHelp() {
{
LogHelper.info("Print help for component:"); LogHelper.info("Print help for component:");
LogHelper.subInfo("component unload [componentName]"); LogHelper.subInfo("component unload [componentName]");
LogHelper.subInfo("component load [componentName] [filename]"); LogHelper.subInfo("component load [componentName] [filename]");
@ -37,54 +36,43 @@ public void printHelp()
public void invoke(String... args) throws Exception { public void invoke(String... args) throws Exception {
verifyArgs(args, 1); verifyArgs(args, 1);
String componentName = null; String componentName = null;
if(args.length > 1) componentName = args[1]; if (args.length > 1) componentName = args[1];
switch(args[0]) switch (args[0]) {
{ case "unload": {
case "unload": if (componentName == null) throw new IllegalArgumentException("Must set componentName");
{
if(componentName == null) throw new IllegalArgumentException("Must set componentName");
Component component = server.config.components.get(componentName); Component component = server.config.components.get(componentName);
if(component == null) { if (component == null) {
LogHelper.error("Component %s not found", componentName); LogHelper.error("Component %s not found", componentName);
return; return;
} }
if(component instanceof AutoCloseable) if (component instanceof AutoCloseable) {
{
((AutoCloseable) component).close(); ((AutoCloseable) component).close();
} } else {
else
{
LogHelper.error("Component %s unload not supported", componentName); LogHelper.error("Component %s unload not supported", componentName);
return; return;
} }
break; break;
} }
case "gc": case "gc": {
{ if (componentName == null) throw new IllegalArgumentException("Must set componentName");
if(componentName == null) throw new IllegalArgumentException("Must set componentName");
Component component = server.config.components.get(componentName); Component component = server.config.components.get(componentName);
if(component == null) { if (component == null) {
LogHelper.error("Component %s not found", componentName); LogHelper.error("Component %s not found", componentName);
return; return;
} }
if(component instanceof NeedGarbageCollection) if (component instanceof NeedGarbageCollection) {
{
((NeedGarbageCollection) component).garbageCollection(); ((NeedGarbageCollection) component).garbageCollection();
} } else {
else
{
LogHelper.error("Component %s gc not supported", componentName); LogHelper.error("Component %s gc not supported", componentName);
return; return;
} }
break; break;
} }
case "load": case "load": {
{ if (componentName == null) throw new IllegalArgumentException("Must set componentName");
if(componentName == null) throw new IllegalArgumentException("Must set componentName"); if (args.length <= 2) throw new IllegalArgumentException("Must set file");
if(args.length <= 2) throw new IllegalArgumentException("Must set file");
String fileName = args[2]; String fileName = args[2];
try(Reader reader = IOHelper.newReader(Paths.get(fileName))) try (Reader reader = IOHelper.newReader(Paths.get(fileName))) {
{
Component component = LaunchServer.gson.fromJson(reader, Component.class); Component component = LaunchServer.gson.fromJson(reader, Component.class);
component.preInit(server); component.preInit(server);
component.init(server); component.init(server);
@ -92,12 +80,10 @@ public void invoke(String... args) throws Exception {
LogHelper.info("Component %s(%s) loaded", componentName, component.getClass().getName()); LogHelper.info("Component %s(%s) loaded", componentName, component.getClass().getName());
} }
} }
case "help": case "help": {
{
printHelp(); printHelp();
} }
default: default: {
{
printHelp(); printHelp();
} }
} }

View file

@ -1,5 +1,5 @@
package ru.gravit.launchserver.command.service; package ru.gravit.launchserver.command.service;
import ru.gravit.launchserver.LaunchServer; import ru.gravit.launchserver.LaunchServer;
import ru.gravit.launchserver.command.Command; import ru.gravit.launchserver.command.Command;
import ru.gravit.utils.helper.LogHelper; import ru.gravit.utils.helper.LogHelper;

View file

@ -22,7 +22,7 @@ public String getUsageDescription() {
@Override @Override
public void invoke(String... args) throws Exception { public void invoke(String... args) throws Exception {
verifyArgs(args,1); verifyArgs(args, 1);
String username = args[0]; String username = args[0];
ClientPermissions permissions = server.config.permissionsHandler.getPermissions(username); ClientPermissions permissions = server.config.permissionsHandler.getPermissions(username);
LogHelper.info("Permissions %s: %s (long: %d)", username, permissions.toString(), permissions.toLong()); LogHelper.info("Permissions %s: %s (long: %d)", username, permissions.toString(), permissions.toLong());

View file

@ -27,25 +27,20 @@ public void invoke(String... args) throws Exception {
ClientPermissions permissions = server.config.permissionsHandler.getPermissions(username); ClientPermissions permissions = server.config.permissionsHandler.getPermissions(username);
String permission = args[1]; String permission = args[1];
boolean isEnabled = Boolean.valueOf(args[2]); boolean isEnabled = Boolean.valueOf(args[2]);
switch (permission) switch (permission) {
{ case "admin": {
case "admin":
{
permissions.canAdmin = isEnabled; permissions.canAdmin = isEnabled;
break; break;
} }
case "server": case "server": {
{
permissions.canServer = isEnabled; permissions.canServer = isEnabled;
break; break;
} }
case "bot": case "bot": {
{
permissions.canBot = isEnabled; permissions.canBot = isEnabled;
break; break;
} }
default: default: {
{
LogHelper.error("Unknown permission: %s", permission); LogHelper.error("Unknown permission: %s", permission);
return; return;
} }

View file

@ -34,8 +34,7 @@ public void invoke(String... args) {
LogHelper.info("Uptime: %d days %d hours %d minutes %d seconds", days, hour, min, second); LogHelper.info("Uptime: %d days %d hours %d minutes %d seconds", days, hour, min, second);
LogHelper.info("Uptime (double): %f", (double) JVMHelper.RUNTIME_MXBEAN.getUptime() / 1000); LogHelper.info("Uptime (double): %f", (double) JVMHelper.RUNTIME_MXBEAN.getUptime() / 1000);
LogHelper.info("Sessions: %d | Modules: %d | Commands: %d", server.sessionManager.getSessions().size(), server.modulesManager.modules.size(), server.commandHandler.commandsMap().size()); LogHelper.info("Sessions: %d | Modules: %d | Commands: %d", server.sessionManager.getSessions().size(), server.modulesManager.modules.size(), server.commandHandler.commandsMap().size());
for(AuthProviderPair pair : server.config.auth) for (AuthProviderPair pair : server.config.auth) {
{
if (pair.handler instanceof CachedAuthHandler) { if (pair.handler instanceof CachedAuthHandler) {
LogHelper.info("AuthHandler %s: EntryCache: %d | usernameCache: %d", pair.name, ((CachedAuthHandler) pair.handler).getEntryCache().size(), ((CachedAuthHandler) pair.handler).getUsernamesCache().size()); LogHelper.info("AuthHandler %s: EntryCache: %d | usernameCache: %d", pair.name, ((CachedAuthHandler) pair.handler).getEntryCache().size(), ((CachedAuthHandler) pair.handler).getUsernamesCache().size());
} }

View file

@ -4,7 +4,6 @@
import ru.gravit.launchserver.LaunchServer; import ru.gravit.launchserver.LaunchServer;
import ru.gravit.launchserver.auth.AuthException; import ru.gravit.launchserver.auth.AuthException;
import ru.gravit.launchserver.auth.provider.AuthProvider; import ru.gravit.launchserver.auth.provider.AuthProvider;
import ru.gravit.launchserver.components.Component;
import ru.gravit.launchserver.response.auth.AuthResponse; import ru.gravit.launchserver.response.auth.AuthResponse;
import ru.gravit.launchserver.socket.Client; import ru.gravit.launchserver.socket.Client;
@ -26,9 +25,9 @@ public void init(LaunchServer launchServer) {
public void postInit(LaunchServer launchServer) { public void postInit(LaunchServer launchServer) {
} }
public void preAuthHook(AuthResponse.AuthContext context, Client client) throws AuthException { public void preAuthHook(AuthResponse.AuthContext context, Client client) throws AuthException {
if(isLimit(context.ip)) if (isLimit(context.ip)) {
{
AuthProvider.authError(message); AuthProvider.authError(message);
} }
} }

View file

@ -9,6 +9,7 @@
public class CommandRemoverComponent extends Component implements AutoCloseable { public class CommandRemoverComponent extends Component implements AutoCloseable {
public String[] removeList = new String[]{}; public String[] removeList = new String[]{};
public transient Map<String, Command> commandsList = new HashMap<>(); public transient Map<String, Command> commandsList = new HashMap<>();
@Override @Override
public void preInit(LaunchServer launchServer) { public void preInit(LaunchServer launchServer) {
@ -21,18 +22,16 @@ public void init(LaunchServer launchServer) {
@Override @Override
public void postInit(LaunchServer launchServer) { public void postInit(LaunchServer launchServer) {
for(String cmd : removeList) for (String cmd : removeList) {
{
Command removedCmd = launchServer.commandHandler.unregisterCommand(cmd); Command removedCmd = launchServer.commandHandler.unregisterCommand(cmd);
if(removedCmd != null) if (removedCmd != null)
commandsList.put(cmd, removedCmd); commandsList.put(cmd, removedCmd);
} }
} }
@Override @Override
public void close() throws Exception { public void close() throws Exception {
for(Map.Entry<String, Command> e : commandsList.entrySet()) for (Map.Entry<String, Command> e : commandsList.entrySet()) {
{
LaunchServer.server.commandHandler.registerCommand(e.getKey(), e.getValue()); LaunchServer.server.commandHandler.registerCommand(e.getKey(), e.getValue());
} }
} }

View file

@ -35,7 +35,10 @@ public static void registerComponents() {
registredComp = true; registredComp = true;
} }
} }
public abstract void preInit(LaunchServer launchServer); public abstract void preInit(LaunchServer launchServer);
public abstract void init(LaunchServer launchServer); public abstract void init(LaunchServer launchServer);
public abstract void postInit(LaunchServer launchServer); public abstract void postInit(LaunchServer launchServer);
} }

View file

@ -13,8 +13,7 @@ public class AuthHandlerAdapter implements JsonSerializer<AuthHandler>, JsonDese
public AuthHandler deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public AuthHandler deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString(); String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString();
Class<? extends AuthHandler> cls = AuthHandler.getHandlerClass(typename); Class<? extends AuthHandler> cls = AuthHandler.getHandlerClass(typename);
if(cls == null) if (cls == null) {
{
LogHelper.error("AuthHandler %s not found", typename); LogHelper.error("AuthHandler %s not found", typename);
return null; return null;
} }

View file

@ -13,8 +13,7 @@ public class AuthProviderAdapter implements JsonSerializer<AuthProvider>, JsonDe
public AuthProvider deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public AuthProvider deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString(); String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString();
Class<? extends AuthProvider> cls = AuthProvider.getProviderClass(typename); Class<? extends AuthProvider> cls = AuthProvider.getProviderClass(typename);
if(cls == null) if (cls == null) {
{
LogHelper.error("AuthProvider %s not found", typename); LogHelper.error("AuthProvider %s not found", typename);
return null; return null;
} }

View file

@ -13,8 +13,7 @@ public class ComponentAdapter implements JsonSerializer<Component>, JsonDeserial
public Component deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public Component deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString(); String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString();
Class<? extends Component> cls = Component.getComponentClass(typename); Class<? extends Component> cls = Component.getComponentClass(typename);
if(cls == null) if (cls == null) {
{
LogHelper.error("Component %s not found", typename); LogHelper.error("Component %s not found", typename);
return null; return null;
} }

View file

@ -13,8 +13,7 @@ public class HWIDHandlerAdapter implements JsonSerializer<HWIDHandler>, JsonDese
public HWIDHandler deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public HWIDHandler deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString(); String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString();
Class<? extends HWIDHandler> cls = HWIDHandler.getHandlerClass(typename); Class<? extends HWIDHandler> cls = HWIDHandler.getHandlerClass(typename);
if(cls == null) if (cls == null) {
{
LogHelper.error("HWIDHandler %s not found", typename); LogHelper.error("HWIDHandler %s not found", typename);
return null; return null;
} }

View file

@ -13,8 +13,7 @@ public class PermissionsHandlerAdapter implements JsonSerializer<PermissionsHand
public PermissionsHandler deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public PermissionsHandler deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString(); String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString();
Class<? extends PermissionsHandler> cls = PermissionsHandler.getHandlerClass(typename); Class<? extends PermissionsHandler> cls = PermissionsHandler.getHandlerClass(typename);
if(cls == null) if (cls == null) {
{
LogHelper.error("PermissionsHandler %s not found", typename); LogHelper.error("PermissionsHandler %s not found", typename);
return null; return null;
} }

View file

@ -13,8 +13,7 @@ public class ProtectHandlerAdapter implements JsonSerializer<ProtectHandler>, Js
public ProtectHandler deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public ProtectHandler deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString(); String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString();
Class<? extends ProtectHandler> cls = ProtectHandler.getHandlerClass(typename); Class<? extends ProtectHandler> cls = ProtectHandler.getHandlerClass(typename);
if(cls == null) if (cls == null) {
{
LogHelper.error("ProtectHandler %s not found", typename); LogHelper.error("ProtectHandler %s not found", typename);
return null; return null;
} }

View file

@ -13,8 +13,7 @@ public class TextureProviderAdapter implements JsonSerializer<TextureProvider>,
public TextureProvider deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public TextureProvider deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString(); String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString();
Class<? extends TextureProvider> cls = TextureProvider.getProviderClass(typename); Class<? extends TextureProvider> cls = TextureProvider.getProviderClass(typename);
if(cls == null) if (cls == null) {
{
LogHelper.error("TextureProvider %s not found", typename); LogHelper.error("TextureProvider %s not found", typename);
return null; return null;
} }

View file

@ -1,7 +1,7 @@
package ru.gravit.launchserver.manangers; package ru.gravit.launchserver.manangers;
import ru.gravit.launcher.managers.SimpleModulesConfigManager;
import ru.gravit.launcher.managers.SimpleModuleManager; import ru.gravit.launcher.managers.SimpleModuleManager;
import ru.gravit.launcher.managers.SimpleModulesConfigManager;
import ru.gravit.launchserver.LaunchServer; import ru.gravit.launchserver.LaunchServer;
import ru.gravit.launchserver.modules.CoreModule; import ru.gravit.launchserver.modules.CoreModule;
import ru.gravit.launchserver.modules.LaunchServerModuleContext; import ru.gravit.launchserver.modules.LaunchServerModuleContext;

View file

@ -83,9 +83,9 @@ public void reply() throws Exception {
debug("Login: '%s', Password: '%s'", login, echo(password.length())); debug("Login: '%s', Password: '%s'", login, echo(password.length()));
AuthProviderResult result; AuthProviderResult result;
AuthProviderPair pair; AuthProviderPair pair;
if(auth_id.isEmpty()) pair = server.config.getAuthProviderPair(); if (auth_id.isEmpty()) pair = server.config.getAuthProviderPair();
else pair = server.config.getAuthProviderPair(auth_id); else pair = server.config.getAuthProviderPair(auth_id);
if(pair == null) requestError("Auth type not found"); if (pair == null) requestError("Auth type not found");
AuthProvider provider = pair.provider; AuthProvider provider = pair.provider;
clientData.type = Client.Type.USER; clientData.type = Client.Type.USER;
AuthContext context = new AuthContext(session, login, password.length(), customText, client, hwid_str, ip, false); AuthContext context = new AuthContext(session, login, password.length(), customText, client, hwid_str, ip, false);
@ -94,7 +94,7 @@ public void reply() throws Exception {
if (!clientData.checkSign) { if (!clientData.checkSign) {
throw new AuthException("You must using checkLauncher"); throw new AuthException("You must using checkLauncher");
} }
provider.preAuth(login,password,customText,ip); provider.preAuth(login, password, customText, ip);
result = provider.auth(login, password, ip); result = provider.auth(login, password, ip);
if (!VerifyHelper.isValidUsername(result.username)) { if (!VerifyHelper.isValidUsername(result.username)) {
AuthProvider.authError(String.format("Illegal result: '%s'", result.username)); AuthProvider.authError(String.format("Illegal result: '%s'", result.username));

View file

@ -52,9 +52,9 @@ public void reply() throws Exception {
debug("ServerLogin: '%s', Password: '%s'", login, echo(password.length())); debug("ServerLogin: '%s', Password: '%s'", login, echo(password.length()));
AuthProviderResult result; AuthProviderResult result;
AuthProviderPair pair; AuthProviderPair pair;
if(auth_id.isEmpty()) pair = server.config.getAuthProviderPair(); if (auth_id.isEmpty()) pair = server.config.getAuthProviderPair();
else pair = server.config.getAuthProviderPair(auth_id); else pair = server.config.getAuthProviderPair(auth_id);
if(pair == null) requestError("Auth type not found"); if (pair == null) requestError("Auth type not found");
AuthProvider provider = pair.provider; AuthProvider provider = pair.provider;
AuthResponse.AuthContext context = new AuthResponse.AuthContext(session, login, password.length(), null, client, null, ip, true); AuthResponse.AuthContext context = new AuthResponse.AuthContext(session, login, password.length(), null, client, null, ip, true);
try { try {

View file

@ -34,10 +34,10 @@ public Client(long session) {
public void up() { public void up() {
timestamp = System.currentTimeMillis(); timestamp = System.currentTimeMillis();
} }
public void updateAuth()
{ public void updateAuth() {
if(!isAuth) return; if (!isAuth) return;
if(auth_id.isEmpty()) auth = LaunchServer.server.config.getAuthProviderPair(); if (auth_id.isEmpty()) auth = LaunchServer.server.config.getAuthProviderPair();
else auth = LaunchServer.server.config.getAuthProviderPair(auth_id); else auth = LaunchServer.server.config.getAuthProviderPair(auth_id);
} }

View file

@ -36,7 +36,7 @@ public WebSocketService(ChannelGroup channels, LaunchServer server, GsonBuilder
this.server = server; this.server = server;
this.gsonBuiler = gson; this.gsonBuiler = gson;
this.gsonBuiler.registerTypeAdapter(JsonResponseInterface.class, new JsonResponseAdapter(this)); this.gsonBuiler.registerTypeAdapter(JsonResponseInterface.class, new JsonResponseAdapter(this));
this.gsonBuiler.registerTypeAdapter(ResultInterface.class,new JsonResultSerializeAdapter()); this.gsonBuiler.registerTypeAdapter(ResultInterface.class, new JsonResultSerializeAdapter());
this.gsonBuiler.registerTypeAdapter(HashedEntry.class, new HashedEntryAdapter()); this.gsonBuiler.registerTypeAdapter(HashedEntry.class, new HashedEntryAdapter());
this.gson = gsonBuiler.create(); this.gson = gsonBuiler.create();
} }
@ -86,6 +86,7 @@ public void registerResponses() {
public void sendObject(ChannelHandlerContext ctx, Object obj) { public void sendObject(ChannelHandlerContext ctx, Object obj) {
ctx.channel().writeAndFlush(new TextWebSocketFrame(gson.toJson(obj, ResultInterface.class))); ctx.channel().writeAndFlush(new TextWebSocketFrame(gson.toJson(obj, ResultInterface.class)));
} }
public void sendObject(ChannelHandlerContext ctx, Object obj, Type type) { public void sendObject(ChannelHandlerContext ctx, Object obj, Type type) {
ctx.channel().writeAndFlush(new TextWebSocketFrame(gson.toJson(obj, type))); ctx.channel().writeAndFlush(new TextWebSocketFrame(gson.toJson(obj, type)));
} }

View file

@ -10,6 +10,7 @@
public class AddLogListenerResponse implements JsonResponseInterface { public class AddLogListenerResponse implements JsonResponseInterface {
public LogHelper.OutputTypes outputType = LogHelper.OutputTypes.PLAIN; public LogHelper.OutputTypes outputType = LogHelper.OutputTypes.PLAIN;
@Override @Override
public String getType() { public String getType() {
return "addLogListener"; return "addLogListener";
@ -25,25 +26,20 @@ public void execute(WebSocketService service, ChannelHandlerContext ctx, Client
service.sendObject(ctx, new ErrorRequestEvent("Access denied")); service.sendObject(ctx, new ErrorRequestEvent("Access denied"));
return; return;
} }
if(client.logOutput != null) if (client.logOutput != null) {
{
LogHelper.info("Client %s remove log listener", client.username); LogHelper.info("Client %s remove log listener", client.username);
LogHelper.removeOutput(client.logOutput); LogHelper.removeOutput(client.logOutput);
} } else {
else
{
LogHelper.info("Client %s add log listener", client.username); LogHelper.info("Client %s add log listener", client.username);
LogHelper.Output output = (str) -> { LogHelper.Output output = (str) -> {
if(!ctx.isRemoved()) if (!ctx.isRemoved()) {
{ service.sendObject(ctx, new LogEvent(str));
service.sendObject(ctx,new LogEvent(str)); } else {
}
else {
LogHelper.removeOutput(client.logOutput); LogHelper.removeOutput(client.logOutput);
LogHelper.info("Client %s remove log listener", client.username); LogHelper.info("Client %s remove log listener", client.username);
} }
}; };
client.logOutput = new LogHelper.OutputEnity(output,outputType); client.logOutput = new LogHelper.OutputEnity(output, outputType);
LogHelper.addOutput(client.logOutput); LogHelper.addOutput(client.logOutput);
} }
} }

View file

@ -42,9 +42,9 @@ public AuthResponse(String login, String password, String auth_id, OshiHWID hwid
public String auth_id; public String auth_id;
public ConnectTypes authType; public ConnectTypes authType;
public OshiHWID hwid; public OshiHWID hwid;
public enum ConnectTypes
{ public enum ConnectTypes {
SERVER,CLIENT,BOT SERVER, CLIENT, BOT
} }
@Override @Override
@ -57,12 +57,11 @@ public void execute(WebSocketService service, ChannelHandlerContext ctx, Client
try { try {
AuthRequestEvent result = new AuthRequestEvent(); AuthRequestEvent result = new AuthRequestEvent();
String ip = IOHelper.getIP(ctx.channel().remoteAddress()); String ip = IOHelper.getIP(ctx.channel().remoteAddress());
if ((authType == null || authType == ConnectTypes.CLIENT) &&!clientData.checkSign) { if ((authType == null || authType == ConnectTypes.CLIENT) && !clientData.checkSign) {
AuthProvider.authError("Don't skip Launcher Update"); AuthProvider.authError("Don't skip Launcher Update");
return; return;
} }
if(password == null) if (password == null) {
{
try { try {
password = IOHelper.decode(SecurityHelper.newRSADecryptCipher(LaunchServer.server.privateKey). password = IOHelper.decode(SecurityHelper.newRSADecryptCipher(LaunchServer.server.privateKey).
doFinal(encryptedPassword)); doFinal(encryptedPassword));
@ -71,21 +70,19 @@ public void execute(WebSocketService service, ChannelHandlerContext ctx, Client
} }
} }
clientData.permissions = LaunchServer.server.config.permissionsHandler.getPermissions(login); clientData.permissions = LaunchServer.server.config.permissionsHandler.getPermissions(login);
if(authType == ConnectTypes.BOT && !clientData.permissions.canBot) if (authType == ConnectTypes.BOT && !clientData.permissions.canBot) {
{
AuthProvider.authError("authType: BOT not allowed for this account"); AuthProvider.authError("authType: BOT not allowed for this account");
} }
if(authType == ConnectTypes.SERVER && !clientData.permissions.canServer) if (authType == ConnectTypes.SERVER && !clientData.permissions.canServer) {
{
AuthProvider.authError("authType: SERVER not allowed for this account"); AuthProvider.authError("authType: SERVER not allowed for this account");
} }
AuthProviderPair pair; AuthProviderPair pair;
if(auth_id.isEmpty()) pair = LaunchServer.server.config.getAuthProviderPair(); if (auth_id.isEmpty()) pair = LaunchServer.server.config.getAuthProviderPair();
else pair = LaunchServer.server.config.getAuthProviderPair(auth_id); else pair = LaunchServer.server.config.getAuthProviderPair(auth_id);
ru.gravit.launchserver.response.auth.AuthResponse.AuthContext context = new ru.gravit.launchserver.response.auth.AuthResponse.AuthContext(0, login, password.length(),customText, client, ip, null, false); ru.gravit.launchserver.response.auth.AuthResponse.AuthContext context = new ru.gravit.launchserver.response.auth.AuthResponse.AuthContext(0, login, password.length(), customText, client, ip, null, false);
AuthProvider provider = pair.provider; AuthProvider provider = pair.provider;
LaunchServer.server.authHookManager.preHook(context, clientData); LaunchServer.server.authHookManager.preHook(context, clientData);
provider.preAuth(login,password,customText,ip); provider.preAuth(login, password, customText, ip);
AuthProviderResult aresult = provider.auth(login, password, ip); AuthProviderResult aresult = provider.auth(login, password, ip);
if (!VerifyHelper.isValidUsername(aresult.username)) { if (!VerifyHelper.isValidUsername(aresult.username)) {
AuthProvider.authError(String.format("Illegal result: '%s'", aresult.username)); AuthProvider.authError(String.format("Illegal result: '%s'", aresult.username));
@ -104,8 +101,8 @@ public void execute(WebSocketService service, ChannelHandlerContext ctx, Client
// throw new AuthException("You profile not found"); // throw new AuthException("You profile not found");
//} //}
UUID uuid = pair.handler.auth(aresult); UUID uuid = pair.handler.auth(aresult);
if(authType == ConnectTypes.CLIENT) if (authType == ConnectTypes.CLIENT)
LaunchServer.server.config.hwidHandler.check(hwid, aresult.username); LaunchServer.server.config.hwidHandler.check(hwid, aresult.username);
LaunchServer.server.authHookManager.postHook(context, clientData); LaunchServer.server.authHookManager.postHook(context, clientData);
clientData.isAuth = true; clientData.isAuth = true;
clientData.permissions = aresult.permissions; clientData.permissions = aresult.permissions;
@ -113,7 +110,7 @@ public void execute(WebSocketService service, ChannelHandlerContext ctx, Client
clientData.updateAuth(); clientData.updateAuth();
result.accessToken = aresult.accessToken; result.accessToken = aresult.accessToken;
result.permissions = clientData.permissions; result.permissions = clientData.permissions;
result.playerProfile = ProfileByUUIDResponse.getProfile(LaunchServer.server,uuid,aresult.username,client, clientData.auth.textureProvider); result.playerProfile = ProfileByUUIDResponse.getProfile(LaunchServer.server, uuid, aresult.username, client, clientData.auth.textureProvider);
service.sendObject(ctx, result); service.sendObject(ctx, result);
} catch (AuthException | HWIDException e) { } catch (AuthException | HWIDException e) {
service.sendObject(ctx, new ErrorRequestEvent(e.getMessage())); service.sendObject(ctx, new ErrorRequestEvent(e.getMessage()));

View file

@ -26,8 +26,8 @@ public void execute(WebSocketService service, ChannelHandlerContext ctx, Client
CheckServerRequestEvent result = new CheckServerRequestEvent(); CheckServerRequestEvent result = new CheckServerRequestEvent();
try { try {
result.uuid = pClient.auth.handler.checkServer(username, serverID); result.uuid = pClient.auth.handler.checkServer(username, serverID);
if(result.uuid != null) if (result.uuid != null)
result.playerProfile = ProfileByUUIDResponse.getProfile(LaunchServer.server,result.uuid,username,client, pClient.auth.textureProvider); result.playerProfile = ProfileByUUIDResponse.getProfile(LaunchServer.server, result.uuid, username, client, pClient.auth.textureProvider);
} catch (AuthException e) { } catch (AuthException e) {
service.sendObject(ctx, new ErrorRequestEvent(e.getMessage())); service.sendObject(ctx, new ErrorRequestEvent(e.getMessage()));
return; return;

View file

@ -11,7 +11,7 @@
import java.util.List; import java.util.List;
public class ProfilesResponse implements JsonResponseInterface { public class ProfilesResponse implements JsonResponseInterface {
@Override @Override
public String getType() { public String getType() {
return "profiles"; return "profiles";
@ -19,8 +19,7 @@ public String getType() {
@Override @Override
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception { public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception {
if(!client.checkSign) if (!client.checkSign) {
{
service.sendObject(ctx, new ErrorRequestEvent("Access denied")); service.sendObject(ctx, new ErrorRequestEvent("Access denied"));
return; return;
} }

View file

@ -13,6 +13,7 @@
public class SetProfileResponse implements JsonResponseInterface { public class SetProfileResponse implements JsonResponseInterface {
public String client; public String client;
@Override @Override
public String getType() { public String getType() {
return "setProfile"; return "setProfile";
@ -20,8 +21,7 @@ public String getType() {
@Override @Override
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception { public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception {
if(!client.isAuth) if (!client.isAuth) {
{
service.sendObject(ctx, new ErrorRequestEvent("Access denied")); service.sendObject(ctx, new ErrorRequestEvent("Access denied"));
return; return;
} }

View file

@ -11,12 +11,13 @@
import java.util.UUID; import java.util.UUID;
public class BatchProfileByUsername implements JsonResponseInterface { public class BatchProfileByUsername implements JsonResponseInterface {
class Entry class Entry {
{
String username; String username;
String client; String client;
} }
Entry[] list; Entry[] list;
@Override @Override
public String getType() { public String getType() {
return "batchProfileByUsername"; return "batchProfileByUsername";
@ -26,10 +27,9 @@ public String getType() {
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception { public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception {
BatchProfileByUsernameRequestEvent result = new BatchProfileByUsernameRequestEvent(); BatchProfileByUsernameRequestEvent result = new BatchProfileByUsernameRequestEvent();
result.playerProfiles = new PlayerProfile[list.length]; result.playerProfiles = new PlayerProfile[list.length];
for(int i=0;i<list.length;++i) for (int i = 0; i < list.length; ++i) {
{
UUID uuid = client.auth.handler.usernameToUUID(list[i].username); UUID uuid = client.auth.handler.usernameToUUID(list[i].username);
result.playerProfiles[i] = ProfileByUUIDResponse.getProfile(LaunchServer.server,uuid,list[i].username,list[i].client, client.auth.textureProvider); result.playerProfiles[i] = ProfileByUUIDResponse.getProfile(LaunchServer.server, uuid, list[i].username, list[i].client, client.auth.textureProvider);
} }
service.sendObject(ctx, result); service.sendObject(ctx, result);
} }

View file

@ -17,6 +17,7 @@
public class ProfileByUUIDResponse implements JsonResponseInterface { public class ProfileByUUIDResponse implements JsonResponseInterface {
public UUID uuid; public UUID uuid;
public String client; public String client;
public static PlayerProfile getProfile(LaunchServer server, UUID uuid, String username, String client, TextureProvider textureProvider) { public static PlayerProfile getProfile(LaunchServer server, UUID uuid, String username, String client, TextureProvider textureProvider) {
// Get skin texture // Get skin texture
Texture skin; Texture skin;
@ -48,6 +49,6 @@ public String getType() {
@Override @Override
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception { public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception {
String username = client.auth.handler.uuidToUsername(uuid); String username = client.auth.handler.uuidToUsername(uuid);
service.sendObject(ctx, new ProfileByUUIDRequestEvent(getProfile(LaunchServer.server,uuid,username,this.client, client.auth.textureProvider))); service.sendObject(ctx, new ProfileByUUIDRequestEvent(getProfile(LaunchServer.server, uuid, username, this.client, client.auth.textureProvider)));
} }
} }

View file

@ -14,6 +14,7 @@
public class ProfileByUsername implements JsonResponseInterface { public class ProfileByUsername implements JsonResponseInterface {
String username; String username;
String client; String client;
@Override @Override
public String getType() { public String getType() {
return "profileByUsername"; return "profileByUsername";
@ -22,6 +23,6 @@ public String getType() {
@Override @Override
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception { public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception {
UUID uuid = client.auth.handler.usernameToUUID(username); UUID uuid = client.auth.handler.usernameToUUID(username);
service.sendObject(ctx, new ProfileByUsernameRequestEvent(getProfile(LaunchServer.server,uuid,username,this.client, client.auth.textureProvider))); service.sendObject(ctx, new ProfileByUsernameRequestEvent(getProfile(LaunchServer.server, uuid, username, this.client, client.auth.textureProvider)));
} }
} }

View file

@ -29,7 +29,7 @@ public String getType() {
@Override @Override
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) { public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) {
byte[] bytes; byte[] bytes;
if(hash != null) if (hash != null)
bytes = Base64.getDecoder().decode(hash); bytes = Base64.getDecoder().decode(hash);
else else
bytes = digest; bytes = digest;

View file

@ -27,7 +27,7 @@ public void execute(WebSocketService service, ChannelHandlerContext ctx, Client
return; return;
} }
HashSet<String> set = new HashSet<>(); HashSet<String> set = new HashSet<>();
for(Map.Entry<String, SignedObjectHolder<HashedDir>> entry : LaunchServer.server.updatesDirMap.entrySet()) for (Map.Entry<String, SignedObjectHolder<HashedDir>> entry : LaunchServer.server.updatesDirMap.entrySet())
set.add(entry.getKey()); set.add(entry.getKey());
service.sendObject(ctx, new UpdateListRequestEvent(set)); service.sendObject(ctx, new UpdateListRequestEvent(set));
} }

View file

@ -11,6 +11,7 @@
public class UpdateResponse implements JsonResponseInterface { public class UpdateResponse implements JsonResponseInterface {
public String dir; public String dir;
@Override @Override
public String getType() { public String getType() {
return "update"; return "update";
@ -19,18 +20,18 @@ public String getType() {
@Override @Override
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception { public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception {
if (!client.isAuth || client.type != Client.Type.USER || client.profile == null) { if (!client.isAuth || client.type != Client.Type.USER || client.profile == null) {
service.sendObject(ctx,new ErrorRequestEvent("Access denied")); service.sendObject(ctx, new ErrorRequestEvent("Access denied"));
return; return;
} }
if (!client.permissions.canAdmin) { if (!client.permissions.canAdmin) {
for (ClientProfile p : LaunchServer.server.getProfiles()) { for (ClientProfile p : LaunchServer.server.getProfiles()) {
if (!client.profile.getTitle().equals(p.getTitle())) continue; if (!client.profile.getTitle().equals(p.getTitle())) continue;
if (!p.isWhitelistContains(client.username)) { if (!p.isWhitelistContains(client.username)) {
service.sendObject(ctx,new ErrorRequestEvent("You don't download this folder")); service.sendObject(ctx, new ErrorRequestEvent("You don't download this folder"));
return; return;
} }
} }
} }
service.sendObject(ctx,new UpdateRequestEvent(LaunchServer.server.updatesDirMap.get(dir).object)); service.sendObject(ctx, new UpdateRequestEvent(LaunchServer.server.updatesDirMap.get(dir).object));
} }
} }

View file

@ -8,13 +8,12 @@
public class ConsoleMain { public class ConsoleMain {
public static CommandHandler commandHandler; public static CommandHandler commandHandler;
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
if(ServerWrapper.config == null) if (ServerWrapper.config == null) {
{
LogHelper.warning("ServerWrapper not found"); LogHelper.warning("ServerWrapper not found");
} }
if(!ServerWrapper.permissions.canAdmin) if (!ServerWrapper.permissions.canAdmin) {
{
LogHelper.warning("Permission canAdmin not found"); LogHelper.warning("Permission canAdmin not found");
} }
try { try {

View file

@ -9,10 +9,10 @@
public class RemoteJLineCommandHandler extends JLineCommandHandler { public class RemoteJLineCommandHandler extends JLineCommandHandler {
public RemoteJLineCommandHandler() throws IOException { public RemoteJLineCommandHandler() throws IOException {
} }
@Override @Override
public void eval(String line, boolean bell) public void eval(String line, boolean bell) {
{ if (line.equals("exit")) System.exit(0);
if(line.equals("exit")) System.exit(0);
ExecCommandRequest request = new ExecCommandRequest(System.out::println, line); ExecCommandRequest request = new ExecCommandRequest(System.out::println, line);
try { try {
request.request(); request.request();

View file

@ -8,10 +8,10 @@ public class RemoteStdCommandHandler extends StdCommandHandler {
public RemoteStdCommandHandler(boolean readCommands) { public RemoteStdCommandHandler(boolean readCommands) {
super(readCommands); super(readCommands);
} }
@Override @Override
public void eval(String line, boolean bell) public void eval(String line, boolean bell) {
{ if (line.equals("exit")) System.exit(0);
if(line.equals("exit")) System.exit(0);
ExecCommandRequest request = new ExecCommandRequest(System.out::println, line); ExecCommandRequest request = new ExecCommandRequest(System.out::println, line);
try { try {
request.request(); request.request();

View file

@ -2,43 +2,43 @@
String mainAgentName = "ru.gravit.launcher.LauncherAgent" String mainAgentName = "ru.gravit.launcher.LauncherAgent"
repositories { repositories {
maven { maven {
url "http://repo.spring.io/plugins-release/" url "http://repo.spring.io/plugins-release/"
} }
} }
sourceCompatibility = '1.8' sourceCompatibility = '1.8'
targetCompatibility = '1.8' targetCompatibility = '1.8'
configurations { configurations {
bundle bundle
pack pack
compile.extendsFrom bundle, pack compile.extendsFrom bundle, pack
} }
jar { jar {
from { configurations.pack.collect { it.isDirectory() ? it : zipTree(it) } } from { configurations.pack.collect { it.isDirectory() ? it : zipTree(it) } }
manifest.attributes("Main-Class": mainClassName, manifest.attributes("Main-Class": mainClassName,
"Premain-Class": mainAgentName, "Premain-Class": mainAgentName,
"Can-Redefine-Classes": "true", "Can-Redefine-Classes": "true",
"Can-Retransform-Classes": "true", "Can-Retransform-Classes": "true",
"Can-Set-Native-Method-Prefix": "true") "Can-Set-Native-Method-Prefix": "true")
} }
dependencies { dependencies {
pack project(':LauncherAPI') // Not error on obf. pack project(':LauncherAPI') // Not error on obf.
bundle 'com.github.oshi:oshi-core:3.13.0' bundle 'com.github.oshi:oshi-core:3.13.0'
} }
task genRuntimeJS(type: Zip) { task genRuntimeJS(type: Zip) {
archiveName = "runtime.zip" archiveName = "runtime.zip"
destinationDir = file("${buildDir}/tmp") destinationDir = file("${buildDir}/tmp")
from "runtime/" from "runtime/"
} }
task dumpLibs(type: Copy) { task dumpLibs(type: Copy) {
into "$buildDir/libs/libraries" into "$buildDir/libs/libraries"
from configurations.bundle from configurations.bundle
} }

View file

@ -12,42 +12,52 @@
<!-- DrLeonardo Design --> <!-- DrLeonardo Design -->
<Pane fx:id="layout" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" visible="true" xmlns="http://javafx.com/javafx/8.0.20" xmlns:fx="http://javafx.com/fxml/1"> <Pane fx:id="layout" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity"
<children> prefHeight="400.0" prefWidth="600.0" visible="true" xmlns="http://javafx.com/javafx/8.0.20"
<ImageView id="background" fitHeight="400.0" fitWidth="600.0"> xmlns:fx="http://javafx.com/fxml/1">
<image> <children>
<Image preserveRatio="true" smooth="true" url="@images/background.png" /> <ImageView id="background" fitHeight="400.0" fitWidth="600.0">
</image> <image>
</ImageView> <Image preserveRatio="true" smooth="true" url="@images/background.png"/>
<Pane layoutX="160.0" layoutY="61.0" prefHeight="306.0" prefWidth="267.0" styleClass="loginPane"> </image>
<children> </ImageView>
<ImageView id="background" fitHeight="27.0" fitWidth="123.0" layoutX="72.0" layoutY="33.0"> <Pane layoutX="160.0" layoutY="61.0" prefHeight="306.0" prefWidth="267.0" styleClass="loginPane">
<image> <children>
<Image url="@images/icons/logo.png" /> <ImageView id="background" fitHeight="27.0" fitWidth="123.0" layoutX="72.0" layoutY="33.0">
</image> <image>
</ImageView> <Image url="@images/icons/logo.png"/>
</children> </image>
</Pane> </ImageView>
<Pane id="authPane" layoutX="1.0" layoutY="2.0" prefHeight="400.0" prefWidth="600.0"> </children>
<children> </Pane>
<TextField id="login" alignment="CENTER" layoutX="175.0" layoutY="144.0" prefHeight="45.0" prefWidth="233.0" promptText="Логин" /> <Pane id="authPane" layoutX="1.0" layoutY="2.0" prefHeight="400.0" prefWidth="600.0">
<PasswordField id="password" alignment="CENTER" layoutX="175.0" layoutY="197.0" prefHeight="45.0" prefWidth="233.0" promptText="Пароль" /> <children>
<Button id="goAuth" layoutX="159.0" layoutY="319.0" mnemonicParsing="false" opacity="1.0" prefHeight="45.0" prefWidth="267.0" styleClass="btn" text="ВОЙТИ" visible="true" /> <TextField id="login" alignment="CENTER" layoutX="175.0" layoutY="144.0" prefHeight="45.0"
<CheckBox id="rememberchb" fx:id="savePassword" contentDisplay="CENTER" layoutX="224.0" layoutY="291.0" prefHeight="17.0" prefWidth="137.0" text="Сохранить пароль" textFill="#dadada" /> prefWidth="233.0" promptText="Логин"/>
<Hyperlink id="link" fx:id="link" layoutY="371.0" prefHeight="30.0" prefWidth="158.0" textAlignment="CENTER" /> <PasswordField id="password" alignment="CENTER" layoutX="175.0" layoutY="197.0" prefHeight="45.0"
<Button id="discord_url" layoutX="278.0" layoutY="373.0" minHeight="16.0" minWidth="28.0" mnemonicParsing="false" prefHeight="16.0" prefWidth="28.0" text="" /> prefWidth="233.0" promptText="Пароль"/>
</children> <Button id="goAuth" layoutX="159.0" layoutY="319.0" mnemonicParsing="false" opacity="1.0"
</Pane> prefHeight="45.0" prefWidth="267.0" styleClass="btn" text="ВОЙТИ" visible="true"/>
<Pane id="mask" opacity="0.0" prefHeight="400.0" prefWidth="600.0" visible="false" /> <CheckBox id="rememberchb" fx:id="savePassword" contentDisplay="CENTER" layoutX="224.0" layoutY="291.0"
<Button id="hidebtn" focusTraversable="false" layoutX="535.0" layoutY="2.0" minHeight="25.0" minWidth="35.0" prefHeight="25.0" prefWidth="25.0" /> prefHeight="17.0" prefWidth="137.0" text="Сохранить пароль" textFill="#dadada"/>
<Button id="exitbtn" focusTraversable="false" layoutX="574.0" layoutY="2.0" minHeight="25.0" minWidth="20.0" prefHeight="25.0" prefWidth="20.0" /> <Hyperlink id="link" fx:id="link" layoutY="371.0" prefHeight="30.0" prefWidth="158.0"
<ImageView fitHeight="12.0" fitWidth="11.0" layoutX="9.0" layoutY="8.0"> textAlignment="CENTER"/>
<image> <Button id="discord_url" layoutX="278.0" layoutY="373.0" minHeight="16.0" minWidth="28.0"
<Image url="@images/icons/logo_small.png" /> mnemonicParsing="false" prefHeight="16.0" prefWidth="28.0" text=""/>
</image> </children>
</ImageView> </Pane>
</children> <Pane id="mask" opacity="0.0" prefHeight="400.0" prefWidth="600.0" visible="false"/>
<stylesheets> <Button id="hidebtn" focusTraversable="false" layoutX="535.0" layoutY="2.0" minHeight="25.0" minWidth="35.0"
<URL value="@login.css" /> prefHeight="25.0" prefWidth="25.0"/>
</stylesheets> <Button id="exitbtn" focusTraversable="false" layoutX="574.0" layoutY="2.0" minHeight="25.0" minWidth="20.0"
prefHeight="25.0" prefWidth="20.0"/>
<ImageView fitHeight="12.0" fitWidth="11.0" layoutX="9.0" layoutY="8.0">
<image>
<Image url="@images/icons/logo_small.png"/>
</image>
</ImageView>
</children>
<stylesheets>
<URL value="@login.css"/>
</stylesheets>
</Pane> </Pane>

View file

@ -13,80 +13,102 @@
<!-- DrLeonardo Design --> <!-- DrLeonardo Design -->
<Pane fx:id="layout" maxHeight="-1.0" maxWidth="-1.0" prefHeight="400.0" prefWidth="600.0" visible="true" xmlns="http://javafx.com/javafx/8.0.20" xmlns:fx="http://javafx.com/fxml/1"> <Pane fx:id="layout" maxHeight="-1.0" maxWidth="-1.0" prefHeight="400.0" prefWidth="600.0" visible="true"
<children> xmlns="http://javafx.com/javafx/8.0.20" xmlns:fx="http://javafx.com/fxml/1">
<ImageView id="background" fitHeight="400.0" fitWidth="600.0"> <children>
<image> <ImageView id="background" fitHeight="400.0" fitWidth="600.0">
<Image url="@images/background.png" /> <image>
</image> <Image url="@images/background.png"/>
</ImageView> </image>
<ImageView fitHeight="12.0" fitWidth="11.0" layoutX="9.0" layoutY="8.0"> </ImageView>
<image> <ImageView fitHeight="12.0" fitWidth="11.0" layoutX="9.0" layoutY="8.0">
<Image url="@images/icons/logo_small.png" /> <image>
</image> <Image url="@images/icons/logo_small.png"/>
</ImageView> </image>
<Pane layoutX="171.0" layoutY="28.0" prefHeight="372.0" prefWidth="429.0" styleClass="menuPane" /> </ImageView>
<Pane id="serverPane" prefHeight="400.0" prefWidth="600.0"> <Pane layoutX="171.0" layoutY="28.0" prefHeight="372.0" prefWidth="429.0" styleClass="menuPane"/>
<children> <Pane id="serverPane" prefHeight="400.0" prefWidth="600.0">
<Button id="hidebtn" focusTraversable="false" layoutX="545.0" layoutY="2.0" minHeight="25.0" minWidth="20.0" prefHeight="25.0" prefWidth="25.0" textAlignment="CENTER" /> <children>
<Button id="exitbtn" alignment="CENTER" contentDisplay="CENTER" focusTraversable="false" layoutX="572.0" layoutY="2.0" minHeight="25.0" minWidth="20.0" prefHeight="25.0" prefWidth="25.0" rotate="360.0" textAlignment="CENTER" translateX="0.0" /> <Button id="hidebtn" focusTraversable="false" layoutX="545.0" layoutY="2.0" minHeight="25.0"
<ScrollPane id="serverlist" hbarPolicy="NEVER" layoutX="0.0" layoutY="27.0" prefHeight="306.0" prefWidth="171.0" visible="true"> minWidth="20.0" prefHeight="25.0" prefWidth="25.0" textAlignment="CENTER"/>
<content> <Button id="exitbtn" alignment="CENTER" contentDisplay="CENTER" focusTraversable="false" layoutX="572.0"
<FlowPane id="servercontainer" alignment="TOP_LEFT" columnHalignment="LEFT" focusTraversable="false" hgap="0.0" maxHeight="0.0" maxWidth="0.0" orientation="HORIZONTAL" prefHeight="-1.0" prefWidth="161.0" prefWrapLength="0.0" rowValignment="TOP" vgap="7.0" visible="true"> layoutY="2.0" minHeight="25.0" minWidth="20.0" prefHeight="25.0" prefWidth="25.0" rotate="360.0"
<padding> textAlignment="CENTER" translateX="0.0"/>
<Insets top="10.0" /> <ScrollPane id="serverlist" hbarPolicy="NEVER" layoutX="0.0" layoutY="27.0" prefHeight="306.0"
</padding> prefWidth="171.0" visible="true">
</FlowPane> <content>
</content> <FlowPane id="servercontainer" alignment="TOP_LEFT" columnHalignment="LEFT"
</ScrollPane> focusTraversable="false" hgap="0.0" maxHeight="0.0" maxWidth="0.0"
<ScrollPane id="serverinfo" hbarPolicy="NEVER" layoutX="170.0" layoutY="71.0" pannable="true" prefHeight="234.0" prefWidth="432.0" visible="true"> orientation="HORIZONTAL" prefHeight="-1.0" prefWidth="161.0" prefWrapLength="0.0"
<content> rowValignment="TOP" vgap="7.0" visible="true">
<FlowPane id="" focusTraversable="false" orientation="HORIZONTAL" prefHeight="219.0" prefWidth="428.0" rowValignment="TOP" visible="true"> <padding>
<padding> <Insets top="10.0"/>
<Insets bottom="10.0" left="15.0" top="7.0" /> </padding>
</padding> </FlowPane>
<children> </content>
<Label id="serverDescription" alignment="TOP_LEFT" contentDisplay="LEFT" nodeOrientation="LEFT_TO_RIGHT" prefHeight="204.0" prefWidth="407.0" text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla convallis magna tellus, in bibendum tortor dignissim non. Phasellus vel tincidunt nulla, eu convallis ligula. Suspendisse ut diam vestibulum, tincidunt neque ut, posuere risus. Pellentesque posuere molestie eros, quis laoreet ante ornare quis. Morbi eu tortor fermentum, iaculis risus sit amet, fringilla augue. Aenean nulla purus, rutrum non sapien et, convallis tincidunt purus. Vivamus a eros pulvinar, dignissim leo lacinia, sodales nulla. Aliquam tortor augue, cursus a rutrum viverra, consequat non tellus. Donec porta nisl sed quam dictum commodo. Sed et vulputate dolor. Morbi ultrices justo vitae convallis semper. Donec sodales velit vel velit faucibus, et scelerisque felis finibus. Sed rutrum lacinia mauris, porta cursus mauris tempor eu. Duis turpis nulla, dictum vitae commodo rhoncus, pretium in turpis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos." textFill="#d3d3d3" wrapText="true"> </ScrollPane>
<font> <ScrollPane id="serverinfo" hbarPolicy="NEVER" layoutX="170.0" layoutY="71.0" pannable="true"
<Font size="14.0" fx:id="x3" /> prefHeight="234.0" prefWidth="432.0" visible="true">
</font> <content>
</Label> <FlowPane id="" focusTraversable="false" orientation="HORIZONTAL" prefHeight="219.0"
</children> prefWidth="428.0" rowValignment="TOP" visible="true">
</FlowPane> <padding>
</content> <Insets bottom="10.0" left="15.0" top="7.0"/>
</ScrollPane> </padding>
<Pane id="serverentrance" layoutX="170.0" layoutY="27.0" prefHeight="372.0" prefWidth="430.0"> <children>
<children> <Label id="serverDescription" alignment="TOP_LEFT" contentDisplay="LEFT"
<Button id="serverLaunch" layoutX="180.0" layoutY="294.0" mnemonicParsing="false" prefHeight="60.0" prefWidth="182.0" text="ИГРАТЬ"> nodeOrientation="LEFT_TO_RIGHT" prefHeight="204.0" prefWidth="407.0"
<font> text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla convallis magna tellus, in bibendum tortor dignissim non. Phasellus vel tincidunt nulla, eu convallis ligula. Suspendisse ut diam vestibulum, tincidunt neque ut, posuere risus. Pellentesque posuere molestie eros, quis laoreet ante ornare quis. Morbi eu tortor fermentum, iaculis risus sit amet, fringilla augue. Aenean nulla purus, rutrum non sapien et, convallis tincidunt purus. Vivamus a eros pulvinar, dignissim leo lacinia, sodales nulla. Aliquam tortor augue, cursus a rutrum viverra, consequat non tellus. Donec porta nisl sed quam dictum commodo. Sed et vulputate dolor. Morbi ultrices justo vitae convallis semper. Donec sodales velit vel velit faucibus, et scelerisque felis finibus. Sed rutrum lacinia mauris, porta cursus mauris tempor eu. Duis turpis nulla, dictum vitae commodo rhoncus, pretium in turpis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos."
<Font size="22.0" /> textFill="#d3d3d3" wrapText="true">
</font> <font>
</Button> <Font size="14.0" fx:id="x3"/>
<Button id="clientbtn" layoutX="363.0" layoutY="294.0" mnemonicParsing="false" prefHeight="60.0" prefWidth="50.0" text="" /> </font>
<Label id="serverStatus" alignment="TOP_RIGHT" contentDisplay="RIGHT" layoutX="14.0" layoutY="312.0" opacity="0.61" prefHeight="25.0" prefWidth="153.0" text="12/100" textAlignment="RIGHT" textFill="WHITE"> </Label>
<font> </children>
<Font name="System Bold" size="16.0" /> </FlowPane>
</font> </content>
</Label> </ScrollPane>
<Label id="serverLabel" layoutX="2.0" layoutY="11.0" prefHeight="40.0" prefWidth="274.0" text="СЕРВЕР IFARM"> <Pane id="serverentrance" layoutX="170.0" layoutY="27.0" prefHeight="372.0" prefWidth="430.0">
<font> <children>
<Font name="System Bold" size="18.0" /> <Button id="serverLaunch" layoutX="180.0" layoutY="294.0" mnemonicParsing="false"
</font> prefHeight="60.0" prefWidth="182.0" text="ИГРАТЬ">
<padding> <font>
<Insets left="14.0" /> <Font size="22.0"/>
</padding> </font>
</Label> </Button>
<Button id="discord_url" alignment="BOTTOM_CENTER" contentDisplay="CENTER" layoutX="386.0" layoutY="23.0" minHeight="16.0" minWidth="28.0" mnemonicParsing="false" prefHeight="16.0" prefWidth="28.0" text="" textAlignment="CENTER" /> <Button id="clientbtn" layoutX="363.0" layoutY="294.0" mnemonicParsing="false" prefHeight="60.0"
</children> prefWidth="50.0" text=""/>
<Label id="serverStatus" alignment="TOP_RIGHT" contentDisplay="RIGHT" layoutX="14.0"
layoutY="312.0" opacity="0.61" prefHeight="25.0" prefWidth="153.0" text="12/100"
textAlignment="RIGHT" textFill="WHITE">
<font>
<Font name="System Bold" size="16.0"/>
</font>
</Label>
<Label id="serverLabel" layoutX="2.0" layoutY="11.0" prefHeight="40.0" prefWidth="274.0"
text="СЕРВЕР IFARM">
<font>
<Font name="System Bold" size="18.0"/>
</font>
<padding>
<Insets left="14.0"/>
</padding>
</Label>
<Button id="discord_url" alignment="BOTTOM_CENTER" contentDisplay="CENTER" layoutX="386.0"
layoutY="23.0" minHeight="16.0" minWidth="28.0" mnemonicParsing="false"
prefHeight="16.0" prefWidth="28.0" text="" textAlignment="CENTER"/>
</children>
</Pane>
<Button id="logoutbtn" layoutX="19.0" layoutY="350.0" mnemonicParsing="false" prefHeight="31.0"
prefWidth="133.0" styleClass="logoutbtn" text="Выйти"/>
<Button id="settingsbtn" alignment="CENTER" contentDisplay="CENTER" layoutX="518.0" layoutY="2.0"
mnemonicParsing="false" prefHeight="25.0" prefWidth="25.0" text="" textAlignment="CENTER"/>
</children>
</Pane> </Pane>
<Button id="logoutbtn" layoutX="19.0" layoutY="350.0" mnemonicParsing="false" prefHeight="31.0" prefWidth="133.0" styleClass="logoutbtn" text="Выйти" /> <Pane id="mask" opacity="0.0" prefHeight="400.0" prefWidth="600.0" visible="false"/>
<Button id="settingsbtn" alignment="CENTER" contentDisplay="CENTER" layoutX="518.0" layoutY="2.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="25.0" text="" textAlignment="CENTER" /> </children>
</children> <stylesheets>
</Pane> <URL value="@mainmenu.css"/>
<Pane id="mask" opacity="0.0" prefHeight="400.0" prefWidth="600.0" visible="false" /> </stylesheets>
</children>
<stylesheets>
<URL value="@mainmenu.css" />
</stylesheets>
</Pane> </Pane>

View file

@ -1,15 +1,16 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8"/>
<title>Offline-режим</title> <title>Offline-режим</title>
</head> </head>
<body style="color:red"> <body style="color:red">
<h2>Offline-режим</h2> <h2>Offline-режим</h2>
Лаунчер запущен в Offline-режиме. В этом режиме Вы можете запустить любой ранее загруженный клиент Лаунчер запущен в Offline-режиме. В этом режиме Вы можете запустить любой ранее загруженный клиент
с любым именем пользователя, при этом вход на серверы с авторизацией, а так же система скинов и плащей <b>может не работать</b>. с любым именем пользователя, при этом вход на серверы с авторизацией, а так же система скинов и плащей <b>может не
Скорее всего, проблема вызвана сбоем на сервере или неполадками в интернет-подключении. работать</b>.
Проверьте состояние интернет-подключения или обратитесь к администратору сервера. Скорее всего, проблема вызвана сбоем на сервере или неполадками в интернет-подключении.
</body> Проверьте состояние интернет-подключения или обратитесь к администратору сервера.
</body>
</html> </html>

View file

@ -7,13 +7,15 @@
<!-- DrLeonardo Design --> <!-- DrLeonardo Design -->
<Pane fx:id="overlay" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.20"> <Pane fx:id="overlay" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1"
xmlns="http://javafx.com/javafx/8.0.20">
<stylesheets> <stylesheets>
<URL value="@debug.css" /> <URL value="@debug.css"/>
</stylesheets> </stylesheets>
<!-- Debug controls --> <!-- Debug controls -->
<TextArea fx:id="output" layoutY="28.0" prefHeight="372.0" prefWidth="600.0" /> <TextArea fx:id="output" layoutY="28.0" prefHeight="372.0" prefWidth="600.0"/>
<Button fx:id="copy" defaultButton="true" layoutX="375.0" layoutY="352.0" prefHeight="30.0" prefWidth="100.0" text="Копировать" /> <Button fx:id="copy" defaultButton="true" layoutX="375.0" layoutY="352.0" prefHeight="30.0" prefWidth="100.0"
<Button fx:id="action" layoutX="480.0" layoutY="352.0" prefHeight="30.0" prefWidth="100.0" /> text="Копировать"/>
<Button fx:id="action" layoutX="480.0" layoutY="352.0" prefHeight="30.0" prefWidth="100.0"/>
</Pane> </Pane>

View file

@ -9,26 +9,28 @@
<!-- DrLeonardo Design --> <!-- DrLeonardo Design -->
<Pane fx:id="overlay" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.20" xmlns:fx="http://javafx.com/fxml/1"> <Pane fx:id="overlay" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.20"
<children> xmlns:fx="http://javafx.com/fxml/1">
<Pane id="holder" layoutX="171.0" layoutY="28.0" prefHeight="371.0" prefWidth="428.0"> <children>
<children> <Pane id="holder" layoutX="171.0" layoutY="28.0" prefHeight="371.0" prefWidth="428.0">
<ScrollPane id="modlist" hbarPolicy="NEVER"> <children>
<content> <ScrollPane id="modlist" hbarPolicy="NEVER">
<VBox prefHeight="370.0" prefWidth="428.0"> <content>
<children> <VBox prefHeight="370.0" prefWidth="428.0">
</children> <children>
<padding> </children>
<Insets left="10.0" top="8.0" /> <padding>
</padding> <Insets left="10.0" top="8.0"/>
</VBox> </padding>
</content> </VBox>
</ScrollPane> </content>
<Button fx:id="apply" defaultButton="true" layoutX="318.0" layoutY="336.0" prefHeight="25.0" prefWidth="100.0" text="Применить" /> </ScrollPane>
</children> <Button fx:id="apply" defaultButton="true" layoutX="318.0" layoutY="336.0" prefHeight="25.0"
</Pane> prefWidth="100.0" text="Применить"/>
</children> </children>
<stylesheets> </Pane>
<URL value="@options.css" /> </children>
</stylesheets> <stylesheets>
<URL value="@options.css"/>
</stylesheets>
</Pane> </Pane>

View file

@ -8,17 +8,20 @@
<!-- DrLeonardo Design | Fixes by Yaroslavik --> <!-- DrLeonardo Design | Fixes by Yaroslavik -->
<Pane fx:id="overlay" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.20" xmlns:fx="http://javafx.com/fxml/1"> <Pane fx:id="overlay" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.20"
<children> xmlns:fx="http://javafx.com/fxml/1">
<ImageView id="spinner" fx:id="spinner" fitHeight="161.0" fitWidth="161.0" layoutX="213.0" layoutY="94.0" y="-6.0"> <children>
<image> <ImageView id="spinner" fx:id="spinner" fitHeight="161.0" fitWidth="161.0" layoutX="213.0" layoutY="94.0"
<Image url="@../../images/icons/loading.gif" /> y="-6.0">
</image> <image>
</ImageView> <Image url="@../../images/icons/loading.gif"/>
<!-- Description --> </image>
<Label fx:id="description" alignment="CENTER" contentDisplay="CENTER" layoutX="152.0" layoutY="249.0" prefHeight="64.0" prefWidth="283.0" text="..." textAlignment="CENTER" /> </ImageView>
</children> <!-- Description -->
<stylesheets> <Label fx:id="description" alignment="CENTER" contentDisplay="CENTER" layoutX="152.0" layoutY="249.0"
<URL value="@processing.css" /> prefHeight="64.0" prefWidth="283.0" text="..." textAlignment="CENTER"/>
</stylesheets> </children>
<stylesheets>
<URL value="@processing.css"/>
</stylesheets>
</Pane> </Pane>

View file

@ -13,56 +13,70 @@
<!-- DrLeonardo Design --> <!-- DrLeonardo Design -->
<Pane fx:id="overlay" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.20" xmlns:fx="http://javafx.com/fxml/1"> <Pane fx:id="overlay" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.20"
<children> xmlns:fx="http://javafx.com/fxml/1">
<Pane id="holder" layoutX="1.0" layoutY="28.0" prefHeight="371.0" prefWidth="598.0"> <children>
<children> <Pane id="holder" layoutX="1.0" layoutY="28.0" prefHeight="371.0" prefWidth="598.0">
<CheckBox fx:id="autoEnter" layoutX="14.0" layoutY="80.0" text="Автовход на сервер" /> <children>
<Text fill="#8c8c8c" layoutX="38.0" layoutY="95.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Включение авто-входа означает что вы сразу после загрузки клиента попадете на сервер" wrappingWidth="533.0000102519989" y="15.0" /> <CheckBox fx:id="autoEnter" layoutX="14.0" layoutY="80.0" text="Автовход на сервер"/>
<CheckBox fx:id="fullScreen" layoutX="13.0" layoutY="185.0" text="Клиент в полный экран" /> <Text fill="#8c8c8c" layoutX="38.0" layoutY="95.0" strokeType="OUTSIDE" strokeWidth="0.0"
<Text fill="#8c8c8c" layoutX="38.0" layoutY="200.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Включение данной функции позволяет запустить игру сразу в полноэкранном режиме" wrappingWidth="533.0000102519989" y="15.0" /> text="Включение авто-входа означает что вы сразу после загрузки клиента попадете на сервер"
<CheckBox id="debug" layoutX="13.0" layoutY="124.0" text="Режим Отладки" /> wrappingWidth="533.0000102519989" y="15.0"/>
<Text fill="#8c8c8c" layoutX="38.0" layoutY="139.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Режим отладки позволяет просмотреть лог запуска и работы программы в реальном времени прямо из лаунчера, что упрощает поиск нужной информации" wrappingWidth="533.0000016447157" y="15.0" /> <CheckBox fx:id="fullScreen" layoutX="13.0" layoutY="185.0" text="Клиент в полный экран"/>
<Text fill="#8c8c8c" layoutX="38.0" layoutY="200.0" strokeType="OUTSIDE" strokeWidth="0.0"
<!-- RAM settings --> text="Включение данной функции позволяет запустить игру сразу в полноэкранном режиме"
<TextFlow layoutX="128.0" layoutY="6.0"> wrappingWidth="533.0000102519989" y="15.0"/>
<Text fx:id="ramLabel" /> <CheckBox id="debug" layoutX="13.0" layoutY="124.0" text="Режим Отладки"/>
</TextFlow> <Text fill="#8c8c8c" layoutX="38.0" layoutY="139.0" strokeType="OUTSIDE" strokeWidth="0.0"
<Slider fx:id="ramSlider" layoutX="18.0" layoutY="26.0" prefHeight="3.0" prefWidth="563.0" /> text="Режим отладки позволяет просмотреть лог запуска и работы программы в реальном времени прямо из лаунчера, что упрощает поиск нужной информации"
<Separator layoutY="65.0" prefHeight="1.0" prefWidth="598.0" /> wrappingWidth="533.0000016447157" y="15.0"/>
<!-- RAM settings -->
<!-- Deldir settings -->
<Button fx:id="deleteDir" layoutX="15.0" layoutY="333.0" prefHeight="25.0" prefWidth="245.0" text="Очистить данные игровых клиентов" textAlignment="CENTER" wrapText="true">
<font>
<Font name="System Bold" size="12.0" />
</font>
</Button>
<!-- Deldir settings -->
<!-- Changedir settings -->
<Button fx:id="changeDir" layoutX="14.0" layoutY="229.0" prefHeight="25.0" prefWidth="200.0" text="Сменить директорию загрузки" textAlignment="CENTER" wrapText="true" />
<Hyperlink id="dirLabel" alignment="TOP_LEFT" layoutX="215.0" layoutY="230.0" prefHeight="23.0" prefWidth="371.0" text="C:/Users" wrapText="true" />
<!-- Changedir settings -->
<Button fx:id="apply" defaultButton="true" layoutX="486.0" layoutY="335.0" prefHeight="23.0" prefWidth="100.0" text="Применить" />
<Text layoutX="17.0" layoutY="19.0">Выделение памяти: </Text>
<Pane fx:id="transferDialog" prefHeight="371.0" prefWidth="598.0">
<children>
<Text fill="WHITE" layoutX="99.0" layoutY="155.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Перенести все данные в новую директорию?" wrappingWidth="400.13671875">
<font>
<Font size="19.0" />
</font>
</Text>
<Button fx:id="applyTransfer" layoutX="130.0" layoutY="186.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="124.0" text="Да, перенести!" />
<Button fx:id="cancelTransfer" layoutX="344.0" layoutY="186.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="124.0" text="Нет, не нужно." />
</children>
</Pane>
</children> <!-- RAM settings -->
</Pane> <TextFlow layoutX="128.0" layoutY="6.0">
</children> <Text fx:id="ramLabel"/>
<stylesheets> </TextFlow>
<URL value="@settings.css" /> <Slider fx:id="ramSlider" layoutX="18.0" layoutY="26.0" prefHeight="3.0" prefWidth="563.0"/>
</stylesheets> <Separator layoutY="65.0" prefHeight="1.0" prefWidth="598.0"/>
<!-- RAM settings -->
<!-- Deldir settings -->
<Button fx:id="deleteDir" layoutX="15.0" layoutY="333.0" prefHeight="25.0" prefWidth="245.0"
text="Очистить данные игровых клиентов" textAlignment="CENTER" wrapText="true">
<font>
<Font name="System Bold" size="12.0"/>
</font>
</Button>
<!-- Deldir settings -->
<!-- Changedir settings -->
<Button fx:id="changeDir" layoutX="14.0" layoutY="229.0" prefHeight="25.0" prefWidth="200.0"
text="Сменить директорию загрузки" textAlignment="CENTER" wrapText="true"/>
<Hyperlink id="dirLabel" alignment="TOP_LEFT" layoutX="215.0" layoutY="230.0" prefHeight="23.0"
prefWidth="371.0" text="C:/Users" wrapText="true"/>
<!-- Changedir settings -->
<Button fx:id="apply" defaultButton="true" layoutX="486.0" layoutY="335.0" prefHeight="23.0"
prefWidth="100.0" text="Применить"/>
<Text layoutX="17.0" layoutY="19.0">Выделение памяти:</Text>
<Pane fx:id="transferDialog" prefHeight="371.0" prefWidth="598.0">
<children>
<Text fill="WHITE" layoutX="99.0" layoutY="155.0" strokeType="OUTSIDE" strokeWidth="0.0"
text="Перенести все данные в новую директорию?" wrappingWidth="400.13671875">
<font>
<Font size="19.0"/>
</font>
</Text>
<Button fx:id="applyTransfer" layoutX="130.0" layoutY="186.0" mnemonicParsing="false"
prefHeight="25.0" prefWidth="124.0" text="Да, перенести!"/>
<Button fx:id="cancelTransfer" layoutX="344.0" layoutY="186.0" mnemonicParsing="false"
prefHeight="25.0" prefWidth="124.0" text="Нет, не нужно."/>
</children>
</Pane>
</children>
</Pane>
</children>
<stylesheets>
<URL value="@settings.css"/>
</stylesheets>
</Pane> </Pane>

View file

@ -10,34 +10,38 @@
<!-- DrLeonardo Design --> <!-- DrLeonardo Design -->
<Pane fx:id="overlay" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.20" xmlns:fx="http://javafx.com/fxml/1"> <Pane fx:id="overlay" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.20"
<children> xmlns:fx="http://javafx.com/fxml/1">
<ImageView fitHeight="400.0" fitWidth="600.0" pickOnBounds="true" preserveRatio="true"> <children>
<image> <ImageView fitHeight="400.0" fitWidth="600.0" pickOnBounds="true" preserveRatio="true">
<Image url="@../../images/background.png" /> <image>
</image> <Image url="@../../images/background.png"/>
</ImageView> </image>
<Pane layoutY="28.0" prefHeight="372.0" prefWidth="600.0" styleClass="downloadPane" /> </ImageView>
<ImageView fitHeight="12.0" fitWidth="11.0" layoutX="9.0" layoutY="8.0"> <Pane layoutY="28.0" prefHeight="372.0" prefWidth="600.0" styleClass="downloadPane"/>
<image> <ImageView fitHeight="12.0" fitWidth="11.0" layoutX="9.0" layoutY="8.0">
<Image url="@../../images/icons/logo_small.png" /> <image>
</image> <Image url="@../../images/icons/logo_small.png"/>
</ImageView> </image>
<Label fx:id="description" layoutX="12.0" layoutY="267.0" prefHeight="98.0" prefWidth="576.0" text="..." textFill="WHITE" /> </ImageView>
<ProgressBar fx:id="progress" disable="false" layoutX="-1.0" layoutY="376.0" opacity="1.0" prefHeight="24.0" prefWidth="600.0" progress="1.0" style="" /> <Label fx:id="description" layoutX="12.0" layoutY="267.0" prefHeight="98.0" prefWidth="576.0" text="..."
<!-- Update controls --> textFill="WHITE"/>
<Label fx:id="utitle" alignment="TOP_LEFT" layoutX="15.0" layoutY="236.0" prefHeight="30.0" prefWidth="470.0" text="Обновление..." textFill="WHITE"> <ProgressBar fx:id="progress" disable="false" layoutX="-1.0" layoutY="376.0" opacity="1.0" prefHeight="24.0"
<font> prefWidth="600.0" progress="1.0" style=""/>
<Font name="System Bold" size="20.0" /> <!-- Update controls -->
</font> <Label fx:id="utitle" alignment="TOP_LEFT" layoutX="15.0" layoutY="236.0" prefHeight="30.0" prefWidth="470.0"
</Label> text="Обновление..." textFill="WHITE">
<ImageView fitHeight="160.0" fitWidth="160.0" layoutX="219.0" layoutY="70.0" y="-6.0"> <font>
<image> <Font name="System Bold" size="20.0"/>
<Image url="@../../images/icons/loading.gif" /> </font>
</image> </Label>
</ImageView> <ImageView fitHeight="160.0" fitWidth="160.0" layoutX="219.0" layoutY="70.0" y="-6.0">
</children> <image>
<stylesheets> <Image url="@../../images/icons/loading.gif"/>
<URL value="@update.css" /> </image>
</stylesheets> </ImageView>
</children>
<stylesheets>
<URL value="@update.css"/>
</stylesheets>
</Pane> </Pane>

View file

@ -15,8 +15,8 @@
import java.util.List; import java.util.List;
public class ClientLauncherWrapper { public class ClientLauncherWrapper {
public static final String MAGIC_ARG = "-Djdk.attach.allowAttachSelf"; public static final String MAGIC_ARG = "-Djdk.attach.allowAttachSelf";
public static void main(String[] arguments) throws IOException, InterruptedException { public static void main(String[] arguments) throws IOException, InterruptedException {
LogHelper.printVersion("Launcher"); LogHelper.printVersion("Launcher");
LogHelper.printLicense("Launcher"); LogHelper.printLicense("Launcher");

View file

@ -303,8 +303,7 @@ public static Process launch(
LogHelper.debug("Writing ClientLauncher params"); LogHelper.debug("Writing ClientLauncher params");
ClientLauncherContext context = new ClientLauncherContext(); ClientLauncherContext context = new ClientLauncherContext();
clientStarted = false; clientStarted = false;
if(writeParamsThread != null && writeParamsThread.isAlive()) if (writeParamsThread != null && writeParamsThread.isAlive()) {
{
writeParamsThread.interrupt(); writeParamsThread.interrupt();
} }
writeParamsThread = CommonHelper.newThread("Client params writter", true, () -> writeParamsThread = CommonHelper.newThread("Client params writter", true, () ->
@ -393,24 +392,20 @@ public static Process launch(
} }
// Let's rock! // Let's rock!
process = builder.start(); process = builder.start();
if(!LogHelper.isDebugEnabled()) { if (!LogHelper.isDebugEnabled()) {
for(int i=0;i<50;++i) for (int i = 0; i < 50; ++i) {
{ if (!process.isAlive()) {
if(!process.isAlive())
{
int exitCode = process.exitValue(); int exitCode = process.exitValue();
LogHelper.error("Process exit code %d", exitCode); LogHelper.error("Process exit code %d", exitCode);
if(writeParamsThread != null && writeParamsThread.isAlive()) writeParamsThread.interrupt(); if (writeParamsThread != null && writeParamsThread.isAlive()) writeParamsThread.interrupt();
break; break;
} }
if(clientStarted) if (clientStarted) {
{
break; break;
} }
Thread.sleep(200); Thread.sleep(200);
} }
if(!clientStarted) if (!clientStarted) {
{
LogHelper.error("Write Client Params not successful. Using debug mode for more information"); LogHelper.error("Write Client Params not successful. Using debug mode for more information");
} }
} }
@ -488,7 +483,7 @@ public static void main(String... args) throws Throwable {
// if (params.updateOptional.contains(s)) s.mark = true; // if (params.updateOptional.contains(s)) s.mark = true;
// else hdir.removeR(s.file); // else hdir.removeR(s.file);
//} //}
Launcher.profile.pushOptionalFile(clientHDir,false); Launcher.profile.pushOptionalFile(clientHDir, false);
Launcher.modulesManager.postInitModules(); Launcher.modulesManager.postInitModules();
// Start WatchService, and only then client // Start WatchService, and only then client
CommonHelper.newThread("Asset Directory Watcher", true, assetWatcher).start(); CommonHelper.newThread("Asset Directory Watcher", true, assetWatcher).start();

View file

@ -64,9 +64,9 @@ public static Path getAppDataDir() throws IOException {
public static Path getLauncherDir(String projectname) throws IOException { public static Path getLauncherDir(String projectname) throws IOException {
return getAppDataDir().resolve(projectname); return getAppDataDir().resolve(projectname);
} }
@LauncherAPI @LauncherAPI
public static Path getGuardDir() public static Path getGuardDir() {
{
return dir.resolve("guard"); return dir.resolve("guard");
} }

View file

@ -66,7 +66,7 @@ public static void makeJsonRequest(RequestInterface request, Runnable callback)
@LauncherAPI @LauncherAPI
public static void startTask(@SuppressWarnings("rawtypes") Task task) { public static void startTask(@SuppressWarnings("rawtypes") Task task) {
worker.execute(task); worker.execute(task);
} }
@LauncherAPI @LauncherAPI
@ -82,19 +82,15 @@ public static long getTotalMemory() {
} }
@LauncherAPI @LauncherAPI
public static int getClientJVMBits() public static int getClientJVMBits() {
{
return LauncherGuardManager.guard.getClientJVMBits(); return LauncherGuardManager.guard.getClientJVMBits();
} }
@LauncherAPI @LauncherAPI
public static long getJVMTotalMemory() public static long getJVMTotalMemory() {
{ if (getClientJVMBits() == 32) {
if(getClientJVMBits() == 32) return Math.min(getTotalMemory(), 1536);
{ } else {
return Math.min(getTotalMemory(),1536);
}
else
{
return getTotalMemory(); return getTotalMemory();
} }
} }
@ -105,8 +101,7 @@ public static HasherStore getDefaultHasherStore() {
} }
@LauncherAPI @LauncherAPI
public static void setAuthParams(AuthRequestEvent event) public static void setAuthParams(AuthRequestEvent event) {
{
LauncherGuardManager.guard.setProtectToken(event.protectToken); LauncherGuardManager.guard.setProtectToken(event.protectToken);
} }

View file

@ -6,7 +6,10 @@
import ru.gravit.launcher.profiles.ClientProfile; import ru.gravit.launcher.profiles.ClientProfile;
import ru.gravit.launcher.serialize.HInput; import ru.gravit.launcher.serialize.HInput;
import ru.gravit.launcher.serialize.HOutput; import ru.gravit.launcher.serialize.HOutput;
import ru.gravit.utils.helper.*; import ru.gravit.utils.helper.IOHelper;
import ru.gravit.utils.helper.JVMHelper;
import ru.gravit.utils.helper.LogHelper;
import ru.gravit.utils.helper.SecurityHelper;
import javax.crypto.BadPaddingException; import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException; import javax.crypto.IllegalBlockSizeException;
@ -112,7 +115,7 @@ public void read(HInput input) throws IOException, SignatureException {
for (int i = 0; i < lastHDirsCount; i++) { for (int i = 0; i < lastHDirsCount; i++) {
String name = IOHelper.verifyFileName(input.readString(255)); String name = IOHelper.verifyFileName(input.readString(255));
HashedDir hdir = new HashedDir(input); HashedDir hdir = new HashedDir(input);
lastHDirs.put(name,hdir); lastHDirs.put(name, hdir);
} }
} }

View file

@ -6,10 +6,16 @@
public interface LauncherGuardInterface { public interface LauncherGuardInterface {
String getName(); String getName();
Path getJavaBinPath(); Path getJavaBinPath();
int getClientJVMBits(); int getClientJVMBits();
void init(boolean clientInstance); void init(boolean clientInstance);
void addCustomParams(ClientLauncherContext context); void addCustomParams(ClientLauncherContext context);
void addCustomEnv(ClientLauncherContext context); void addCustomEnv(ClientLauncherContext context);
void setProtectToken(String token); void setProtectToken(String token);
} }

View file

@ -6,21 +6,17 @@
public class LauncherGuardManager { public class LauncherGuardManager {
public static LauncherGuardInterface guard; public static LauncherGuardInterface guard;
public static void initGuard(boolean clientInstance)
{ public static void initGuard(boolean clientInstance) {
if(ClientLauncher.isUsingWrapper()) if (ClientLauncher.isUsingWrapper()) {
{
guard = new LauncherWrapperGuard(); guard = new LauncherWrapperGuard();
} } else if (ClientLauncher.isDownloadJava()) {
else if(ClientLauncher.isDownloadJava())
{
guard = new LauncherJavaGuard(); guard = new LauncherJavaGuard();
} } else guard = new LauncherNoGuard();
else guard = new LauncherNoGuard();
guard.init(clientInstance); guard.init(clientInstance);
} }
public static Path getGuardJavaBinPath()
{ public static Path getGuardJavaBinPath() {
return guard.getJavaBinPath(); return guard.getJavaBinPath();
} }
} }

View file

@ -4,7 +4,9 @@
import ru.gravit.launcher.LauncherConfig; import ru.gravit.launcher.LauncherConfig;
import ru.gravit.launcher.client.ClientLauncherContext; import ru.gravit.launcher.client.ClientLauncherContext;
import ru.gravit.launcher.client.DirBridge; import ru.gravit.launcher.client.DirBridge;
import ru.gravit.utils.helper.*; import ru.gravit.utils.helper.IOHelper;
import ru.gravit.utils.helper.JVMHelper;
import ru.gravit.utils.helper.UnpackHelper;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
@ -23,13 +25,11 @@ public String getName() {
@Override @Override
public Path getJavaBinPath() { public Path getJavaBinPath() {
if(JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE) if (JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE) {
{
String projectName = Launcher.getConfig().projectname; String projectName = Launcher.getConfig().projectname;
String wrapperUnpackName = JVMHelper.JVM_BITS == 64 ? projectName.concat("64.exe") : projectName.concat("32.exe"); String wrapperUnpackName = JVMHelper.JVM_BITS == 64 ? projectName.concat("64.exe") : projectName.concat("32.exe");
return DirBridge.getGuardDir().resolve(wrapperUnpackName); return DirBridge.getGuardDir().resolve(wrapperUnpackName);
} } else
else
return IOHelper.resolveJavaBin(Paths.get(System.getProperty("java.home"))); return IOHelper.resolveJavaBin(Paths.get(System.getProperty("java.home")));
} }
@ -45,8 +45,8 @@ public void init(boolean clientInstance) {
String projectName = Launcher.getConfig().projectname; String projectName = Launcher.getConfig().projectname;
String wrapperUnpackName = JVMHelper.JVM_BITS == 64 ? projectName.concat("64.exe") : projectName.concat("32.exe"); String wrapperUnpackName = JVMHelper.JVM_BITS == 64 ? projectName.concat("64.exe") : projectName.concat("32.exe");
String antiInjectName = JVMHelper.JVM_BITS == 64 ? "AntiInject64.dll" : "AntiInject32.dll"; String antiInjectName = JVMHelper.JVM_BITS == 64 ? "AntiInject64.dll" : "AntiInject32.dll";
UnpackHelper.unpack(Launcher.getResourceURL(wrapperName, "guard"),DirBridge.getGuardDir().resolve(wrapperUnpackName)); UnpackHelper.unpack(Launcher.getResourceURL(wrapperName, "guard"), DirBridge.getGuardDir().resolve(wrapperUnpackName));
UnpackHelper.unpack(Launcher.getResourceURL(antiInjectName, "guard"),DirBridge.getGuardDir().resolve(antiInjectName)); UnpackHelper.unpack(Launcher.getResourceURL(antiInjectName, "guard"), DirBridge.getGuardDir().resolve(antiInjectName));
} catch (IOException e) { } catch (IOException e) {
throw new SecurityException(e); throw new SecurityException(e);
} }
@ -59,18 +59,17 @@ public void addCustomParams(ClientLauncherContext context) {
@Override @Override
public void addCustomEnv(ClientLauncherContext context) { public void addCustomEnv(ClientLauncherContext context) {
Map<String,String> env = context.builder.environment(); Map<String, String> env = context.builder.environment();
env.put("JAVA_HOME", System.getProperty("java.home")); env.put("JAVA_HOME", System.getProperty("java.home"));
LauncherConfig config = Launcher.getConfig(); LauncherConfig config = Launcher.getConfig();
env.put("GUARD_USERNAME", context.playerProfile.username); env.put("GUARD_USERNAME", context.playerProfile.username);
env.put("GUARD_PUBLICKEY", config.publicKey.getModulus().toString(16)); env.put("GUARD_PUBLICKEY", config.publicKey.getModulus().toString(16));
env.put("GUARD_PROJECTNAME", config.projectname); env.put("GUARD_PROJECTNAME", config.projectname);
if(protectToken != null) if (protectToken != null)
env.put("GUARD_TOKEN", protectToken); env.put("GUARD_TOKEN", protectToken);
if(config.guardLicenseName != null) if (config.guardLicenseName != null)
env.put("GUARD_LICENSE_NAME", config.guardLicenseName); env.put("GUARD_LICENSE_NAME", config.guardLicenseName);
if(config.guardLicenseKey != null) if (config.guardLicenseKey != null) {
{
env.put("GUARD_LICENSE_KEY", config.guardLicenseKey); env.put("GUARD_LICENSE_KEY", config.guardLicenseKey);
} }
} }

View file

@ -146,8 +146,7 @@ public void run(String[] args) throws ScriptException, NoSuchMethodException, IO
@Override @Override
public void preLoad() throws IOException, ScriptException { public void preLoad() throws IOException, ScriptException {
if(!isPreLoaded) if (!isPreLoaded) {
{
loadScript(Launcher.API_SCRIPT_FILE); loadScript(Launcher.API_SCRIPT_FILE);
loadScript(Launcher.CONFIG_SCRIPT_FILE); loadScript(Launcher.CONFIG_SCRIPT_FILE);
isPreLoaded = true; isPreLoaded = true;

View file

@ -64,23 +64,18 @@ public String getHWDisk() {
} }
} }
public String getSoundCardInfo() public String getSoundCardInfo() {
{ for (SoundCard soundcard : hardware.getSoundCards()) {
for(SoundCard soundcard : hardware.getSoundCards())
{
return soundcard.getName(); return soundcard.getName();
} }
return ""; return "";
} }
public String getMacAddr() public String getMacAddr() {
{ for (NetworkIF networkIF : hardware.getNetworkIFs()) {
for(NetworkIF networkIF : hardware.getNetworkIFs()) for (String ipv4 : networkIF.getIPv4addr()) {
{ if (ipv4.startsWith("127.")) continue;
for(String ipv4 : networkIF.getIPv4addr()) if (ipv4.startsWith("10.")) continue;
{
if(ipv4.startsWith("127.")) continue;
if(ipv4.startsWith("10.")) continue;
return networkIF.getMacaddr(); return networkIF.getMacaddr();
} }
} }
@ -110,22 +105,19 @@ public void printHardwareInformation() {
for (UsbDevice s : hardware.getUsbDevices(true)) { for (UsbDevice s : hardware.getUsbDevices(true)) {
LogHelper.debug("USBDevice Serial: %s Name: %s", s.getSerialNumber(), s.getName()); LogHelper.debug("USBDevice Serial: %s Name: %s", s.getSerialNumber(), s.getName());
} }
for(NetworkIF networkIF : hardware.getNetworkIFs()) for (NetworkIF networkIF : hardware.getNetworkIFs()) {
{
LogHelper.debug("Network Interface: %s mac: %s", networkIF.getName(), networkIF.getMacaddr()); LogHelper.debug("Network Interface: %s mac: %s", networkIF.getName(), networkIF.getMacaddr());
NetworkInterface network = networkIF.getNetworkInterface(); NetworkInterface network = networkIF.getNetworkInterface();
if(network.isLoopback() || network.isVirtual()) continue; if (network.isLoopback() || network.isVirtual()) continue;
LogHelper.debug("Network Interface display: %s name: %s", network.getDisplayName(), network.getName()); LogHelper.debug("Network Interface display: %s name: %s", network.getDisplayName(), network.getName());
for(String ipv4 : networkIF.getIPv4addr()) for (String ipv4 : networkIF.getIPv4addr()) {
{ if (ipv4.startsWith("127.")) continue;
if(ipv4.startsWith("127.")) continue; if (ipv4.startsWith("10.")) continue;
if(ipv4.startsWith("10.")) continue;
LogHelper.subDebug("IPv4: %s", ipv4); LogHelper.subDebug("IPv4: %s", ipv4);
} }
} }
for(SoundCard soundcard : hardware.getSoundCards()) for (SoundCard soundcard : hardware.getSoundCards()) {
{ LogHelper.debug("SoundCard %s", soundcard.getName());
LogHelper.debug("SoundCard %s", soundcard.getName());
} }
CentralProcessor processor = hardware.getProcessor(); CentralProcessor processor = hardware.getProcessor();
LogHelper.debug("Processor Model: %s ID: %s", processor.getModel(), processor.getProcessorID()); LogHelper.debug("Processor Model: %s ID: %s", processor.getModel(), processor.getProcessorID());

View file

@ -2,9 +2,9 @@
targetCompatibility = '1.8' targetCompatibility = '1.8'
dependencies { dependencies {
compile project(':libLauncher') compile project(':libLauncher')
compile 'org.java-websocket:Java-WebSocket:1.3.9' compile 'org.java-websocket:Java-WebSocket:1.3.9'
compile 'org.apache.httpcomponents:httpclient:4.5.7' compile 'org.apache.httpcomponents:httpclient:4.5.7'
compileOnly 'com.google.guava:guava:26.0-jre' compileOnly 'com.google.guava:guava:26.0-jre'
compile files('../compat/authlib/authlib-clean.jar') compile files('../compat/authlib/authlib-clean.jar')
} }

View file

@ -1,5 +1,14 @@
package ru.gravit.launcher.downloader; package ru.gravit.launcher.downloader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import ru.gravit.utils.helper.IOHelper;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URI; import java.net.URI;
@ -8,40 +17,32 @@
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import ru.gravit.utils.helper.IOHelper;
public class ListDownloader { public class ListDownloader {
public void download(String base, List<String> applies, Path dstDirFile) throws IOException, URISyntaxException { public void download(String base, List<String> applies, Path dstDirFile) throws IOException, URISyntaxException {
try(CloseableHttpClient httpclient = HttpClients.custom() try (CloseableHttpClient httpclient = HttpClients.custom()
.setRedirectStrategy(new LaxRedirectStrategy()) .setRedirectStrategy(new LaxRedirectStrategy())
.build()) { .build()) {
HttpGet get = null; HttpGet get = null;
for (String apply : applies) { for (String apply : applies) {
URI u = new URL(base.concat(apply)).toURI(); URI u = new URL(base.concat(apply)).toURI();
if (get == null) get = new HttpGet(u); if (get == null) get = new HttpGet(u);
else { else {
get.reset(); get.reset();
get.setURI(u); get.setURI(u);
} }
httpclient.execute(get, new FileDownloadResponseHandler(dstDirFile.resolve(apply))); httpclient.execute(get, new FileDownloadResponseHandler(dstDirFile.resolve(apply)));
} }
} }
} }
static class FileDownloadResponseHandler implements ResponseHandler<Path> { static class FileDownloadResponseHandler implements ResponseHandler<Path> {
private final Path target; private final Path target;
public FileDownloadResponseHandler(Path target) { public FileDownloadResponseHandler(Path target) {
this.target = target; this.target = target;
} }
@Override @Override
public Path handleResponse(HttpResponse response) throws ClientProtocolException, IOException { public Path handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
InputStream source = response.getEntity().getContent(); InputStream source = response.getEntity().getContent();

View file

@ -58,9 +58,9 @@ public R request() throws Exception {
if (!started.compareAndSet(false, true)) if (!started.compareAndSet(false, true))
throw new IllegalStateException("Request already started"); throw new IllegalStateException("Request already started");
R wsResult = null; R wsResult = null;
if(config.isNettyEnabled) if (config.isNettyEnabled)
wsResult = requestWebSockets(); wsResult = requestWebSockets();
if(wsResult != null) return wsResult; if (wsResult != null) return wsResult;
// Make request to LaunchServer // Make request to LaunchServer
try (Socket socket = IOHelper.newSocket()) { try (Socket socket = IOHelper.newSocket()) {
socket.connect(IOHelper.resolve(config.address)); socket.connect(IOHelper.resolve(config.address));
@ -71,10 +71,11 @@ public R request() throws Exception {
} }
} }
} }
protected R requestWebSockets() throws Exception
{ protected R requestWebSockets() throws Exception {
return null; return null;
} }
@LauncherAPI @LauncherAPI
protected abstract R requestDo(HInput input, HOutput output) throws Exception; protected abstract R requestDo(HInput input, HOutput output) throws Exception;

View file

@ -43,6 +43,7 @@ public AuthRequest(LauncherConfig config, String login, byte[] password, HWID hw
this.auth_id = auth_id; this.auth_id = auth_id;
customText = ""; customText = "";
} }
@LauncherAPI @LauncherAPI
public AuthRequest(LauncherConfig config, String login, byte[] password, HWID hwid, String customText, String auth_id) { public AuthRequest(LauncherConfig config, String login, byte[] password, HWID hwid, String customText, String auth_id) {
super(config); super(config);
@ -57,11 +58,12 @@ public AuthRequest(LauncherConfig config, String login, byte[] password, HWID hw
public AuthRequest(String login, byte[] password, HWID hwid) { public AuthRequest(String login, byte[] password, HWID hwid) {
this(null, login, password, hwid); this(null, login, password, hwid);
} }
@Override @Override
public AuthRequestEvent requestWebSockets() throws Exception public AuthRequestEvent requestWebSockets() throws Exception {
{
return (AuthRequestEvent) LegacyRequestBridge.sendRequest(this); return (AuthRequestEvent) LegacyRequestBridge.sendRequest(this);
} }
@LauncherAPI @LauncherAPI
public AuthRequest(String login, byte[] password, HWID hwid, String auth_id) { public AuthRequest(String login, byte[] password, HWID hwid, String auth_id) {
this(null, login, password, hwid, auth_id); this(null, login, password, hwid, auth_id);
@ -71,6 +73,7 @@ public AuthRequest(String login, byte[] password, HWID hwid, String auth_id) {
public Integer getLegacyType() { public Integer getLegacyType() {
return RequestType.AUTH.getNumber(); return RequestType.AUTH.getNumber();
} }
/*public class EchoRequest implements RequestInterface /*public class EchoRequest implements RequestInterface
{ {
String echo; String echo;

View file

@ -21,11 +21,12 @@ public SetProfileRequest(LauncherConfig config, ClientProfile profile) {
this.profile = profile; this.profile = profile;
this.client = profile.getTitle(); this.client = profile.getTitle();
} }
@Override @Override
public SetProfileRequestEvent requestWebSockets() throws Exception public SetProfileRequestEvent requestWebSockets() throws Exception {
{
return (SetProfileRequestEvent) LegacyRequestBridge.sendRequest(this); return (SetProfileRequestEvent) LegacyRequestBridge.sendRequest(this);
} }
@Override @Override
public Integer getLegacyType() { public Integer getLegacyType() {
return RequestType.SETPROFILE.getNumber(); return RequestType.SETPROFILE.getNumber();

View file

@ -47,15 +47,14 @@ public static void update(LauncherConfig config, LauncherRequestEvent result) th
builder.inheritIO(); builder.inheritIO();
// Rewrite and start new instance // Rewrite and start new instance
if(result.binary != null) if (result.binary != null)
IOHelper.write(BINARY_PATH, result.binary); IOHelper.write(BINARY_PATH, result.binary);
else else {
{ URLConnection connection = IOHelper.newConnection(new URL(result.url));
URLConnection connection = IOHelper.newConnection(new URL(result.url)); connection.connect();
connection.connect(); try (OutputStream stream = connection.getOutputStream()) {
try(OutputStream stream = connection.getOutputStream()) { IOHelper.transfer(BINARY_PATH, stream);
IOHelper.transfer(BINARY_PATH, stream); }
}
} }
builder.start(); builder.start();
@ -70,10 +69,9 @@ public LauncherRequest() {
} }
@Override @Override
public LauncherRequestEvent requestWebSockets() throws Exception public LauncherRequestEvent requestWebSockets() throws Exception {
{
LauncherRequestEvent result = (LauncherRequestEvent) LegacyRequestBridge.sendRequest(this); LauncherRequestEvent result = (LauncherRequestEvent) LegacyRequestBridge.sendRequest(this);
if(result.needUpdate) update(config, result); if (result.needUpdate) update(config, result);
return result; return result;
} }

View file

@ -33,8 +33,7 @@ public Integer getLegacyType() {
} }
@Override @Override
public ProfilesRequestEvent requestWebSockets() throws Exception public ProfilesRequestEvent requestWebSockets() throws Exception {
{
return (ProfilesRequestEvent) LegacyRequestBridge.sendRequest(this); return (ProfilesRequestEvent) LegacyRequestBridge.sendRequest(this);
} }

View file

@ -26,8 +26,7 @@ public UpdateListRequest(LauncherConfig config) {
} }
@Override @Override
public UpdateListRequestEvent requestWebSockets() throws Exception public UpdateListRequestEvent requestWebSockets() throws Exception {
{
return (UpdateListRequestEvent) LegacyRequestBridge.sendRequest(this); return (UpdateListRequestEvent) LegacyRequestBridge.sendRequest(this);
} }

View file

@ -197,9 +197,9 @@ private static void fillActionsQueue(Queue<UpdateAction> queue, HashedDir mismat
} }
} }
} }
@Override @Override
public UpdateRequestEvent requestWebSockets() throws Exception public UpdateRequestEvent requestWebSockets() throws Exception {
{
return (UpdateRequestEvent) LegacyRequestBridge.sendRequest(this); return (UpdateRequestEvent) LegacyRequestBridge.sendRequest(this);
} }

View file

@ -1,37 +1,36 @@
package ru.gravit.launcher.request.websockets; package ru.gravit.launcher.request.websockets;
import java.net.URI;
import java.util.Map;
import org.java_websocket.client.WebSocketClient; import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455; import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshake;
import ru.gravit.utils.helper.LogHelper; import ru.gravit.utils.helper.LogHelper;
import java.net.URI;
import java.util.Map;
public class ClientJSONPoint extends WebSocketClient { public class ClientJSONPoint extends WebSocketClient {
public ClientJSONPoint(URI serverUri, Map<String, String> httpHeaders, int connectTimeout) { public ClientJSONPoint(URI serverUri, Map<String, String> httpHeaders, int connectTimeout) {
super(serverUri, new Draft_6455(), httpHeaders, connectTimeout); super(serverUri, new Draft_6455(), httpHeaders, connectTimeout);
} }
@Override @Override
public void onOpen(ServerHandshake handshakedata) { public void onOpen(ServerHandshake handshakedata) {
}
@Override }
public void onMessage(String message) {
}
@Override @Override
public void onClose(int code, String reason, boolean remote) { public void onMessage(String message) {
LogHelper.debug("Disconnected: " + code + " " + remote + " " + reason != null ? reason : "no reason"); }
}
@Override @Override
public void onError(Exception ex) { public void onClose(int code, String reason, boolean remote) {
LogHelper.error(ex); LogHelper.debug("Disconnected: " + code + " " + remote + " " + reason != null ? reason : "no reason");
} }
@Override
public void onError(Exception ex) {
LogHelper.error(ex);
}
} }

View file

@ -23,7 +23,7 @@ public class ClientWebSocketService extends ClientJSONPoint {
private HashSet<EventHandler> handlers; private HashSet<EventHandler> handlers;
public ClientWebSocketService(GsonBuilder gsonBuilder, String address, int i) { public ClientWebSocketService(GsonBuilder gsonBuilder, String address, int i) {
super(createURL(address), Collections.emptyMap(), i); super(createURL(address), Collections.emptyMap(), i);
requests = new HashMap<>(); requests = new HashMap<>();
results = new HashMap<>(); results = new HashMap<>();
handlers = new HashSet<>(); handlers = new HashSet<>();
@ -33,32 +33,34 @@ public ClientWebSocketService(GsonBuilder gsonBuilder, String address, int i) {
this.gsonBuilder.registerTypeAdapter(HashedEntry.class, new HashedEntryAdapter()); this.gsonBuilder.registerTypeAdapter(HashedEntry.class, new HashedEntryAdapter());
this.gson = gsonBuilder.create(); this.gson = gsonBuilder.create();
} }
private static URI createURL(String address) {
try { private static URI createURL(String address) {
URI u = new URI(address); try {
return u; URI u = new URI(address);
} catch (Throwable e) { return u;
LogHelper.error(e); } catch (Throwable e) {
return null; LogHelper.error(e);
} return null;
} }
@Override }
public void onMessage(String message) {
@Override
public void onMessage(String message) {
ResultInterface result = gson.fromJson(message, ResultInterface.class); ResultInterface result = gson.fromJson(message, ResultInterface.class);
for(EventHandler handler : handlers) for (EventHandler handler : handlers) {
{
handler.process(result); handler.process(result);
} }
} }
@Override @Override
public void onError(Exception e) public void onError(Exception e) {
{
LogHelper.error(e); LogHelper.error(e);
} }
public Class<? extends RequestInterface> getRequestClass(String key) { public Class<? extends RequestInterface> getRequestClass(String key) {
return requests.get(key); return requests.get(key);
} }
public Class<? extends ResultInterface> getResultClass(String key) { public Class<? extends ResultInterface> getResultClass(String key) {
return results.get(key); return results.get(key);
} }
@ -91,20 +93,20 @@ public void registerResults() {
registerResult("update", UpdateRequestEvent.class); registerResult("update", UpdateRequestEvent.class);
} }
public void registerHandler(EventHandler eventHandler) public void registerHandler(EventHandler eventHandler) {
{
handlers.add(eventHandler); handlers.add(eventHandler);
} }
public void sendObject(Object obj) throws IOException { public void sendObject(Object obj) throws IOException {
send(gson.toJson(obj, RequestInterface.class)); send(gson.toJson(obj, RequestInterface.class));
} }
public void sendObject(Object obj, Type type) throws IOException { public void sendObject(Object obj, Type type) throws IOException {
send(gson.toJson(obj, type)); send(gson.toJson(obj, type));
} }
@FunctionalInterface @FunctionalInterface
public interface EventHandler public interface EventHandler {
{
void process(ResultInterface resultInterface); void process(ResultInterface resultInterface);
} }
} }

View file

@ -8,46 +8,46 @@
import ru.gravit.utils.helper.LogHelper; import ru.gravit.utils.helper.LogHelper;
import java.io.IOException; import java.io.IOException;
public class LegacyRequestBridge { public class LegacyRequestBridge {
public static WaitEventHandler waitEventHandler = new WaitEventHandler(); public static WaitEventHandler waitEventHandler = new WaitEventHandler();
public static ClientWebSocketService service; public static ClientWebSocketService service;
public static ResultInterface sendRequest(RequestInterface request) throws IOException, InterruptedException { public static ResultInterface sendRequest(RequestInterface request) throws IOException, InterruptedException {
WaitEventHandler.ResultEvent e = new WaitEventHandler.ResultEvent(); WaitEventHandler.ResultEvent e = new WaitEventHandler.ResultEvent();
e.type = request.getType(); e.type = request.getType();
waitEventHandler.requests.add(e); waitEventHandler.requests.add(e);
service.sendObject(request); service.sendObject(request);
while(!e.ready) while (!e.ready) {
{ synchronized (e) {
synchronized(e)
{
e.wait(); e.wait();
LogHelper.debug("WAIT OK"); LogHelper.debug("WAIT OK");
} }
} }
ResultInterface result = e.result; ResultInterface result = e.result;
waitEventHandler.requests.remove(e); waitEventHandler.requests.remove(e);
if(e.result.getType().equals("error")) if (e.result.getType().equals("error")) {
{
ErrorRequestEvent errorRequestEvent = (ErrorRequestEvent) e.result; ErrorRequestEvent errorRequestEvent = (ErrorRequestEvent) e.result;
throw new RequestException(errorRequestEvent.error); throw new RequestException(errorRequestEvent.error);
} }
return result; return result;
} }
public static void initWebSockets(String address)
{ public static void initWebSockets(String address) {
service = new ClientWebSocketService(new GsonBuilder(), address, 5000); service = new ClientWebSocketService(new GsonBuilder(), address, 5000);
service.registerResults(); service.registerResults();
service.registerRequests(); service.registerRequests();
service.registerHandler(waitEventHandler); service.registerHandler(waitEventHandler);
try { try {
if(!service.connectBlocking()) LogHelper.error("Error connecting"); if (!service.connectBlocking()) LogHelper.error("Error connecting");
LogHelper.debug("Connect to %s",address); LogHelper.debug("Connect to %s", address);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
static { static {
if(Launcher.getConfig().nettyPort != 0) if (Launcher.getConfig().nettyPort != 0)
initWebSockets(Launcher.getConfig().nettyAddress); initWebSockets(Launcher.getConfig().nettyAddress);
} }
} }

View file

@ -7,17 +7,15 @@
public class WaitEventHandler implements ClientWebSocketService.EventHandler { public class WaitEventHandler implements ClientWebSocketService.EventHandler {
public HashSet<ResultEvent> requests = new HashSet<>(); public HashSet<ResultEvent> requests = new HashSet<>();
@Override @Override
public void process(ResultInterface result) { public void process(ResultInterface result) {
LogHelper.debug("Processing event %s type", result.getType()); LogHelper.debug("Processing event %s type", result.getType());
for(ResultEvent r : requests) for (ResultEvent r : requests) {
{
LogHelper.subDebug("Processing %s", r.type); LogHelper.subDebug("Processing %s", r.type);
if(r.type.equals(result.getType()) || result.getType().equals("error")) if (r.type.equals(result.getType()) || result.getType().equals("error")) {
{
LogHelper.debug("Event %s type", r.type); LogHelper.debug("Event %s type", r.type);
synchronized (r) synchronized (r) {
{
r.result = result; r.result = result;
r.ready = true; r.ready = true;
r.notifyAll(); r.notifyAll();
@ -25,8 +23,8 @@ public void process(ResultInterface result) {
} }
} }
} }
public static class ResultEvent
{ public static class ResultEvent {
public ResultInterface result; public ResultInterface result;
public String type; public String type;
public boolean ready; public boolean ready;

View file

@ -14,10 +14,10 @@
jar { jar {
from { configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } } from { configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } }
manifest.attributes("Main-Class": mainClassName, manifest.attributes("Main-Class": mainClassName,
"Premain-Class": mainAgentName, "Premain-Class": mainAgentName,
"Can-Redefine-Classes": "true", "Can-Redefine-Classes": "true",
"Can-Retransform-Classes": "true", "Can-Retransform-Classes": "true",
"Can-Set-Native-Method-Prefix": "true") "Can-Set-Native-Method-Prefix": "true")
} }
dependencies { dependencies {

View file

@ -1,7 +1,7 @@
package ru.gravit.launcher.server; package ru.gravit.launcher.server;
import ru.gravit.launcher.managers.SimpleModulesConfigManager;
import ru.gravit.launcher.managers.SimpleModuleManager; import ru.gravit.launcher.managers.SimpleModuleManager;
import ru.gravit.launcher.managers.SimpleModulesConfigManager;
import ru.gravit.utils.PublicURLClassLoader; import ru.gravit.utils.PublicURLClassLoader;
import java.net.URL; import java.net.URL;

View file

@ -8,7 +8,10 @@
import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType; import java.lang.invoke.MethodType;
import java.nio.file.*; import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.BasicFileAttributes;
import java.util.jar.JarFile; import java.util.jar.JarFile;

View file

@ -18,8 +18,6 @@
import ru.gravit.utils.helper.SecurityHelper; import ru.gravit.utils.helper.SecurityHelper;
import java.io.IOException; import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType; import java.lang.invoke.MethodType;
@ -88,8 +86,8 @@ public boolean loopAuth(int count, int sleeptime) {
try { try {
Thread.sleep(sleeptime); Thread.sleep(sleeptime);
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
LogHelper.error(e); LogHelper.error(e);
return false; return false;
} }
} }
@ -102,14 +100,12 @@ public static void initGson() {
Launcher.gson = Launcher.gsonBuilder.create(); Launcher.gson = Launcher.gsonBuilder.create();
} }
public void run(String... args) throws Throwable public void run(String... args) throws Throwable {
{
gsonBuiler = new GsonBuilder(); gsonBuiler = new GsonBuilder();
gsonBuiler.setPrettyPrinting(); gsonBuiler.setPrettyPrinting();
gson = gsonBuiler.create(); gson = gsonBuiler.create();
initGson(); initGson();
if(args.length > 0 && args[0].equals("setup") && !disableSetup) if (args.length > 0 && args[0].equals("setup") && !disableSetup) {
{
LogHelper.debug("Read ServerWrapperConfig.json"); LogHelper.debug("Read ServerWrapperConfig.json");
loadConfig(); loadConfig();
ServerWrapperSetup setup = new ServerWrapperSetup(); ServerWrapperSetup setup = new ServerWrapperSetup();
@ -123,7 +119,7 @@ public void run(String... args) throws Throwable
LogHelper.debug("Read ServerWrapperConfig.json"); LogHelper.debug("Read ServerWrapperConfig.json");
loadConfig(); loadConfig();
updateLauncherConfig(); updateLauncherConfig();
if(config.env != null) Launcher.applyLauncherEnv(config.env); if (config.env != null) Launcher.applyLauncherEnv(config.env);
else Launcher.applyLauncherEnv(LauncherConfig.LauncherEnvironment.STD); else Launcher.applyLauncherEnv(LauncherConfig.LauncherEnvironment.STD);
if (config.logFile != null) LogHelper.addOutput(IOHelper.newWriter(Paths.get(config.logFile), true)); if (config.logFile != null) LogHelper.addOutput(IOHelper.newWriter(Paths.get(config.logFile), true));
if (config.syncAuth) auth(); if (config.syncAuth) auth();
@ -170,24 +166,20 @@ public void run(String... args) throws Throwable
LogHelper.info("Minecraft Version (for profile): %s", wrapper.profile == null ? "unknown" : wrapper.profile.getVersion().name); LogHelper.info("Minecraft Version (for profile): %s", wrapper.profile == null ? "unknown" : wrapper.profile.getVersion().name);
LogHelper.info("Start Minecraft Server"); LogHelper.info("Start Minecraft Server");
LogHelper.debug("Invoke main method %s", mainClass.getName()); LogHelper.debug("Invoke main method %s", mainClass.getName());
if(config.args == null) if (config.args == null) {
{
String[] real_args; String[] real_args;
if(args.length > 0) if (args.length > 0) {
{
real_args = new String[args.length - 1]; real_args = new String[args.length - 1];
System.arraycopy(args, 1, real_args, 0, args.length - 1); System.arraycopy(args, 1, real_args, 0, args.length - 1);
} else real_args = args; } else real_args = args;
mainMethod.invoke(real_args); mainMethod.invoke(real_args);
} } else {
else
{
mainMethod.invoke(config.args); mainMethod.invoke(config.args);
} }
} }
public void updateLauncherConfig()
{ public void updateLauncherConfig() {
LauncherConfig cfg = null; LauncherConfig cfg = null;
try { try {

View file

@ -9,8 +9,8 @@
public class ServerWrapperCommands { public class ServerWrapperCommands {
public final CommandHandler commandHandler; public final CommandHandler commandHandler;
public void registerCommands()
{ public void registerCommands() {
//FUTURE //FUTURE
} }

View file

@ -1,15 +1,12 @@
package ru.gravit.launcher.server.setup; package ru.gravit.launcher.server.setup;
import ru.gravit.launcher.Launcher;
import ru.gravit.launcher.LauncherConfig; import ru.gravit.launcher.LauncherConfig;
import ru.gravit.launcher.server.ServerWrapper; import ru.gravit.launcher.server.ServerWrapper;
import ru.gravit.utils.PublicURLClassLoader; import ru.gravit.utils.PublicURLClassLoader;
import ru.gravit.utils.helper.IOHelper; import ru.gravit.utils.helper.IOHelper;
import ru.gravit.utils.helper.JVMHelper; import ru.gravit.utils.helper.JVMHelper;
import ru.gravit.utils.helper.LogHelper; import ru.gravit.utils.helper.LogHelper;
import ru.gravit.utils.helper.SecurityHelper;
import java.io.BufferedWriter;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.net.URL; import java.net.URL;
@ -21,8 +18,8 @@
public class ServerWrapperSetup { public class ServerWrapperSetup {
public ServerWrapperCommands commands; public ServerWrapperCommands commands;
public PublicURLClassLoader urlClassLoader; public PublicURLClassLoader urlClassLoader;
public void run() throws IOException
{ public void run() throws IOException {
ServerWrapper wrapper = ServerWrapper.wrapper; ServerWrapper wrapper = ServerWrapper.wrapper;
System.out.println("Print jar filename:"); System.out.println("Print jar filename:");
String jarName = commands.commandHandler.readLine(); String jarName = commands.commandHandler.readLine();
@ -32,15 +29,13 @@ public void run() throws IOException
urlClassLoader = new PublicURLClassLoader(new URL[]{jarURL}); urlClassLoader = new PublicURLClassLoader(new URL[]{jarURL});
LogHelper.info("Check jar MainClass"); LogHelper.info("Check jar MainClass");
String mainClassName = file.getManifest().getMainAttributes().getValue("Main-Class"); String mainClassName = file.getManifest().getMainAttributes().getValue("Main-Class");
if(mainClassName == null) if (mainClassName == null) {
{
LogHelper.error("Main-Class not found in MANIFEST"); LogHelper.error("Main-Class not found in MANIFEST");
return; return;
} }
try { try {
Class mainClass = Class.forName(mainClassName, false, urlClassLoader); Class mainClass = Class.forName(mainClassName, false, urlClassLoader);
} catch (ClassNotFoundException e) } catch (ClassNotFoundException e) {
{
LogHelper.error(e); LogHelper.error(e);
return; return;
} }
@ -52,21 +47,18 @@ public void run() throws IOException
wrapper.config.mainclass = mainClassName; wrapper.config.mainclass = mainClassName;
wrapper.config.address = address; wrapper.config.address = address;
wrapper.config.port = port; wrapper.config.port = port;
if(!Files.exists(ServerWrapper.publicKeyFile)) if (!Files.exists(ServerWrapper.publicKeyFile)) {
{
LogHelper.error("public.key not found"); LogHelper.error("public.key not found");
for(int i=0;i<10;++i) for (int i = 0; i < 10; ++i) {
{
System.out.println("Print F to continue:"); System.out.println("Print F to continue:");
String printF = commands.commandHandler.readLine(); String printF = commands.commandHandler.readLine();
if(printF.equals("stop")) return; if (printF.equals("stop")) return;
if(Files.exists(ServerWrapper.publicKeyFile)) break; if (Files.exists(ServerWrapper.publicKeyFile)) break;
else LogHelper.error("public.key not found"); else LogHelper.error("public.key not found");
} }
} }
boolean stopOnError = wrapper.config.stopOnError; boolean stopOnError = wrapper.config.stopOnError;
for(int i=0;i<10;++i) for (int i = 0; i < 10; ++i) {
{
System.out.println("Print server account login:"); System.out.println("Print server account login:");
String login = commands.commandHandler.readLine(); String login = commands.commandHandler.readLine();
System.out.println("Print server account password:"); System.out.println("Print server account password:");
@ -79,12 +71,9 @@ public void run() throws IOException
wrapper.config.stopOnError = false; wrapper.config.stopOnError = false;
LauncherConfig cfg = null; LauncherConfig cfg = null;
if(wrapper.auth()) if (wrapper.auth()) {
{
break; break;
} } else {
else
{
LogHelper.error("Auth error. Recheck account params"); LogHelper.error("Auth error. Recheck account params");
} }
} }
@ -94,21 +83,17 @@ public void run() throws IOException
Path startScript; Path startScript;
if (JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE) startScript = Paths.get("start.bat"); if (JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE) startScript = Paths.get("start.bat");
else startScript = Paths.get("start.sh"); else startScript = Paths.get("start.sh");
if(Files.exists(startScript)) if (Files.exists(startScript)) {
{
LogHelper.warning("start script found. Move to start.bak"); LogHelper.warning("start script found. Move to start.bak");
Path startScriptBak = Paths.get("start.bak"); Path startScriptBak = Paths.get("start.bak");
IOHelper.move(startScript, startScriptBak); IOHelper.move(startScript, startScriptBak);
} }
try(Writer writer = IOHelper.newWriter(startScript)) try (Writer writer = IOHelper.newWriter(startScript)) {
{ if (JVMHelper.OS_TYPE == JVMHelper.OS.LINUX) {
if(JVMHelper.OS_TYPE == JVMHelper.OS.LINUX)
{
writer.append("#!/bin/sh\n\n"); writer.append("#!/bin/sh\n\n");
} }
writer.append("java "); writer.append("java ");
if(mainClassName.contains("bungee")) if (mainClassName.contains("bungee")) {
{
LogHelper.info("Found BungeeCord mainclass. Modules dir change to modules_srv"); LogHelper.info("Found BungeeCord mainclass. Modules dir change to modules_srv");
writer.append(JVMHelper.jvmProperty("serverwrapper.modulesDir", "modules_srv")); writer.append(JVMHelper.jvmProperty("serverwrapper.modulesDir", "modules_srv"));
writer.append(" "); writer.append(" ");
@ -117,8 +102,7 @@ public void run() throws IOException
writer.append("-cp "); writer.append("-cp ");
String pathServerWrapper = IOHelper.getCodeSource(ServerWrapper.class).getFileName().toString(); String pathServerWrapper = IOHelper.getCodeSource(ServerWrapper.class).getFileName().toString();
writer.append(pathServerWrapper); writer.append(pathServerWrapper);
if(JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE) if (JVMHelper.OS_TYPE == JVMHelper.OS.MUSTDIE) {
{
writer.append(";"); writer.append(";");
} else writer.append(":"); } else writer.append(":");
writer.append(jarName); writer.append(jarName);

View file

@ -2,7 +2,7 @@
targetCompatibility = '1.8' targetCompatibility = '1.8'
dependencies { dependencies {
compileOnly 'org.fusesource.jansi:jansi:1.17.1' compileOnly 'org.fusesource.jansi:jansi:1.17.1'
compileOnly 'jline:jline:2.14.6' compileOnly 'jline:jline:2.14.6'
compile 'com.google.code.gson:gson:2.8.5' compile 'com.google.code.gson:gson:2.8.5'
} }

View file

@ -42,9 +42,9 @@ public ClientPermissions(long data) {
canUSR3 = (data & (1 << 4)) != 0; canUSR3 = (data & (1 << 4)) != 0;
canBot = (data & (1 << 5)) != 0; canBot = (data & (1 << 5)) != 0;
} }
@LauncherAPI @LauncherAPI
public long toLong() public long toLong() {
{
long result = 0; long result = 0;
result |= canAdmin ? 0 : 1; result |= canAdmin ? 0 : 1;
result |= canServer ? 0 : (1 << 1); result |= canServer ? 0 : (1 << 1);

View file

@ -125,10 +125,8 @@ public static Version getVersion() {
return new Version(MAJOR, MINOR, PATCH, BUILD, RELEASE); return new Version(MAJOR, MINOR, PATCH, BUILD, RELEASE);
} }
public static void applyLauncherEnv(LauncherConfig.LauncherEnvironment env) public static void applyLauncherEnv(LauncherConfig.LauncherEnvironment env) {
{ switch (env) {
switch (env)
{
case DEV: case DEV:
LogHelper.setDevEnabled(true); LogHelper.setDevEnabled(true);
LogHelper.setStacktraceEnabled(true); LogHelper.setStacktraceEnabled(true);

View file

@ -46,7 +46,7 @@ public static AutogenConfig getAutogenConfig() {
@LauncherAPI @LauncherAPI
public LauncherConfig(HInput input) throws IOException, InvalidKeySpecException { public LauncherConfig(HInput input) throws IOException, InvalidKeySpecException {
address = InetSocketAddress.createUnresolved( config.address, config.port); address = InetSocketAddress.createUnresolved(config.address, config.port);
publicKey = SecurityHelper.toPublicRSAKey(input.readByteArray(SecurityHelper.CRYPTO_MAX_LENGTH)); publicKey = SecurityHelper.toPublicRSAKey(input.readByteArray(SecurityHelper.CRYPTO_MAX_LENGTH));
projectname = config.projectname; projectname = config.projectname;
clientPort = config.clientPort; clientPort = config.clientPort;

View file

@ -27,7 +27,7 @@ public String getSerializeString() {
public int getLevel() //Уровень доверия, насколько уникальные значения public int getLevel() //Уровень доверия, насколько уникальные значения
{ {
int result = 0; int result = 0;
if (totalMemory != 0) result+=8; if (totalMemory != 0) result += 8;
if (serialNumber != null && !serialNumber.equals("unknown")) result += 12; if (serialNumber != null && !serialNumber.equals("unknown")) result += 12;
if (HWDiskSerial != null && !HWDiskSerial.equals("unknown")) result += 30; if (HWDiskSerial != null && !HWDiskSerial.equals("unknown")) result += 30;
if (processorID != null && !processorID.equals("unknown")) result += 10; if (processorID != null && !processorID.equals("unknown")) result += 10;
@ -37,16 +37,15 @@ public int getLevel() //Уровень доверия, насколько уни
@Override @Override
public int compare(HWID hwid) { public int compare(HWID hwid) {
if(hwid instanceof OshiHWID) if (hwid instanceof OshiHWID) {
{
int rate = 0; int rate = 0;
OshiHWID oshi = (OshiHWID) hwid; OshiHWID oshi = (OshiHWID) hwid;
if(Math.abs(oshi.totalMemory - totalMemory) < 1024*1024) rate+=5; if (Math.abs(oshi.totalMemory - totalMemory) < 1024 * 1024) rate += 5;
if(oshi.totalMemory == totalMemory) rate+=15; if (oshi.totalMemory == totalMemory) rate += 15;
if(oshi.HWDiskSerial.equals(HWDiskSerial)) rate+=45; if (oshi.HWDiskSerial.equals(HWDiskSerial)) rate += 45;
if(oshi.processorID.equals(processorID)) rate+=18; if (oshi.processorID.equals(processorID)) rate += 18;
if(oshi.serialNumber.equals(serialNumber)) rate+=15; if (oshi.serialNumber.equals(serialNumber)) rate += 15;
if(!oshi.macAddr.isEmpty() && oshi.macAddr.equals(macAddr)) rate+=19; if (!oshi.macAddr.isEmpty() && oshi.macAddr.equals(macAddr)) rate += 19;
return rate; return rate;
} }
return 0; return 0;

View file

@ -10,8 +10,10 @@
public class AuthRequestEvent implements EventInterface, ResultInterface { public class AuthRequestEvent implements EventInterface, ResultInterface {
private static final UUID uuid = UUID.fromString("77e1bfd7-adf9-4f5d-87d6-a7dd068deb74"); private static final UUID uuid = UUID.fromString("77e1bfd7-adf9-4f5d-87d6-a7dd068deb74");
public AuthRequestEvent() { public AuthRequestEvent() {
} }
@LauncherNetworkAPI @LauncherNetworkAPI
public String error; public String error;
@LauncherNetworkAPI @LauncherNetworkAPI

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