mirror of
https://github.com/GravitLauncher/Launcher
synced 2024-11-15 03:31:15 +03:00
IDEA Code Reformat
This commit is contained in:
parent
f9b8bd2947
commit
874a30eb6b
81 changed files with 740 additions and 697 deletions
|
@ -106,7 +106,7 @@ public static final class Config extends ConfigObject {
|
|||
private final StringConfigEntry address;
|
||||
private final String bindAddress;
|
||||
|
||||
private Config(BlockConfigEntry block, Path coredir,LaunchServer server) {
|
||||
private Config(BlockConfigEntry block, Path coredir, LaunchServer server) {
|
||||
super(block);
|
||||
address = block.getEntry("address", StringConfigEntry.class);
|
||||
port = VerifyHelper.verifyInt(block.getEntryValue("port", IntegerConfigEntry.class),
|
||||
|
@ -129,7 +129,7 @@ private Config(BlockConfigEntry block, Path coredir,LaunchServer server) {
|
|||
block.getEntry("authHandlerConfig", BlockConfigEntry.class));
|
||||
authProvider = new AuthProvider[1];
|
||||
authProvider[0] = AuthProvider.newProvider(block.getEntryValue("authProvider", StringConfigEntry.class),
|
||||
block.getEntry("authProviderConfig", BlockConfigEntry.class),server);
|
||||
block.getEntry("authProviderConfig", BlockConfigEntry.class), server);
|
||||
textureProvider = TextureProvider.newProvider(block.getEntryValue("textureProvider", StringConfigEntry.class),
|
||||
block.getEntry("textureProviderConfig", BlockConfigEntry.class));
|
||||
hwidHandler = HWIDHandler.newHandler(block.getEntryValue("hwidHandler", StringConfigEntry.class),
|
||||
|
@ -137,7 +137,7 @@ private Config(BlockConfigEntry block, Path coredir,LaunchServer server) {
|
|||
|
||||
// Set misc config
|
||||
genMappings = block.getEntryValue("proguardPrintMappings", BooleanConfigEntry.class);
|
||||
mirrors = block.getEntry("mirrors",ListConfigEntry.class);
|
||||
mirrors = block.getEntry("mirrors", ListConfigEntry.class);
|
||||
launch4j = new ExeConf(block.getEntry("launch4J", BlockConfigEntry.class));
|
||||
sign = new SignConf(block.getEntry("signing", BlockConfigEntry.class), coredir);
|
||||
binaryName = block.getEntryValue("binaryName", StringConfigEntry.class);
|
||||
|
@ -410,7 +410,7 @@ public LaunchServer(Path dir, boolean portable) throws IOException, InvalidKeySp
|
|||
generateConfigIfNotExists();
|
||||
LogHelper.info("Reading LaunchServer config file");
|
||||
try (BufferedReader reader = IOHelper.newReader(configFile)) {
|
||||
config = new Config(TextConfigReader.read(reader, true), dir,this);
|
||||
config = new Config(TextConfigReader.read(reader, true), dir, this);
|
||||
}
|
||||
config.verify();
|
||||
|
||||
|
@ -473,12 +473,12 @@ public void close() {
|
|||
|
||||
// Close handlers & providers
|
||||
try {
|
||||
for(AuthHandler h : config.authHandler) h.close();
|
||||
for (AuthHandler h : config.authHandler) h.close();
|
||||
} catch (IOException e) {
|
||||
LogHelper.error(e);
|
||||
}
|
||||
try {
|
||||
for(AuthProvider p : config.authProvider) p.close();
|
||||
for (AuthProvider p : config.authProvider) p.close();
|
||||
} catch (IOException e) {
|
||||
LogHelper.error(e);
|
||||
}
|
||||
|
@ -501,7 +501,7 @@ private void generateConfigIfNotExists() throws IOException {
|
|||
LogHelper.info("Creating LaunchServer config");
|
||||
Config newConfig;
|
||||
try (BufferedReader reader = IOHelper.newReader(IOHelper.getResourceURL("ru/gravit/launchserver/defaults/config.cfg"))) {
|
||||
newConfig = new Config(TextConfigReader.read(reader, false), dir,this);
|
||||
newConfig = new Config(TextConfigReader.read(reader, false), dir, this);
|
||||
}
|
||||
|
||||
// Set server address
|
||||
|
|
|
@ -9,12 +9,13 @@ public ClientPermissions() {
|
|||
canAdmin = false;
|
||||
canServer = false;
|
||||
}
|
||||
|
||||
public ClientPermissions(long data) {
|
||||
canAdmin = (data & (1)) != 0;
|
||||
canAdmin = (data & (1)) != 0;
|
||||
canServer = (data & (1 << 1)) != 0;
|
||||
}
|
||||
public static ClientPermissions getSuperuserAccount()
|
||||
{
|
||||
|
||||
public static ClientPermissions getSuperuserAccount() {
|
||||
ClientPermissions perm = new ClientPermissions();
|
||||
perm.canServer = true;
|
||||
perm.canAdmin = true;
|
||||
|
|
|
@ -7,8 +7,9 @@
|
|||
|
||||
public final class AcceptAuthProvider extends AuthProvider {
|
||||
private final boolean isAdminAccess;
|
||||
|
||||
public AcceptAuthProvider(BlockConfigEntry block, LaunchServer server) {
|
||||
super(block,server);
|
||||
super(block, server);
|
||||
isAdminAccess = block.hasEntry("admin") ? block.getEntryValue("admin", BooleanConfigEntry.class) : false;
|
||||
}
|
||||
|
||||
|
|
|
@ -23,11 +23,11 @@ public static AuthProviderResult authError(String message) throws AuthException
|
|||
}
|
||||
|
||||
|
||||
public static AuthProvider newProvider(String name, BlockConfigEntry block,LaunchServer server) {
|
||||
public static AuthProvider newProvider(String name, BlockConfigEntry block, LaunchServer server) {
|
||||
VerifyHelper.verifyIDName(name);
|
||||
ServerAdapter<AuthProvider> authHandlerAdapter = VerifyHelper.getMapValue(AUTH_PROVIDERS, name,
|
||||
String.format("Unknown auth provider: '%s'", name));
|
||||
return authHandlerAdapter.convert(block,server);
|
||||
return authHandlerAdapter.convert(block, server);
|
||||
}
|
||||
|
||||
|
||||
|
@ -51,8 +51,8 @@ public static void registerProviders() {
|
|||
registredProv = true;
|
||||
}
|
||||
}
|
||||
public AuthHandler getAccociateHandler(int this_position)
|
||||
{
|
||||
|
||||
public AuthHandler getAccociateHandler(int this_position) {
|
||||
return server.config.authHandler[this_position];
|
||||
}
|
||||
|
||||
|
@ -67,9 +67,10 @@ protected AuthProvider(BlockConfigEntry block, LaunchServer launchServer) {
|
|||
|
||||
@Override
|
||||
public abstract void close() throws IOException;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ServerAdapter<O extends ConfigObject> {
|
||||
|
||||
O convert(BlockConfigEntry entry,LaunchServer server);
|
||||
O convert(BlockConfigEntry entry, LaunchServer server);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,7 +13,8 @@ public AuthProviderResult(String username, String accessToken) {
|
|||
this.accessToken = accessToken;
|
||||
permissions = ClientPermissions.DEFAULT;
|
||||
}
|
||||
public AuthProviderResult(String username, String accessToken,ClientPermissions permissions) {
|
||||
|
||||
public AuthProviderResult(String username, String accessToken, ClientPermissions permissions) {
|
||||
this.username = username;
|
||||
this.accessToken = accessToken;
|
||||
this.permissions = permissions;
|
||||
|
|
|
@ -12,7 +12,7 @@ public abstract class DigestAuthProvider extends AuthProvider {
|
|||
|
||||
|
||||
protected DigestAuthProvider(BlockConfigEntry block, LaunchServer server) {
|
||||
super(block,server);
|
||||
super(block, server);
|
||||
digest = DigestAlgorithm.byName(block.getEntryValue("digest", StringConfigEntry.class));
|
||||
}
|
||||
|
||||
|
|
|
@ -45,7 +45,7 @@ private Entry(BlockConfigEntry block) {
|
|||
private FileTime cacheLastModified;
|
||||
|
||||
public FileAuthProvider(BlockConfigEntry block, LaunchServer server) {
|
||||
super(block,server);
|
||||
super(block, server);
|
||||
file = IOHelper.toPath(block.getEntryValue("file", StringConfigEntry.class));
|
||||
|
||||
// Try to update cache
|
||||
|
|
|
@ -26,7 +26,7 @@ public final class JsonAuthProvider extends AuthProvider {
|
|||
private final String responseErrorKeyName;
|
||||
|
||||
JsonAuthProvider(BlockConfigEntry block, LaunchServer server) {
|
||||
super(block,server);
|
||||
super(block, server);
|
||||
String configUrl = block.getEntryValue("url", StringConfigEntry.class);
|
||||
userKeyName = VerifyHelper.verify(block.getEntryValue("userKeyName", StringConfigEntry.class),
|
||||
VerifyHelper.NOT_EMPTY, "Username key name can't be empty");
|
||||
|
@ -54,7 +54,7 @@ public AuthProviderResult auth(String login, String password, String ip) throws
|
|||
String value;
|
||||
|
||||
if ((value = response.getString(responseUserKeyName, null)) != null)
|
||||
return new AuthProviderResult(value, SecurityHelper.randomStringToken(),new ClientPermissions(response.getLong(responsePermissionKeyName,0)));
|
||||
return new AuthProviderResult(value, SecurityHelper.randomStringToken(), new ClientPermissions(response.getLong(responsePermissionKeyName, 0)));
|
||||
else if ((value = response.getString(responseErrorKeyName, null)) != null)
|
||||
return authError(value);
|
||||
else
|
||||
|
|
|
@ -55,7 +55,7 @@ public static JsonObject makeJSONRequest(URL url, JsonObject request) throws IOE
|
|||
}
|
||||
|
||||
public MojangAuthProvider(BlockConfigEntry block, LaunchServer server) {
|
||||
super(block,server);
|
||||
super(block, server);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -24,7 +24,7 @@ public final class MySQLAuthProvider extends AuthProvider {
|
|||
private final boolean usePermission;
|
||||
|
||||
public MySQLAuthProvider(BlockConfigEntry block, LaunchServer server) {
|
||||
super(block,server);
|
||||
super(block, server);
|
||||
mySQLHolder = new MySQLSourceConfig("authProviderPool", block);
|
||||
|
||||
// Read query
|
||||
|
|
|
@ -11,7 +11,7 @@ public final class NullAuthProvider extends AuthProvider {
|
|||
private volatile AuthProvider provider;
|
||||
|
||||
public NullAuthProvider(BlockConfigEntry block, LaunchServer server) {
|
||||
super(block,server);
|
||||
super(block, server);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -10,7 +10,7 @@ public final class RejectAuthProvider extends AuthProvider {
|
|||
private final String message;
|
||||
|
||||
public RejectAuthProvider(BlockConfigEntry block, LaunchServer server) {
|
||||
super(block,server);
|
||||
super(block, server);
|
||||
message = VerifyHelper.verify(block.getEntryValue("message", StringConfigEntry.class), VerifyHelper.NOT_EMPTY,
|
||||
"Auth error message can't be empty");
|
||||
}
|
||||
|
|
|
@ -20,7 +20,7 @@ public final class RequestAuthProvider extends AuthProvider {
|
|||
private final boolean usePermission;
|
||||
|
||||
public RequestAuthProvider(BlockConfigEntry block, LaunchServer server) {
|
||||
super(block,server);
|
||||
super(block, server);
|
||||
url = block.getEntryValue("url", StringConfigEntry.class);
|
||||
response = Pattern.compile(block.getEntryValue("response", StringConfigEntry.class));
|
||||
usePermission = block.hasEntry("usePermission") ? block.getEntryValue("usePermission", BooleanConfigEntry.class) : false;
|
||||
|
|
|
@ -48,12 +48,13 @@ public CtClass getCtClass() {
|
|||
public byte[] getBytecode() throws IOException, CannotCompileException {
|
||||
return ctClass.toBytecode();
|
||||
}
|
||||
|
||||
public void compile() throws CannotCompileException {
|
||||
body.append("}");
|
||||
moduleBody.append("}");
|
||||
ctConstructor.setBody(body.toString());
|
||||
initModuleMethod.insertAfter(moduleBody.toString());
|
||||
if(ctClass.isFrozen()) ctClass.defrost();
|
||||
if (ctClass.isFrozen()) ctClass.defrost();
|
||||
}
|
||||
|
||||
public String getZipEntryPath() {
|
||||
|
@ -83,16 +84,19 @@ public void setPort(int port) {
|
|||
body.append(port);
|
||||
body.append(";");
|
||||
}
|
||||
|
||||
public void setClientPort(int port) {
|
||||
body.append("this.clientPort = ");
|
||||
body.append(port);
|
||||
body.append(";");
|
||||
}
|
||||
|
||||
public void setUsingWrapper(boolean b) {
|
||||
body.append("this.isUsingWrapper = ");
|
||||
body.append(b ? "true" : "false");
|
||||
body.append(";");
|
||||
}
|
||||
|
||||
public void setDownloadJava(boolean b) {
|
||||
body.append("this.isDownloadJava = ");
|
||||
body.append(b ? "true" : "false");
|
||||
|
|
|
@ -98,6 +98,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
|
|||
private static ZipEntry newEntry(String fileName) {
|
||||
return newZipEntry(Launcher.RUNTIME_DIR + IOHelper.CROSS_SEPARATOR + fileName);
|
||||
}
|
||||
|
||||
private static ZipEntry newGuardEntry(String fileName) {
|
||||
return newZipEntry(Launcher.GUARD_DIR + IOHelper.CROSS_SEPARATOR + fileName);
|
||||
}
|
||||
|
@ -145,13 +146,11 @@ public void build() throws IOException {
|
|||
} catch (ParseException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
if(server.buildHookManager.isNeedPostProguardHook())
|
||||
{
|
||||
if (server.buildHookManager.isNeedPostProguardHook()) {
|
||||
Path obfPath = Paths.get(server.config.binaryName + "-obf.jar");
|
||||
Path tmpPath = Paths.get(server.config.binaryName + "-tmp.jar");
|
||||
IOHelper.move(obfPath,tmpPath);
|
||||
try (ZipOutputStream output = new ZipOutputStream(IOHelper.newOutput(obfPath)))
|
||||
{
|
||||
IOHelper.move(obfPath, tmpPath);
|
||||
try (ZipOutputStream output = new ZipOutputStream(IOHelper.newOutput(obfPath))) {
|
||||
try (ZipInputStream input = new ZipInputStream(
|
||||
IOHelper.newInput(tmpPath))) {
|
||||
ZipEntry e = input.getNextEntry();
|
||||
|
|
|
@ -43,6 +43,7 @@ public final boolean exists() {
|
|||
public final DigestBytesHolder getBytes() {
|
||||
return binary;
|
||||
}
|
||||
|
||||
public final byte[] getSign() {
|
||||
return sign;
|
||||
}
|
||||
|
@ -51,7 +52,7 @@ public final byte[] getSign() {
|
|||
public final boolean sync() throws IOException {
|
||||
boolean exists = exists();
|
||||
binary = exists ? new DigestBytesHolder(IOHelper.read(syncBinaryFile), SecurityHelper.DigestAlgorithm.SHA512) : null;
|
||||
sign = exists ? SecurityHelper.sign(IOHelper.read(syncBinaryFile),server.privateKey) : null;
|
||||
sign = exists ? SecurityHelper.sign(IOHelper.read(syncBinaryFile), server.privateKey) : null;
|
||||
|
||||
return exists;
|
||||
}
|
||||
|
|
|
@ -29,7 +29,7 @@ public void invoke(String... args) throws Exception {
|
|||
String login = args[0];
|
||||
String password = args[1];
|
||||
int auth_id = 0;
|
||||
if(args.length >= 3) auth_id = Integer.valueOf(args[3]);
|
||||
if (args.length >= 3) auth_id = Integer.valueOf(args[3]);
|
||||
|
||||
// Authenticate
|
||||
AuthProvider provider = server.config.authProvider[auth_id];
|
||||
|
|
|
@ -28,7 +28,7 @@ public void invoke(String... args) throws Exception {
|
|||
if (handler == null)
|
||||
handler = new NettyServerSocketHandler(server);
|
||||
if (args[0].equals("start")) {
|
||||
CommonHelper.newThread("Netty Server",true,handler).start();
|
||||
CommonHelper.newThread("Netty Server", true, handler).start();
|
||||
}
|
||||
if (args[0].equals("stop")) {
|
||||
handler.close();
|
||||
|
|
|
@ -229,7 +229,7 @@ private static void sendListing(ChannelHandlerContext ctx, File dir, String dirP
|
|||
.append("<ul>")
|
||||
.append("<li><a href=\"../\">..</a></li>\r\n");
|
||||
|
||||
for (File f: dir.listFiles()) {
|
||||
for (File f : dir.listFiles()) {
|
||||
if (f.isHidden() || !f.canRead()) {
|
||||
continue;
|
||||
}
|
||||
|
@ -275,8 +275,7 @@ private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus stat
|
|||
/**
|
||||
* When file timestamp is the same as what the browser is sending up, send a "304 Not Modified"
|
||||
*
|
||||
* @param ctx
|
||||
* Context
|
||||
* @param ctx Context
|
||||
*/
|
||||
private static void sendNotModified(ChannelHandlerContext ctx) {
|
||||
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED);
|
||||
|
@ -289,8 +288,7 @@ private static void sendNotModified(ChannelHandlerContext ctx) {
|
|||
/**
|
||||
* Sets the Date header for the HTTP response
|
||||
*
|
||||
* @param response
|
||||
* HTTP response
|
||||
* @param response HTTP response
|
||||
*/
|
||||
private static void setDateHeader(FullHttpResponse response) {
|
||||
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
|
||||
|
@ -303,10 +301,8 @@ private static void setDateHeader(FullHttpResponse response) {
|
|||
/**
|
||||
* Sets the Date and Cache headers for the HTTP Response
|
||||
*
|
||||
* @param response
|
||||
* HTTP response
|
||||
* @param fileToCache
|
||||
* file to extract content type
|
||||
* @param response HTTP response
|
||||
* @param fileToCache file to extract content type
|
||||
*/
|
||||
private static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
|
||||
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
|
||||
|
@ -327,10 +323,8 @@ private static void setDateAndCacheHeaders(HttpResponse response, File fileToCac
|
|||
/**
|
||||
* Sets the content type header for the HTTP Response
|
||||
*
|
||||
* @param response
|
||||
* HTTP response
|
||||
* @param file
|
||||
* file to extract content type
|
||||
* @param response HTTP response
|
||||
* @param file file to extract content type
|
||||
*/
|
||||
private static void setContentTypeHeader(HttpResponse response, File file) {
|
||||
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
|
||||
|
|
|
@ -64,6 +64,7 @@ public byte[] classTransform(byte[] clazz, CharSequence classname) {
|
|||
for (Transformer transformer : CLASS_TRANSFORMER) result = transformer.transform(result, classname);
|
||||
return result;
|
||||
}
|
||||
|
||||
public byte[] proGuardClassTransform(byte[] clazz, CharSequence classname) {
|
||||
byte[] result = clazz;
|
||||
for (Transformer transformer : POST_PROGUARD_HOOKS) result = transformer.transform(result, classname);
|
||||
|
@ -109,11 +110,12 @@ public void registerIgnoredClass(String clazz) {
|
|||
public void registerPostHook(PostBuildHook hook) {
|
||||
POST_HOOKS.add(hook);
|
||||
}
|
||||
|
||||
public void registerProGuardHook(Transformer hook) {
|
||||
POST_PROGUARD_HOOKS.add(hook);
|
||||
}
|
||||
public boolean isNeedPostProguardHook()
|
||||
{
|
||||
|
||||
public boolean isNeedPostProguardHook() {
|
||||
return !POST_PROGUARD_HOOKS.isEmpty();
|
||||
}
|
||||
|
||||
|
|
|
@ -7,58 +7,63 @@
|
|||
import java.util.ArrayList;
|
||||
|
||||
public class MirrorManager {
|
||||
public class Mirror
|
||||
{
|
||||
public class Mirror {
|
||||
URL url;
|
||||
String assetsURLMask;
|
||||
String clientsURLMask;
|
||||
boolean enabled;
|
||||
Mirror(String url)
|
||||
{
|
||||
|
||||
Mirror(String url) {
|
||||
assetsURLMask = url.concat("assets/%s.zip");
|
||||
clientsURLMask = url.concat("clients/%s.zip");
|
||||
}
|
||||
private URL formatArg(String mask,String arg) throws MalformedURLException {
|
||||
|
||||
private URL formatArg(String mask, String arg) throws MalformedURLException {
|
||||
return new URL(String.format(mask, IOHelper.urlEncode(arg)));
|
||||
}
|
||||
|
||||
public URL getAssetsURL(String assets) throws MalformedURLException {
|
||||
return formatArg(assetsURLMask,assets);
|
||||
return formatArg(assetsURLMask, assets);
|
||||
}
|
||||
|
||||
public URL getClientsURL(String client) throws MalformedURLException {
|
||||
return formatArg(clientsURLMask,client);
|
||||
return formatArg(clientsURLMask, client);
|
||||
}
|
||||
}
|
||||
|
||||
protected ArrayList<Mirror> list = new ArrayList<>();
|
||||
private Mirror defaultMirror;
|
||||
|
||||
public void addMirror(String mirror) throws MalformedURLException {
|
||||
Mirror m = new Mirror(mirror);
|
||||
m.enabled = true;
|
||||
if(defaultMirror == null) defaultMirror = m;
|
||||
if (defaultMirror == null) defaultMirror = m;
|
||||
}
|
||||
public void addMirror(String mirror,boolean enabled) throws MalformedURLException {
|
||||
|
||||
public void addMirror(String mirror, boolean enabled) throws MalformedURLException {
|
||||
Mirror m = new Mirror(mirror);
|
||||
m.url = new URL(mirror);
|
||||
m.enabled = enabled;
|
||||
if(defaultMirror == null && enabled) defaultMirror = m;
|
||||
if (defaultMirror == null && enabled) defaultMirror = m;
|
||||
}
|
||||
public Mirror getDefaultMirror()
|
||||
{
|
||||
|
||||
public Mirror getDefaultMirror() {
|
||||
return defaultMirror;
|
||||
}
|
||||
public void setDefaultMirror(Mirror m)
|
||||
{
|
||||
|
||||
public void setDefaultMirror(Mirror m) {
|
||||
defaultMirror = m;
|
||||
}
|
||||
public void disableMirror(int index)
|
||||
{
|
||||
|
||||
public void disableMirror(int index) {
|
||||
list.get(index).enabled = false;
|
||||
}
|
||||
public void enableMirror(int index)
|
||||
{
|
||||
|
||||
public void enableMirror(int index) {
|
||||
list.get(index).enabled = true;
|
||||
}
|
||||
public int size()
|
||||
{
|
||||
|
||||
public int size() {
|
||||
return list.size();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -22,7 +22,7 @@ public boolean addClient(Client client) {
|
|||
|
||||
public void garbageCollection() {
|
||||
long time = System.currentTimeMillis();
|
||||
clientSet.removeIf(c -> (c.timestamp + SESSION_TIMEOUT < time) && ((c.type == Client.Type.USER) || ((c.type == Client.Type.SERVER) && !NON_GARBAGE_SERVER ) ));
|
||||
clientSet.removeIf(c -> (c.timestamp + SESSION_TIMEOUT < time) && ((c.type == Client.Type.USER) || ((c.type == Client.Type.SERVER) && !NON_GARBAGE_SERVER)));
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -50,7 +50,7 @@ public static void registerResponses() {
|
|||
registerResponse(RequestType.PROFILES.getNumber(), ProfilesResponse::new);
|
||||
registerResponse(RequestType.SERVERAUTH.getNumber(), AuthServerResponse::new);
|
||||
registerResponse(RequestType.SETPROFILE.getNumber(), SetProfileResponse::new);
|
||||
registerResponse(RequestType.CHANGESERVER.getNumber(),ChangeServerResponse::new);
|
||||
registerResponse(RequestType.CHANGESERVER.getNumber(), ChangeServerResponse::new);
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -42,13 +42,13 @@ public void reply() throws Exception {
|
|||
String login = input.readString(SerializeLimits.MAX_LOGIN);
|
||||
boolean isClient = input.readBoolean();
|
||||
String client = null;
|
||||
if(isClient)
|
||||
if (isClient)
|
||||
client = input.readString(SerializeLimits.MAX_CLIENT);
|
||||
int auth_id = input.readInt();
|
||||
long hwid_hdd = input.readLong();
|
||||
long hwid_cpu = input.readLong();
|
||||
long hwid_bios = input.readLong();
|
||||
if(auth_id + 1 > server.config.authProvider.length || auth_id < 0) auth_id = 0;
|
||||
if (auth_id + 1 > server.config.authProvider.length || auth_id < 0) auth_id = 0;
|
||||
byte[] encryptedPassword = input.readByteArray(SecurityHelper.CRYPTO_MAX_LENGTH);
|
||||
// Decrypt password
|
||||
String password;
|
||||
|
@ -71,8 +71,7 @@ public void reply() throws Exception {
|
|||
AuthProvider.authError(server.config.authRejectString);
|
||||
return;
|
||||
}
|
||||
if(!clientData.checkSign)
|
||||
{
|
||||
if (!clientData.checkSign) {
|
||||
throw new AuthException("You must using checkLauncher");
|
||||
}
|
||||
result = provider.auth(login, password, ip);
|
||||
|
@ -80,7 +79,7 @@ public void reply() throws Exception {
|
|||
AuthProvider.authError(String.format("Illegal result: '%s'", result.username));
|
||||
return;
|
||||
}
|
||||
if(isClient) {
|
||||
if (isClient) {
|
||||
Collection<SignedObjectHolder<ClientProfile>> profiles = server.getProfiles();
|
||||
for (SignedObjectHolder<ClientProfile> p : profiles) {
|
||||
if (p.object.getTitle().equals(client)) {
|
||||
|
|
|
@ -38,7 +38,7 @@ public void reply() throws Exception {
|
|||
String login = input.readString(SerializeLimits.MAX_LOGIN);
|
||||
String client = input.readString(SerializeLimits.MAX_CLIENT);
|
||||
int auth_id = input.readInt();
|
||||
if(auth_id + 1 > server.config.authProvider.length || auth_id < 0) auth_id = 0;
|
||||
if (auth_id + 1 > server.config.authProvider.length || auth_id < 0) auth_id = 0;
|
||||
byte[] encryptedPassword = input.readByteArray(SecurityHelper.CRYPTO_MAX_LENGTH);
|
||||
// Decrypt password
|
||||
String password;
|
||||
|
@ -73,7 +73,7 @@ public void reply() throws Exception {
|
|||
clientData.profile = p.object;
|
||||
}
|
||||
}
|
||||
if(clientData.profile == null) {
|
||||
if (clientData.profile == null) {
|
||||
throw new AuthException("You profile not found");
|
||||
}
|
||||
clientData.type = Client.Type.SERVER;
|
||||
|
|
|
@ -19,9 +19,8 @@ public void reply() throws Exception {
|
|||
writeNoError(output);
|
||||
output.writeBoolean(needChange);
|
||||
//if true
|
||||
if(needChange)
|
||||
{
|
||||
output.writeString(address,255);
|
||||
if (needChange) {
|
||||
output.writeString(address, 255);
|
||||
output.writeInt(port);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -20,7 +20,7 @@ public SetProfileResponse(LaunchServer server, long session, HInput input, HOutp
|
|||
public void reply() throws Exception {
|
||||
String client = input.readString(SerializeLimits.MAX_CLIENT);
|
||||
Client clientData = server.sessionManager.getClient(session);
|
||||
if(!clientData.isAuth) requestError("You not auth");
|
||||
if (!clientData.isAuth) requestError("You not auth");
|
||||
Collection<SignedObjectHolder<ClientProfile>> profiles = server.getProfiles();
|
||||
for (SignedObjectHolder<ClientProfile> p : profiles) {
|
||||
if (p.object.getTitle().equals(client)) {
|
||||
|
|
|
@ -26,8 +26,7 @@ public void reply() throws IOException {
|
|||
}
|
||||
Client client = server.sessionManager.getOrNewClient(session);
|
||||
byte[] digest = input.readByteArray(0);
|
||||
if(!Arrays.equals(bytes.getDigest(), digest))
|
||||
{
|
||||
if (!Arrays.equals(bytes.getDigest(), digest)) {
|
||||
writeNoError(output);
|
||||
output.writeBoolean(true);
|
||||
output.writeByteArray(bytes.getBytes(), 0);
|
||||
|
|
|
@ -23,8 +23,8 @@ public void reply() throws IOException {
|
|||
// Resolve launcher binary
|
||||
Client client = server.sessionManager.getClient(session);
|
||||
input.readBoolean();
|
||||
if(client.type == Client.Type.USER && !client.checkSign) {
|
||||
LogHelper.warning("User session: %d ip %s try get profiles",session,ip);
|
||||
if (client.type == Client.Type.USER && !client.checkSign) {
|
||||
LogHelper.warning("User session: %d ip %s try get profiles", session, ip);
|
||||
requestError("Assess denied");
|
||||
return;
|
||||
}
|
||||
|
|
|
@ -22,6 +22,6 @@ public void reply() throws Exception {
|
|||
// Write all update dirs names
|
||||
output.writeLength(updateDirs.size(), 0);
|
||||
for (Entry<String, SignedObjectHolder<HashedDir>> entry : updateDirs)
|
||||
output.writeString(entry.getKey(), 255);
|
||||
output.writeString(entry.getKey(), 255);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -38,12 +38,14 @@ public void reply() throws IOException {
|
|||
return;
|
||||
}
|
||||
Client clientData = server.sessionManager.getClient(session);
|
||||
if(!clientData.isAuth || clientData.type != Client.Type.USER || clientData.profile == null) { requestError("Assess denied"); return;}
|
||||
for(SignedObjectHolder<ClientProfile> p : server.getProfiles())
|
||||
{
|
||||
if (!clientData.isAuth || clientData.type != Client.Type.USER || clientData.profile == null) {
|
||||
requestError("Assess denied");
|
||||
return;
|
||||
}
|
||||
for (SignedObjectHolder<ClientProfile> p : server.getProfiles()) {
|
||||
ClientProfile profile = p.object;
|
||||
if(!clientData.profile.getTitle().equals(profile.getTitle())) continue;
|
||||
if(!profile.isWhitelistContains(clientData.username)) {
|
||||
if (!clientData.profile.getTitle().equals(profile.getTitle())) continue;
|
||||
if (!profile.isWhitelistContains(clientData.username)) {
|
||||
requestError("You don't download this folder");
|
||||
return;
|
||||
}
|
||||
|
|
|
@ -23,12 +23,13 @@ public Client(long session) {
|
|||
username = "";
|
||||
checkSign = false;
|
||||
}
|
||||
|
||||
//Данные ваторизации
|
||||
public void up() {
|
||||
timestamp = System.currentTimeMillis();
|
||||
}
|
||||
public enum Type
|
||||
{
|
||||
|
||||
public enum Type {
|
||||
SERVER,
|
||||
USER
|
||||
}
|
||||
|
|
|
@ -140,7 +140,7 @@ public void initChannel(NioSocketChannel ch) {
|
|||
pipeline.addLast(new HttpObjectAggregator(65536));
|
||||
pipeline.addLast(new WebSocketServerCompressionHandler());
|
||||
pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true));
|
||||
pipeline.addLast(new FileServerHandler(LaunchServer.server.updatesDir,true));
|
||||
pipeline.addLast(new FileServerHandler(LaunchServer.server.updatesDir, true));
|
||||
pipeline.addLast(new WebSocketFrameHandler());
|
||||
}
|
||||
});
|
||||
|
|
|
@ -11,14 +11,17 @@
|
|||
import ru.gravit.launchserver.socket.Client;
|
||||
import ru.gravit.utils.helper.IOHelper;
|
||||
import ru.gravit.utils.helper.LogHelper;
|
||||
|
||||
public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
|
||||
public static LaunchServer server;
|
||||
public static GsonBuilder builder = new GsonBuilder();
|
||||
public static WebSocketService service = new WebSocketService(new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), LaunchServer.server,builder);
|
||||
public static WebSocketService service = new WebSocketService(new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), LaunchServer.server, builder);
|
||||
private Client client;
|
||||
|
||||
static {
|
||||
service.registerResponses();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelActive(ChannelHandlerContext ctx) {
|
||||
LogHelper.debug("New client %s", IOHelper.getIP(ctx.channel().remoteAddress()));
|
||||
|
|
|
@ -25,69 +25,68 @@
|
|||
|
||||
public class WebSocketService {
|
||||
public final ChannelGroup channels;
|
||||
|
||||
public WebSocketService(ChannelGroup channels, LaunchServer server, GsonBuilder gson) {
|
||||
this.channels = channels;
|
||||
this.server = server;
|
||||
this.gsonBuiler = gson;
|
||||
this.
|
||||
gsonBuiler.registerTypeAdapter(JsonResponseInterface.class,new JsonResponseAdapter(this));
|
||||
gsonBuiler.registerTypeAdapter(HashedEntry.class,new HashedEntryAdapter());
|
||||
gsonBuiler.registerTypeAdapter(JsonResponseInterface.class, new JsonResponseAdapter(this));
|
||||
gsonBuiler.registerTypeAdapter(HashedEntry.class, new HashedEntryAdapter());
|
||||
this.gson = gsonBuiler.create();
|
||||
}
|
||||
|
||||
private final LaunchServer server;
|
||||
private static final HashMap<String,Class> responses = new HashMap<>();
|
||||
private static final HashMap<String, Class> responses = new HashMap<>();
|
||||
private final Gson gson;
|
||||
private final GsonBuilder gsonBuiler;
|
||||
|
||||
void process(ChannelHandlerContext ctx, TextWebSocketFrame frame, Client client)
|
||||
{
|
||||
void process(ChannelHandlerContext ctx, TextWebSocketFrame frame, Client client) {
|
||||
String request = frame.text();
|
||||
JsonResponseInterface response = gson.fromJson(request, JsonResponseInterface.class);
|
||||
try {
|
||||
response.execute(this,ctx,client);
|
||||
} catch (Exception e)
|
||||
{
|
||||
response.execute(this, ctx, client);
|
||||
} catch (Exception e) {
|
||||
LogHelper.error(e);
|
||||
sendObject(ctx,new ExceptionResult(e));
|
||||
sendObject(ctx, new ExceptionResult(e));
|
||||
}
|
||||
}
|
||||
public Class getResponseClass(String type)
|
||||
{
|
||||
|
||||
public Class getResponseClass(String type) {
|
||||
return responses.get(type);
|
||||
}
|
||||
public void registerResponse(String key,Class responseInterfaceClass)
|
||||
{
|
||||
responses.put(key,responseInterfaceClass);
|
||||
|
||||
public void registerResponse(String key, Class responseInterfaceClass) {
|
||||
responses.put(key, responseInterfaceClass);
|
||||
}
|
||||
public void registerClient(Channel channel)
|
||||
{
|
||||
|
||||
public void registerClient(Channel channel) {
|
||||
channels.add(channel);
|
||||
}
|
||||
public void registerResponses()
|
||||
{
|
||||
|
||||
public void registerResponses() {
|
||||
registerResponse("echo", EchoResponse.class);
|
||||
registerResponse("auth", AuthResponse.class);
|
||||
registerResponse("checkServer", CheckServerResponse.class);
|
||||
registerResponse("joinServer", JoinServerResponse.class);
|
||||
registerResponse("launcherUpdate", LauncherResponse.class);
|
||||
registerResponse("updateList", UpdateListResponse.class);
|
||||
registerResponse("cmdExec",UpdateListResponse.class);
|
||||
registerResponse("cmdExec", UpdateListResponse.class);
|
||||
}
|
||||
public void sendObject(ChannelHandlerContext ctx, Object obj)
|
||||
{
|
||||
|
||||
public void sendObject(ChannelHandlerContext ctx, Object obj) {
|
||||
ctx.channel().writeAndFlush(new TextWebSocketFrame(gson.toJson(obj)));
|
||||
}
|
||||
public void sendObjectAndClose(ChannelHandlerContext ctx, Object obj)
|
||||
{
|
||||
|
||||
public void sendObjectAndClose(ChannelHandlerContext ctx, Object obj) {
|
||||
ctx.channel().writeAndFlush(new TextWebSocketFrame(gson.toJson(obj))).addListener(ChannelFutureListener.CLOSE);
|
||||
}
|
||||
public void sendEvent(EventResult obj)
|
||||
{
|
||||
|
||||
public void sendEvent(EventResult obj) {
|
||||
channels.writeAndFlush(new TextWebSocketFrame(gson.toJson(obj)));
|
||||
}
|
||||
public static class ErrorResult
|
||||
{
|
||||
|
||||
public static class ErrorResult {
|
||||
public ErrorResult(String error) {
|
||||
this.error = error;
|
||||
this.type = "requestError";
|
||||
|
@ -96,8 +95,8 @@ public ErrorResult(String error) {
|
|||
public final String error;
|
||||
public final String type;
|
||||
}
|
||||
public static class SuccessResult
|
||||
{
|
||||
|
||||
public static class SuccessResult {
|
||||
public SuccessResult(String requesttype) {
|
||||
this.requesttype = requesttype;
|
||||
this.type = "success";
|
||||
|
@ -106,15 +105,16 @@ public SuccessResult(String requesttype) {
|
|||
public final String requesttype;
|
||||
public final String type;
|
||||
}
|
||||
public static class EventResult
|
||||
{
|
||||
|
||||
public static class EventResult {
|
||||
public EventResult() {
|
||||
this.type = "event";
|
||||
}
|
||||
|
||||
public final String type;
|
||||
}
|
||||
public static class ExceptionResult
|
||||
{
|
||||
|
||||
public static class ExceptionResult {
|
||||
public ExceptionResult(Exception e) {
|
||||
this.message = e.getMessage();
|
||||
this.clazz = e.getClass().getName();
|
||||
|
|
|
@ -18,12 +18,12 @@ public String getType() {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(WebSocketService service,ChannelHandlerContext ctx, Client client) {
|
||||
LogHelper.info("Echo: %s, isAuth %s",echo,client.isAuth ? "true" : "false");
|
||||
service.sendObject(ctx,new Result(echo));
|
||||
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) {
|
||||
LogHelper.info("Echo: %s, isAuth %s", echo, client.isAuth ? "true" : "false");
|
||||
service.sendObject(ctx, new Result(echo));
|
||||
}
|
||||
public class Result
|
||||
{
|
||||
|
||||
public class Result {
|
||||
String echo;
|
||||
|
||||
public Result(String echo) {
|
||||
|
|
|
@ -6,5 +6,6 @@
|
|||
|
||||
public interface JsonResponseInterface {
|
||||
String getType();
|
||||
void execute(WebSocketService service,ChannelHandlerContext ctx, Client client) throws Exception;
|
||||
|
||||
void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception;
|
||||
}
|
||||
|
|
|
@ -8,6 +8,7 @@
|
|||
|
||||
public class ExecCommandResponse implements JsonResponseInterface {
|
||||
public String cmd;
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "cmdExec";
|
||||
|
@ -15,9 +16,15 @@ public String getType() {
|
|||
|
||||
@Override
|
||||
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception {
|
||||
if(!client.isAuth) {service.sendObject(ctx,new WebSocketService.ErrorResult("Access denied")); return; }
|
||||
if(!client.permissions.canAdmin) {service.sendObject(ctx,new WebSocketService.ErrorResult("Access denied")); return; }
|
||||
LaunchServer.server.commandHandler.eval(cmd,false);
|
||||
service.sendObject(ctx,new WebSocketService.SuccessResult("cmdExec"));
|
||||
if (!client.isAuth) {
|
||||
service.sendObject(ctx, new WebSocketService.ErrorResult("Access denied"));
|
||||
return;
|
||||
}
|
||||
if (!client.permissions.canAdmin) {
|
||||
service.sendObject(ctx, new WebSocketService.ErrorResult("Access denied"));
|
||||
return;
|
||||
}
|
||||
LaunchServer.server.commandHandler.eval(cmd, false);
|
||||
service.sendObject(ctx, new WebSocketService.SuccessResult("cmdExec"));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -32,6 +32,7 @@ public AuthResponse(String login, String password, int authid, HWID hwid) {
|
|||
|
||||
public int authid;
|
||||
public HWID hwid;
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "auth";
|
||||
|
@ -45,8 +46,7 @@ public void execute(WebSocketService service, ChannelHandlerContext ctx, Client
|
|||
AuthProvider.authError(LaunchServer.server.config.authRejectString);
|
||||
return;
|
||||
}
|
||||
if(!clientData.checkSign)
|
||||
{
|
||||
if (!clientData.checkSign) {
|
||||
AuthProvider.authError("Don't skip Launcher Update");
|
||||
return;
|
||||
}
|
||||
|
@ -65,20 +65,19 @@ public void execute(WebSocketService service, ChannelHandlerContext ctx, Client
|
|||
clientData.profile = p.object;
|
||||
}
|
||||
}
|
||||
if(clientData.profile == null) {
|
||||
if (clientData.profile == null) {
|
||||
throw new AuthException("You profile not found");
|
||||
}
|
||||
LaunchServer.server.config.hwidHandler.check(hwid, result.username);
|
||||
clientData.isAuth = true;
|
||||
clientData.permissions = result.permissions;
|
||||
service.sendObject(ctx,new WebSocketService.SuccessResult("auth"));
|
||||
} catch (AuthException | HWIDException e)
|
||||
{
|
||||
service.sendObject(ctx,new WebSocketService.ErrorResult(e.getMessage()));
|
||||
service.sendObject(ctx, new WebSocketService.SuccessResult("auth"));
|
||||
} catch (AuthException | HWIDException e) {
|
||||
service.sendObject(ctx, new WebSocketService.ErrorResult(e.getMessage()));
|
||||
}
|
||||
}
|
||||
public class Result
|
||||
{
|
||||
|
||||
public class Result {
|
||||
public Result() {
|
||||
}
|
||||
|
||||
|
|
|
@ -13,6 +13,7 @@
|
|||
public class CheckServerResponse implements JsonResponseInterface {
|
||||
public String serverID;
|
||||
public String username;
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "checkServer";
|
||||
|
@ -24,17 +25,17 @@ public void execute(WebSocketService service, ChannelHandlerContext ctx, Client
|
|||
try {
|
||||
uuid = LaunchServer.server.config.authHandler[0].checkServer(username, serverID);
|
||||
} catch (AuthException e) {
|
||||
service.sendObject(ctx,new WebSocketService.ErrorResult(e.getMessage()));
|
||||
service.sendObject(ctx, new WebSocketService.ErrorResult(e.getMessage()));
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
LogHelper.error(e);
|
||||
service.sendObject(ctx,new WebSocketService.ErrorResult("Internal authHandler error"));
|
||||
service.sendObject(ctx, new WebSocketService.ErrorResult("Internal authHandler error"));
|
||||
return;
|
||||
}
|
||||
service.sendObject(ctx,new Result());
|
||||
service.sendObject(ctx, new Result());
|
||||
}
|
||||
public class Result
|
||||
{
|
||||
|
||||
public class Result {
|
||||
public String type = "success";
|
||||
public String requesttype = "checkServer";
|
||||
}
|
||||
|
|
|
@ -12,6 +12,7 @@ public class JoinServerResponse implements JsonResponseInterface {
|
|||
public String serverID;
|
||||
public String accessToken;
|
||||
public String username;
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "joinServer";
|
||||
|
@ -21,19 +22,19 @@ public String getType() {
|
|||
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception {
|
||||
boolean success;
|
||||
try {
|
||||
success = LaunchServer.server.config.authHandler[0].joinServer(username,accessToken,serverID);
|
||||
success = LaunchServer.server.config.authHandler[0].joinServer(username, accessToken, serverID);
|
||||
} catch (AuthException e) {
|
||||
service.sendObject(ctx,new WebSocketService.ErrorResult(e.getMessage()));
|
||||
service.sendObject(ctx, new WebSocketService.ErrorResult(e.getMessage()));
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
LogHelper.error(e);
|
||||
service.sendObject(ctx,new WebSocketService.ErrorResult("Internal authHandler error"));
|
||||
service.sendObject(ctx, new WebSocketService.ErrorResult("Internal authHandler error"));
|
||||
return;
|
||||
}
|
||||
service.sendObject(ctx,new Result(success));
|
||||
service.sendObject(ctx, new Result(success));
|
||||
}
|
||||
public class Result
|
||||
{
|
||||
|
||||
public class Result {
|
||||
public String type = "success";
|
||||
public String requesttype = "checkServer";
|
||||
|
||||
|
|
|
@ -17,6 +17,7 @@ public class LauncherResponse implements JsonResponseInterface {
|
|||
//REPLACED TO REAL URL
|
||||
public static final String JAR_URL = "http://localhost:9752/Launcher.jar";
|
||||
public static final String EXE_URL = "http://localhost:9752/Launcher.exe";
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "launcherUpdate";
|
||||
|
@ -25,38 +26,34 @@ public String getType() {
|
|||
@Override
|
||||
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception {
|
||||
byte[] bytes = Base64.getDecoder().decode(hash);
|
||||
if(launcher_type == 1) // JAR
|
||||
if (launcher_type == 1) // JAR
|
||||
{
|
||||
byte[] hash = LaunchServer.server.launcherBinary.getBytes().getDigest();
|
||||
if(hash == null) service.sendObjectAndClose(ctx, new Result(true,JAR_URL));
|
||||
if(Arrays.equals(bytes, hash))
|
||||
{
|
||||
service.sendObject(ctx, new Result(false,JAR_URL));
|
||||
} else
|
||||
{
|
||||
service.sendObjectAndClose(ctx, new Result(true,JAR_URL));
|
||||
if (hash == null) service.sendObjectAndClose(ctx, new Result(true, JAR_URL));
|
||||
if (Arrays.equals(bytes, hash)) {
|
||||
service.sendObject(ctx, new Result(false, JAR_URL));
|
||||
} else {
|
||||
service.sendObjectAndClose(ctx, new Result(true, JAR_URL));
|
||||
}
|
||||
} else if(launcher_type == 2) //EXE
|
||||
} else if (launcher_type == 2) //EXE
|
||||
{
|
||||
byte[] hash = LaunchServer.server.launcherEXEBinary.getBytes().getDigest();
|
||||
if(hash == null) service.sendObjectAndClose(ctx, new Result(true,EXE_URL));
|
||||
if(Arrays.equals(bytes, hash))
|
||||
{
|
||||
service.sendObject(ctx, new Result(false,EXE_URL));
|
||||
} else
|
||||
{
|
||||
service.sendObjectAndClose(ctx, new Result(true,EXE_URL));
|
||||
if (hash == null) service.sendObjectAndClose(ctx, new Result(true, EXE_URL));
|
||||
if (Arrays.equals(bytes, hash)) {
|
||||
service.sendObject(ctx, new Result(false, EXE_URL));
|
||||
} else {
|
||||
service.sendObjectAndClose(ctx, new Result(true, EXE_URL));
|
||||
}
|
||||
} else service.sendObject(ctx, new WebSocketService.ErrorResult("Request launcher type error"));
|
||||
|
||||
}
|
||||
public class Result
|
||||
{
|
||||
|
||||
public class Result {
|
||||
public String type = "success";
|
||||
public String requesttype = "launcherUpdate";
|
||||
public String url;
|
||||
|
||||
public Result(boolean needUpdate,String url) {
|
||||
public Result(boolean needUpdate, String url) {
|
||||
this.needUpdate = needUpdate;
|
||||
this.url = url;
|
||||
}
|
||||
|
|
|
@ -9,6 +9,7 @@
|
|||
|
||||
public class UpdateListResponse implements JsonResponseInterface {
|
||||
public String dir;
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "updateList";
|
||||
|
@ -16,15 +17,15 @@ public String getType() {
|
|||
|
||||
@Override
|
||||
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception {
|
||||
if(!client.isAuth) {
|
||||
service.sendObject(ctx,new WebSocketService.ErrorResult("Access denied"));
|
||||
if (!client.isAuth) {
|
||||
service.sendObject(ctx, new WebSocketService.ErrorResult("Access denied"));
|
||||
return;
|
||||
}
|
||||
HashedDir hdir = LaunchServer.server.updatesDirMap.get(dir).object;
|
||||
service.sendObject(ctx,new Result(hdir));
|
||||
service.sendObject(ctx, new Result(hdir));
|
||||
}
|
||||
class Result
|
||||
{
|
||||
|
||||
class Result {
|
||||
public final String type;
|
||||
public final String requesttype;
|
||||
public final HashedDir dir;
|
||||
|
|
|
@ -15,11 +15,12 @@
|
|||
public class AvanguardStarter {
|
||||
static class SecurityThread implements Runnable {
|
||||
static long macID = GuardBind.avnGetMacId();
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while (!Thread.interrupted()) {
|
||||
try {
|
||||
if(macID != GuardBind.avnGetMacId()) {
|
||||
if (macID != GuardBind.avnGetMacId()) {
|
||||
LogHelper.error("MacID changed");
|
||||
safeHalt(8);
|
||||
}
|
||||
|
@ -43,18 +44,16 @@ public void run() {
|
|||
}
|
||||
}
|
||||
}
|
||||
static void safeHalt(int exitcode)
|
||||
{
|
||||
|
||||
static void safeHalt(int exitcode) {
|
||||
try {
|
||||
SafeExitJVMLegacy.exit(exitcode);
|
||||
} catch (Throwable ignored)
|
||||
{
|
||||
} catch (Throwable ignored) {
|
||||
|
||||
}
|
||||
try {
|
||||
SafeExitJVM.exit(exitcode);
|
||||
} catch (Throwable ignored)
|
||||
{
|
||||
} catch (Throwable ignored) {
|
||||
|
||||
}
|
||||
NativeJVMHalt halt = new NativeJVMHalt(exitcode);
|
||||
|
@ -72,8 +71,7 @@ public static void main(boolean init) {
|
|||
LogHelper.error("Cheating == crash!");
|
||||
try {
|
||||
SafeExitJVM.exit(threatType + 7000);
|
||||
} catch (Throwable e)
|
||||
{
|
||||
} catch (Throwable e) {
|
||||
SafeExitJVMLegacy.exit(threatType + 7000);
|
||||
}
|
||||
return false;
|
||||
|
@ -82,21 +80,21 @@ public static void main(boolean init) {
|
|||
GuardBind.avnStartDefence();
|
||||
CommonHelper.newThread("Security Thread", true, new SecurityThread()).start();
|
||||
}
|
||||
public static void load()
|
||||
{
|
||||
|
||||
public static void load() {
|
||||
GuardBind.startAbs(avanguard.toString());
|
||||
}
|
||||
|
||||
public static void start(Path path1) throws IOException {
|
||||
Path path = path1.resolve("guard");
|
||||
if(!IOHelper.exists(path))
|
||||
if (!IOHelper.exists(path))
|
||||
Files.createDirectories(path);
|
||||
Path avanguard = path.resolve(JVMHelper.JVM_BITS == 64 ? "Avanguard64.dll" : "Avanguard32.dll");
|
||||
Path wrapper = path.resolve(JVMHelper.JVM_BITS == 64 ? NAME + "64.exe" : NAME + "32.exe");
|
||||
String avanguardResource = JVMHelper.JVM_BITS == 64 ? "Avanguard64.dll" : "Avanguard32.dll";
|
||||
String wrapperResource = JVMHelper.JVM_BITS == 64 ? "wrapper64.exe" : "wrapper32.exe";
|
||||
UnpackHelper.unpack(Launcher.getResourceURL(avanguardResource,"guard"),avanguard);
|
||||
UnpackHelper.unpack(Launcher.getResourceURL(wrapperResource,"guard"),wrapper);
|
||||
UnpackHelper.unpack(Launcher.getResourceURL(avanguardResource, "guard"), avanguard);
|
||||
UnpackHelper.unpack(Launcher.getResourceURL(wrapperResource, "guard"), wrapper);
|
||||
AvanguardStarter.wrapper = wrapper;
|
||||
AvanguardStarter.avanguard = avanguard;
|
||||
HashedDir guard = new HashedDir(path, null, true, false);
|
||||
|
|
|
@ -36,16 +36,14 @@ public static void main(String[] arguments) throws IOException, InterruptedExcep
|
|||
LogHelper.debug("Commandline: " + args);
|
||||
processBuilder.command(args);
|
||||
Process process = processBuilder.start();
|
||||
if(!LogHelper.isDebugEnabled()) {
|
||||
if (!LogHelper.isDebugEnabled()) {
|
||||
Thread.sleep(3000);
|
||||
if (!process.isAlive()) {
|
||||
LogHelper.error("Process error code: %d", process.exitValue());
|
||||
} else {
|
||||
LogHelper.debug("Process started success");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
process.waitFor();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -135,8 +135,8 @@ public static void addLauncherClassBindings(Map<String, Object> bindings) {
|
|||
bindings.put("DigestAlgorithmClass", SecurityHelper.DigestAlgorithm.class);
|
||||
bindings.put("VerifyHelperClass", VerifyHelper.class);
|
||||
bindings.put("DirBridgeClass", DirBridge.class);
|
||||
bindings.put("FunctionalBridgeClass",FunctionalBridge.class);
|
||||
bindings.put("LauncherSettingsClass",LauncherSettings.class);
|
||||
bindings.put("FunctionalBridgeClass", FunctionalBridge.class);
|
||||
bindings.put("LauncherSettingsClass", LauncherSettings.class);
|
||||
|
||||
// Load JS API if available
|
||||
bindings.put("RingProgressIndicatorClass", RingProgressIndicator.class);
|
||||
|
@ -217,8 +217,8 @@ public void start(String... args) throws Throwable {
|
|||
Launcher.modulesManager.postInitModules();
|
||||
invoker.invokeFunction("start", (Object) args);
|
||||
}
|
||||
public static LauncherEngine clientInstance()
|
||||
{
|
||||
|
||||
public static LauncherEngine clientInstance() {
|
||||
return new LauncherEngine();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -88,9 +88,8 @@ public Params(byte[] launcherDigest, Path assetDir, Path clientDir, PlayerProfil
|
|||
boolean autoEnter, boolean fullScreen, int ram, int width, int height) {
|
||||
this.launcherDigest = launcherDigest.clone();
|
||||
this.updateOptional = new HashSet<>();
|
||||
for(ClientProfile.MarkedString s : Launcher.profile.getOptional())
|
||||
{
|
||||
if(s.mark) updateOptional.add(s);
|
||||
for (ClientProfile.MarkedString s : Launcher.profile.getOptional()) {
|
||||
if (s.mark) updateOptional.add(s);
|
||||
}
|
||||
// Client paths
|
||||
this.assetDir = assetDir;
|
||||
|
@ -113,14 +112,13 @@ public Params(HInput input) throws Exception {
|
|||
clientDir = IOHelper.toPath(input.readString(0));
|
||||
updateOptional = new HashSet<>();
|
||||
int len = input.readLength(128);
|
||||
for(int i=0;i<len;++i)
|
||||
{
|
||||
updateOptional.add(new ClientProfile.MarkedString(input.readString(512),true));
|
||||
for (int i = 0; i < len; ++i) {
|
||||
updateOptional.add(new ClientProfile.MarkedString(input.readString(512), true));
|
||||
}
|
||||
// Client params
|
||||
pp = new PlayerProfile(input);
|
||||
byte[] encryptedAccessToken = input.readByteArray(SecurityHelper.CRYPTO_MAX_LENGTH);
|
||||
String accessTokenD = new String(SecurityHelper.decrypt(Launcher.getConfig().secretKeyClient.getBytes(),encryptedAccessToken));
|
||||
String accessTokenD = new String(SecurityHelper.decrypt(Launcher.getConfig().secretKeyClient.getBytes(), encryptedAccessToken));
|
||||
accessToken = SecurityHelper.verifyToken(accessTokenD);
|
||||
autoEnter = input.readBoolean();
|
||||
fullScreen = input.readBoolean();
|
||||
|
@ -135,15 +133,14 @@ public void write(HOutput output) throws IOException {
|
|||
// Client paths
|
||||
output.writeString(assetDir.toString(), 0);
|
||||
output.writeString(clientDir.toString(), 0);
|
||||
output.writeLength(updateOptional.size(),128);
|
||||
for(ClientProfile.MarkedString s : updateOptional)
|
||||
{
|
||||
output.writeString(s.string,512);
|
||||
output.writeLength(updateOptional.size(), 128);
|
||||
for (ClientProfile.MarkedString s : updateOptional) {
|
||||
output.writeString(s.string, 512);
|
||||
}
|
||||
// Client params
|
||||
pp.write(output);
|
||||
try {
|
||||
output.writeByteArray(SecurityHelper.encrypt(Launcher.getConfig().secretKeyClient.getBytes(),accessToken.getBytes()), SecurityHelper.CRYPTO_MAX_LENGTH);
|
||||
output.writeByteArray(SecurityHelper.encrypt(Launcher.getConfig().secretKeyClient.getBytes(), accessToken.getBytes()), SecurityHelper.CRYPTO_MAX_LENGTH);
|
||||
} catch (Exception e) {
|
||||
LogHelper.error(e);
|
||||
}
|
||||
|
@ -227,6 +224,7 @@ private static void addClientArgs(Collection<String> args, ClientProfile profile
|
|||
Collections.addAll(args, "--height", Integer.toString(params.height));
|
||||
}
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public static void setJavaBinPath(Path javaBinPath) {
|
||||
JavaBinPath = javaBinPath;
|
||||
|
@ -289,7 +287,9 @@ private static void launch(ClientProfile profile, Params params) throws Throwabl
|
|||
System.setProperty("minecraft.applet.TargetDirectory", params.clientDir.toString()); // For 1.5.2
|
||||
mainMethod.invoke((Object) args.toArray(EMPTY_ARRAY));
|
||||
}
|
||||
|
||||
private static Process process = null;
|
||||
|
||||
@LauncherAPI
|
||||
public static Process launch(
|
||||
SignedObjectHolder<HashedDir> assetHDir, SignedObjectHolder<HashedDir> clientHDir,
|
||||
|
@ -301,26 +301,24 @@ public static Process launch(
|
|||
try {
|
||||
try (ServerSocket socket = new ServerSocket()) {
|
||||
|
||||
socket.setReuseAddress(true);
|
||||
socket.bind(new InetSocketAddress(SOCKET_HOST, SOCKET_PORT));
|
||||
Socket client = socket.accept();
|
||||
if(process == null)
|
||||
{
|
||||
LogHelper.error("Process is null");
|
||||
return;
|
||||
}
|
||||
if(!process.isAlive())
|
||||
{
|
||||
LogHelper.error("Process is not alive");
|
||||
JOptionPane.showMessageDialog(null,"Client Process crashed","Launcher",JOptionPane.ERROR_MESSAGE);
|
||||
return;
|
||||
}
|
||||
try (HOutput output = new HOutput(client.getOutputStream())) {
|
||||
params.write(output);
|
||||
profile.write(output);
|
||||
assetHDir.write(output);
|
||||
clientHDir.write(output);
|
||||
}
|
||||
socket.setReuseAddress(true);
|
||||
socket.bind(new InetSocketAddress(SOCKET_HOST, SOCKET_PORT));
|
||||
Socket client = socket.accept();
|
||||
if (process == null) {
|
||||
LogHelper.error("Process is null");
|
||||
return;
|
||||
}
|
||||
if (!process.isAlive()) {
|
||||
LogHelper.error("Process is not alive");
|
||||
JOptionPane.showMessageDialog(null, "Client Process crashed", "Launcher", JOptionPane.ERROR_MESSAGE);
|
||||
return;
|
||||
}
|
||||
try (HOutput output = new HOutput(client.getOutputStream())) {
|
||||
params.write(output);
|
||||
profile.write(output);
|
||||
assetHDir.write(output);
|
||||
clientHDir.write(output);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -337,15 +335,13 @@ public static Process launch(
|
|||
boolean wrapper = isUsingWrapper();
|
||||
Path javaBin;
|
||||
if (wrapper) javaBin = AvanguardStarter.wrapper;
|
||||
else if(isDownloadJava)
|
||||
{
|
||||
else if (isDownloadJava) {
|
||||
//Linux и Mac не должны скачивать свою JVM
|
||||
if(JVMHelper.OS_TYPE == OS.MUSTDIE)
|
||||
if (JVMHelper.OS_TYPE == OS.MUSTDIE)
|
||||
javaBin = IOHelper.resolveJavaBin(JavaBinPath);
|
||||
else
|
||||
javaBin = IOHelper.resolveJavaBin(Paths.get(System.getProperty("java.home")));
|
||||
}
|
||||
else
|
||||
} else
|
||||
javaBin = IOHelper.resolveJavaBin(Paths.get(System.getProperty("java.home")));
|
||||
args.add(javaBin.toString());
|
||||
args.add(MAGICAL_INTEL_OPTION);
|
||||
|
@ -463,9 +459,8 @@ public static void main(String... args) throws Throwable {
|
|||
// Verify current state of all dirs
|
||||
//verifyHDir(IOHelper.JVM_DIR, jvmHDir.object, null, digest);
|
||||
HashedDir hdir = clientHDir.object;
|
||||
for(ClientProfile.MarkedString s : Launcher.profile.getOptional())
|
||||
{
|
||||
if(params.updateOptional.contains(s)) s.mark = true;
|
||||
for (ClientProfile.MarkedString s : Launcher.profile.getOptional()) {
|
||||
if (params.updateOptional.contains(s)) s.mark = true;
|
||||
else hdir.removeR(s.string);
|
||||
}
|
||||
verifyHDir(params.assetDir, assetHDir.object, assetMatcher, digest);
|
||||
|
@ -477,6 +472,7 @@ public static void main(String... args) throws Throwable {
|
|||
launch(profile.object, params);
|
||||
}
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public void launchLocal(SignedObjectHolder<HashedDir> assetHDir, SignedObjectHolder<HashedDir> clientHDir,
|
||||
SignedObjectHolder<ClientProfile> profile, Params params) throws Throwable {
|
||||
|
@ -502,9 +498,8 @@ public void launchLocal(SignedObjectHolder<HashedDir> assetHDir, SignedObjectHol
|
|||
// Verify current state of all dirs
|
||||
//verifyHDir(IOHelper.JVM_DIR, jvmHDir.object, null, digest);
|
||||
HashedDir hdir = clientHDir.object;
|
||||
for(ClientProfile.MarkedString s : Launcher.profile.getOptional())
|
||||
{
|
||||
if(params.updateOptional.contains(s)) s.mark = true;
|
||||
for (ClientProfile.MarkedString s : Launcher.profile.getOptional()) {
|
||||
if (params.updateOptional.contains(s)) s.mark = true;
|
||||
else hdir.removeR(s.string);
|
||||
}
|
||||
verifyHDir(params.assetDir, assetHDir.object, assetMatcher, digest);
|
||||
|
|
|
@ -14,18 +14,18 @@
|
|||
public class FunctionalBridge {
|
||||
@LauncherAPI
|
||||
public static LauncherSettings settings;
|
||||
|
||||
@LauncherAPI
|
||||
public HashedDirRunnable offlineUpdateRequest(String dirName, Path dir, SignedObjectHolder<HashedDir> hdir, FileNameMatcher matcher, boolean digest) throws Exception
|
||||
{
|
||||
public HashedDirRunnable offlineUpdateRequest(String dirName, Path dir, SignedObjectHolder<HashedDir> hdir, FileNameMatcher matcher, boolean digest) throws Exception {
|
||||
return () -> {
|
||||
if(hdir == null)
|
||||
{
|
||||
if (hdir == null) {
|
||||
Request.requestError(java.lang.String.format("Директории '%s' нет в кэше", dirName));
|
||||
}
|
||||
ClientLauncher.verifyHDir(dir, hdir.object, matcher, digest);
|
||||
return hdir;
|
||||
};
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public LegacyLauncherRequest.Result offlineLauncherRequest() throws IOException, SignatureException {
|
||||
if (settings.lastDigest == null || settings.lastProfiles.isEmpty()) {
|
||||
|
@ -38,8 +38,9 @@ public LegacyLauncherRequest.Result offlineLauncherRequest() throws IOException,
|
|||
// settings.lastDigest, Launcher.getConfig().publicKey);
|
||||
|
||||
// Return last sign and profiles
|
||||
return new LegacyLauncherRequest.Result(null,settings.lastDigest,settings.lastProfiles);
|
||||
return new LegacyLauncherRequest.Result(null, settings.lastDigest, settings.lastProfiles);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface HashedDirRunnable {
|
||||
SignedObjectHolder<HashedDir> run() throws Exception;
|
||||
|
|
|
@ -46,36 +46,36 @@ public class LauncherSettings {
|
|||
@LauncherAPI
|
||||
public List<SignedObjectHolder<ClientProfile>> lastProfiles = new LinkedList<>();
|
||||
@LauncherAPI
|
||||
public Map<String,SignedObjectHolder<HashedDir>> lastHDirs = new HashMap<>(16);
|
||||
public Map<String, SignedObjectHolder<HashedDir>> lastHDirs = new HashMap<>(16);
|
||||
|
||||
@LauncherAPI
|
||||
public void load() throws SignatureException {
|
||||
LogHelper.debug("Loading settings file");
|
||||
try {
|
||||
try(HInput input = new HInput(IOHelper.newInput(file)))
|
||||
{
|
||||
try (HInput input = new HInput(IOHelper.newInput(file))) {
|
||||
read(input);
|
||||
}
|
||||
} catch(IOException e) {
|
||||
} catch (IOException e) {
|
||||
LogHelper.error(e);
|
||||
setDefault();
|
||||
}
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public void save() throws SignatureException {
|
||||
LogHelper.debug("Save settings file");
|
||||
try {
|
||||
try(HOutput output = new HOutput(IOHelper.newOutput(file)))
|
||||
{
|
||||
try (HOutput output = new HOutput(IOHelper.newOutput(file))) {
|
||||
write(output);
|
||||
}
|
||||
} catch(IOException e) {
|
||||
} catch (IOException e) {
|
||||
LogHelper.error(e);
|
||||
setDefault();
|
||||
}
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public void read(HInput input) throws IOException, SignatureException
|
||||
{
|
||||
public void read(HInput input) throws IOException, SignatureException {
|
||||
int magic = input.readInt();
|
||||
if (magic != settingsMagic) {
|
||||
setDefault();
|
||||
|
@ -114,9 +114,10 @@ public void read(HInput input) throws IOException, SignatureException
|
|||
for (int i = 0; i < lastHDirsCount; i++) {
|
||||
String name = IOHelper.verifyFileName(input.readString(255));
|
||||
VerifyHelper.putIfAbsent(lastHDirs, name, new SignedObjectHolder<>(input, publicKey, HashedDir::new),
|
||||
java.lang.String.format("Duplicate offline hashed dir: '%s'", name));
|
||||
java.lang.String.format("Duplicate offline hashed dir: '%s'", name));
|
||||
}
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public void write(HOutput output) throws IOException {
|
||||
output.writeInt(settingsMagic);
|
||||
|
@ -156,14 +157,14 @@ public void write(HOutput output) throws IOException {
|
|||
entry.getValue().write(output);
|
||||
}
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public void setRAM(int ram)
|
||||
{
|
||||
public void setRAM(int ram) {
|
||||
this.ram = java.lang.Math.min(((ram / 256)) * 256, JVMHelper.RAM);
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public void setDefault()
|
||||
{
|
||||
public void setDefault() {
|
||||
// Auth settings
|
||||
login = null;
|
||||
rsaPassword = null;
|
||||
|
@ -182,6 +183,7 @@ public void setDefault()
|
|||
lastProfiles.clear();
|
||||
lastHDirs.clear();
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public byte[] setPassword(String password) throws BadPaddingException, IllegalBlockSizeException {
|
||||
byte[] encrypted = SecurityHelper.newRSAEncryptCipher(Launcher.getConfig().publicKey).doFinal(IOHelper.encode(password));
|
||||
|
|
|
@ -41,8 +41,9 @@ public AuthRequest(LauncherConfig config, String login, byte[] encryptedPassword
|
|||
this.encryptedPassword = encryptedPassword.clone();
|
||||
auth_id = 0;
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public AuthRequest(LauncherConfig config, String login, byte[] encryptedPassword,int auth_id) {
|
||||
public AuthRequest(LauncherConfig config, String login, byte[] encryptedPassword, int auth_id) {
|
||||
super(config);
|
||||
this.login = VerifyHelper.verify(login, VerifyHelper.NOT_EMPTY, "Login can't be empty");
|
||||
this.encryptedPassword = encryptedPassword.clone();
|
||||
|
@ -53,9 +54,10 @@ public AuthRequest(LauncherConfig config, String login, byte[] encryptedPassword
|
|||
public AuthRequest(String login, byte[] encryptedPassword) {
|
||||
this(null, login, encryptedPassword);
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public AuthRequest(String login, byte[] encryptedPassword,int auth_id) {
|
||||
this(null, login, encryptedPassword,auth_id);
|
||||
public AuthRequest(String login, byte[] encryptedPassword, int auth_id) {
|
||||
this(null, login, encryptedPassword, auth_id);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -67,7 +69,7 @@ public Integer getType() {
|
|||
protected Result requestDo(HInput input, HOutput output) throws IOException {
|
||||
output.writeString(login, SerializeLimits.MAX_LOGIN);
|
||||
output.writeBoolean(Launcher.profile != null);
|
||||
if(Launcher.profile != null)
|
||||
if (Launcher.profile != null)
|
||||
output.writeString(Launcher.profile.getTitle(), SerializeLimits.MAX_CLIENT);
|
||||
output.writeInt(auth_id);
|
||||
output.writeLong(Launcher.isUsingAvanguard() ? GuardBind.avnGetHddId() : 0);
|
||||
|
|
|
@ -40,6 +40,7 @@ public AuthServerRequest(LauncherConfig config, String login, byte[] encryptedPa
|
|||
auth_id = 0;
|
||||
title = "";
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public AuthServerRequest(LauncherConfig config, String login, byte[] encryptedPassword, int auth_id) {
|
||||
super(config);
|
||||
|
@ -48,8 +49,9 @@ public AuthServerRequest(LauncherConfig config, String login, byte[] encryptedPa
|
|||
this.auth_id = auth_id;
|
||||
title = "";
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public AuthServerRequest(LauncherConfig config, String login, byte[] encryptedPassword, int auth_id,String title) {
|
||||
public AuthServerRequest(LauncherConfig config, String login, byte[] encryptedPassword, int auth_id, String title) {
|
||||
super(config);
|
||||
this.login = VerifyHelper.verify(login, VerifyHelper.NOT_EMPTY, "Login can't be empty");
|
||||
this.encryptedPassword = encryptedPassword.clone();
|
||||
|
@ -61,9 +63,10 @@ public AuthServerRequest(LauncherConfig config, String login, byte[] encryptedPa
|
|||
public AuthServerRequest(String login, byte[] encryptedPassword) {
|
||||
this(null, login, encryptedPassword);
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public AuthServerRequest(String login, byte[] encryptedPassword, int auth_id) {
|
||||
this(null, login, encryptedPassword,auth_id);
|
||||
this(null, login, encryptedPassword, auth_id);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -13,28 +13,27 @@ public class ChangeServerRequest extends Request<ChangeServerRequest.Result> {
|
|||
public Integer getType() {
|
||||
return RequestType.CHANGESERVER.getNumber();
|
||||
}
|
||||
public boolean change(Result result)
|
||||
{
|
||||
if(!result.needChange) return false;
|
||||
Launcher.getConfig().address = InetSocketAddress.createUnresolved( result.address, result.port);
|
||||
|
||||
public boolean change(Result result) {
|
||||
if (!result.needChange) return false;
|
||||
Launcher.getConfig().address = InetSocketAddress.createUnresolved(result.address, result.port);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Result requestDo(HInput input, HOutput output) throws Exception {
|
||||
readError(input);
|
||||
Result result = new Result();
|
||||
result.needChange = input.readBoolean();
|
||||
if(result.needChange)
|
||||
{
|
||||
if (result.needChange) {
|
||||
result.address = input.readString(255);
|
||||
result.port = input.readInt();
|
||||
}
|
||||
if(result.needChange) change(result);
|
||||
if (result.needChange) change(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
public class Result
|
||||
{
|
||||
public class Result {
|
||||
public boolean needChange;
|
||||
public String address;
|
||||
public int port;
|
||||
|
|
|
@ -39,11 +39,10 @@ public Integer getType() {
|
|||
protected PlayerProfile requestDo(HInput input, HOutput output) throws IOException {
|
||||
output.writeString(username, SerializeLimits.MAX_LOGIN);
|
||||
output.writeASCII(serverID, SerializeLimits.MAX_SERVERID); // 1 char for minus sign
|
||||
if(Launcher.profile == null) {
|
||||
if (Launcher.profile == null) {
|
||||
LogHelper.error("Profile is null. Title is not net.");
|
||||
output.writeString("", SerializeLimits.MAX_CLIENT);
|
||||
}
|
||||
else
|
||||
} else
|
||||
output.writeString(Launcher.profile.getTitle(), SerializeLimits.MAX_CLIENT);
|
||||
output.flush();
|
||||
|
||||
|
|
|
@ -86,9 +86,9 @@ public Integer getType() {
|
|||
@SuppressWarnings("CallToSystemExit")
|
||||
protected Result requestDo(HInput input, HOutput output) throws Exception {
|
||||
Path launcherPath = IOHelper.getCodeSource(LauncherRequest.class);
|
||||
byte[] digest = SecurityHelper.digest(SecurityHelper.DigestAlgorithm.SHA512,launcherPath);
|
||||
byte[] digest = SecurityHelper.digest(SecurityHelper.DigestAlgorithm.SHA512, launcherPath);
|
||||
output.writeBoolean(EXE_BINARY);
|
||||
output.writeByteArray(digest,0);
|
||||
output.writeByteArray(digest, 0);
|
||||
output.flush();
|
||||
readError(input);
|
||||
|
||||
|
@ -97,7 +97,7 @@ protected Result requestDo(HInput input, HOutput output) throws Exception {
|
|||
if (shouldUpdate) {
|
||||
byte[] binary = input.readByteArray(0);
|
||||
Result result = new Result(binary, digest);
|
||||
update(Launcher.getConfig(),result);
|
||||
update(Launcher.getConfig(), result);
|
||||
}
|
||||
|
||||
// Return request result
|
||||
|
|
|
@ -307,7 +307,7 @@ protected SignedObjectHolder<HashedDir> requestDo(HInput input, HOutput output)
|
|||
// Get diff between local and remote dir
|
||||
SignedObjectHolder<HashedDir> remoteHDirHolder = new SignedObjectHolder<>(input, config.publicKey, HashedDir::new);
|
||||
HashedDir hackHackedDir = remoteHDirHolder.object;
|
||||
Launcher.profile.pushOptional(hackHackedDir,!Launcher.profile.isUpdateFastCheck());
|
||||
Launcher.profile.pushOptional(hackHackedDir, !Launcher.profile.isUpdateFastCheck());
|
||||
HashedDir.Diff diff = hackHackedDir.diff(localDir, matcher);
|
||||
totalSize = diff.mismatch.size();
|
||||
boolean compress = input.readBoolean();
|
||||
|
|
|
@ -29,34 +29,34 @@
|
|||
*/
|
||||
@ClientEndpoint
|
||||
public class ClientJSONPoint {
|
||||
public Session session = null;
|
||||
private ClientWebSocketService service;
|
||||
public Session session = null;
|
||||
private ClientWebSocketService service;
|
||||
|
||||
public void setService(ClientWebSocketService service) {
|
||||
this.service = service;
|
||||
}
|
||||
public void setService(ClientWebSocketService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@OnOpen
|
||||
public void onOpen(final Session session_r) {
|
||||
session = session_r;
|
||||
System.out.println("Connected to endpoint: " + session.getBasicRemote());
|
||||
}
|
||||
@OnOpen
|
||||
public void onOpen(final Session session_r) {
|
||||
session = session_r;
|
||||
System.out.println("Connected to endpoint: " + session.getBasicRemote());
|
||||
}
|
||||
|
||||
@OnError
|
||||
public void processError(final Throwable t) {
|
||||
t.printStackTrace();
|
||||
}
|
||||
@OnError
|
||||
public void processError(final Throwable t) {
|
||||
t.printStackTrace();
|
||||
}
|
||||
|
||||
@OnMessage
|
||||
public void processMessage(Reader message) {
|
||||
service.processMessage(message);
|
||||
}
|
||||
|
||||
public void send(String js) throws IOException {
|
||||
session.getBasicRemote().sendText(js);
|
||||
}
|
||||
|
||||
public void sendAsync(String js) throws IOException {
|
||||
session.getAsyncRemote().sendText(js);
|
||||
}
|
||||
@OnMessage
|
||||
public void processMessage(Reader message) {
|
||||
service.processMessage(message);
|
||||
}
|
||||
|
||||
public void send(String js) throws IOException {
|
||||
session.getBasicRemote().sendText(js);
|
||||
}
|
||||
|
||||
public void sendAsync(String js) throws IOException {
|
||||
session.getAsyncRemote().sendText(js);
|
||||
}
|
||||
}
|
|
@ -13,47 +13,49 @@ public class ClientWebSocketService {
|
|||
public final GsonBuilder gsonBuilder;
|
||||
public final Gson gson;
|
||||
public final ClientJSONPoint point;
|
||||
private HashMap<String,Class> requests;
|
||||
private HashMap<String,Class> results;
|
||||
private HashMap<String, Class> requests;
|
||||
private HashMap<String, Class> results;
|
||||
|
||||
public ClientWebSocketService(GsonBuilder gsonBuilder,ClientJSONPoint point) {
|
||||
public ClientWebSocketService(GsonBuilder gsonBuilder, ClientJSONPoint point) {
|
||||
requests = new HashMap<>();
|
||||
results = new HashMap<>();
|
||||
this.gsonBuilder = gsonBuilder;
|
||||
gsonBuilder.registerTypeAdapter(RequestInterface.class, new JsonRequestAdapter(this));
|
||||
gsonBuilder.registerTypeAdapter(HashedEntry.class,new HashedEntryAdapter());
|
||||
gsonBuilder.registerTypeAdapter(HashedEntry.class, new HashedEntryAdapter());
|
||||
this.gson = gsonBuilder.create();
|
||||
this.point = point;
|
||||
point.setService(this);
|
||||
}
|
||||
public void processMessage(Reader reader)
|
||||
{
|
||||
ResultInterface result = gson.fromJson(reader,ResultInterface.class);
|
||||
|
||||
public void processMessage(Reader reader) {
|
||||
ResultInterface result = gson.fromJson(reader, ResultInterface.class);
|
||||
result.process();
|
||||
}
|
||||
public Class getRequestClass(String key)
|
||||
{
|
||||
|
||||
public Class getRequestClass(String key) {
|
||||
return requests.get(key);
|
||||
}
|
||||
public void registerRequest(String key, Class clazz)
|
||||
{
|
||||
requests.put(key,clazz);
|
||||
|
||||
public void registerRequest(String key, Class clazz) {
|
||||
requests.put(key, clazz);
|
||||
}
|
||||
public void registerRequests()
|
||||
{
|
||||
|
||||
public void registerRequests() {
|
||||
|
||||
}
|
||||
public void registerResult(String key, Class clazz)
|
||||
{
|
||||
results.put(key,clazz);
|
||||
|
||||
public void registerResult(String key, Class clazz) {
|
||||
results.put(key, clazz);
|
||||
}
|
||||
public void registerResults()
|
||||
{
|
||||
|
||||
public void registerResults() {
|
||||
|
||||
}
|
||||
|
||||
public void sendObjectAsync(Object obj) throws IOException {
|
||||
point.sendAsync(gson.toJson(obj));
|
||||
}
|
||||
|
||||
public void sendObject(Object obj) throws IOException {
|
||||
point.send(gson.toJson(obj));
|
||||
}
|
||||
|
|
|
@ -10,8 +10,9 @@
|
|||
import java.util.jar.JarFile;
|
||||
|
||||
public class ServerAgent {
|
||||
private static boolean isAgentStarted=false;
|
||||
private static boolean isAgentStarted = false;
|
||||
public static Instrumentation inst;
|
||||
|
||||
public static final class StarterVisitor extends SimpleFileVisitor<Path> {
|
||||
private Instrumentation inst;
|
||||
|
||||
|
@ -25,18 +26,21 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
|
|||
return super.visitFile(file, attrs);
|
||||
}
|
||||
}
|
||||
|
||||
public static void addJVMClassPath(String path) throws IOException {
|
||||
LogHelper.debug("Load %s",path);
|
||||
LogHelper.debug("Load %s", path);
|
||||
inst.appendToSystemClassLoaderSearch(new JarFile(path));
|
||||
}
|
||||
|
||||
public static void addJVMClassPath(JarFile file) throws IOException {
|
||||
LogHelper.debug("Load %s",file.getName());
|
||||
LogHelper.debug("Load %s", file.getName());
|
||||
inst.appendToSystemClassLoaderSearch(file);
|
||||
}
|
||||
public boolean isAgentStarted()
|
||||
{
|
||||
|
||||
public boolean isAgentStarted() {
|
||||
return isAgentStarted;
|
||||
}
|
||||
|
||||
public static long getObjSize(Object obj) {
|
||||
return inst.getObjectSize(obj);
|
||||
}
|
||||
|
|
|
@ -33,10 +33,11 @@ public class ServerWrapper {
|
|||
public static ModulesManager modulesManager;
|
||||
public static Path configFile;
|
||||
public static Config config;
|
||||
|
||||
public static boolean auth(ServerWrapper wrapper) {
|
||||
try {
|
||||
LauncherConfig cfg = Launcher.getConfig();
|
||||
Boolean auth = new AuthServerRequest(cfg,config.login,SecurityHelper.newRSAEncryptCipher(cfg.publicKey).doFinal(IOHelper.encode(config.password)),0,config.title).request();
|
||||
Boolean auth = new AuthServerRequest(cfg, config.login, SecurityHelper.newRSAEncryptCipher(cfg.publicKey).doFinal(IOHelper.encode(config.password)), 0, config.title).request();
|
||||
ProfilesRequest.Result result = new ProfilesRequest(cfg).request();
|
||||
for (SignedObjectHolder<ClientProfile> p : result.profiles) {
|
||||
LogHelper.debug("Get profile: %s", p.object.getTitle());
|
||||
|
@ -48,21 +49,21 @@ public static boolean auth(ServerWrapper wrapper) {
|
|||
}
|
||||
}
|
||||
return true;
|
||||
} catch (Throwable e)
|
||||
{
|
||||
} catch (Throwable e) {
|
||||
LogHelper.error(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
public static boolean loopAuth(ServerWrapper wrapper,int count,int sleeptime) {
|
||||
if(count == 0) {
|
||||
while(true) {
|
||||
if(auth(wrapper)) return true;
|
||||
|
||||
public static boolean loopAuth(ServerWrapper wrapper, int count, int sleeptime) {
|
||||
if (count == 0) {
|
||||
while (true) {
|
||||
if (auth(wrapper)) return true;
|
||||
}
|
||||
}
|
||||
for(int i=0;i<count;++i) {
|
||||
if(auth(wrapper)) return true;
|
||||
for (int i = 0; i < count; ++i) {
|
||||
if (auth(wrapper)) return true;
|
||||
try {
|
||||
Thread.sleep(sleeptime);
|
||||
} catch (InterruptedException e) {
|
||||
|
@ -71,6 +72,7 @@ public static boolean loopAuth(ServerWrapper wrapper,int count,int sleeptime) {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ServerWrapper wrapper = new ServerWrapper();
|
||||
modulesManager = new ModulesManager(wrapper);
|
||||
|
@ -82,21 +84,21 @@ public static void main(String[] args) throws Throwable {
|
|||
try (BufferedReader reader = IOHelper.newReader(configFile)) {
|
||||
config = new Config(TextConfigReader.read(reader, true));
|
||||
}
|
||||
LauncherConfig cfg = new LauncherConfig(config.address, config.port, SecurityHelper.toPublicRSAKey(IOHelper.read(Paths.get("public.key"))),new HashMap<>(),config.projectname);
|
||||
LauncherConfig cfg = new LauncherConfig(config.address, config.port, SecurityHelper.toPublicRSAKey(IOHelper.read(Paths.get("public.key"))), new HashMap<>(), config.projectname);
|
||||
Launcher.setConfig(cfg);
|
||||
if(config.syncAuth) auth(wrapper);
|
||||
else CommonHelper.newThread("Server Auth Thread",true,() -> ServerWrapper.loopAuth(wrapper,config.reconnectCount,config.reconnectSleep));
|
||||
if (config.syncAuth) auth(wrapper);
|
||||
else
|
||||
CommonHelper.newThread("Server Auth Thread", true, () -> ServerWrapper.loopAuth(wrapper, config.reconnectCount, config.reconnectSleep));
|
||||
modulesManager.initModules();
|
||||
String classname = config.mainclass.isEmpty() ? args[0] : config.mainclass;
|
||||
Class<?> mainClass;
|
||||
if(config.customClassLoader) {
|
||||
if (config.customClassLoader) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Class<ClassLoader> classloader_class = (Class<ClassLoader>) Class.forName(config.classloader);
|
||||
Class<ClassLoader> classloader_class = (Class<ClassLoader>) Class.forName(config.classloader);
|
||||
ClassLoader loader = classloader_class.getConstructor(ClassLoader.class).newInstance(ClassLoader.getSystemClassLoader());
|
||||
Thread.currentThread().setContextClassLoader(loader);
|
||||
mainClass = Class.forName(classname,false,loader);
|
||||
}
|
||||
else mainClass = Class.forName(classname);
|
||||
mainClass = Class.forName(classname, false, loader);
|
||||
} else mainClass = Class.forName(classname);
|
||||
MethodHandle mainMethod = MethodHandles.publicLookup().findStatic(mainClass, "main", MethodType.methodType(void.class, String[].class));
|
||||
String[] real_args = new String[args.length - 1];
|
||||
System.arraycopy(args, 1, real_args, 0, args.length - 1);
|
||||
|
@ -104,6 +106,7 @@ public static void main(String[] args) throws Throwable {
|
|||
LogHelper.debug("Invoke main method");
|
||||
mainMethod.invoke(real_args);
|
||||
}
|
||||
|
||||
private static void generateConfigIfNotExists() throws IOException {
|
||||
if (IOHelper.isFile(configFile))
|
||||
return;
|
||||
|
@ -123,6 +126,7 @@ private static void generateConfigIfNotExists() throws IOException {
|
|||
TextConfigWriter.write(newConfig.block, writer, true);
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Config extends ConfigObject {
|
||||
public String title;
|
||||
public String projectname;
|
||||
|
@ -136,22 +140,24 @@ public static final class Config extends ConfigObject {
|
|||
public String mainclass;
|
||||
public String login;
|
||||
public String password;
|
||||
|
||||
protected Config(BlockConfigEntry block) {
|
||||
super(block);
|
||||
title = block.getEntryValue("title",StringConfigEntry.class);
|
||||
address = block.getEntryValue("address",StringConfigEntry.class);
|
||||
projectname = block.getEntryValue("projectName",StringConfigEntry.class);
|
||||
login = block.getEntryValue("login",StringConfigEntry.class);
|
||||
password = block.getEntryValue("password",StringConfigEntry.class);
|
||||
title = block.getEntryValue("title", StringConfigEntry.class);
|
||||
address = block.getEntryValue("address", StringConfigEntry.class);
|
||||
projectname = block.getEntryValue("projectName", StringConfigEntry.class);
|
||||
login = block.getEntryValue("login", StringConfigEntry.class);
|
||||
password = block.getEntryValue("password", StringConfigEntry.class);
|
||||
port = block.getEntryValue("port", IntegerConfigEntry.class);
|
||||
customClassLoader = block.getEntryValue("customClassLoader", BooleanConfigEntry.class);
|
||||
if(customClassLoader)
|
||||
classloader = block.getEntryValue("classloader",StringConfigEntry.class);
|
||||
mainclass = block.getEntryValue("MainClass",StringConfigEntry.class);
|
||||
reconnectCount = block.hasEntry("reconnectCount") ? block.getEntryValue("reconnectCount",IntegerConfigEntry.class) : 1;
|
||||
reconnectSleep = block.hasEntry("reconnectSleep") ? block.getEntryValue("reconnectSleep",IntegerConfigEntry.class) : 30000;
|
||||
syncAuth = block.hasEntry("syncAuth") ? block.getEntryValue("syncAuth",BooleanConfigEntry.class) : true;
|
||||
if (customClassLoader)
|
||||
classloader = block.getEntryValue("classloader", StringConfigEntry.class);
|
||||
mainclass = block.getEntryValue("MainClass", StringConfigEntry.class);
|
||||
reconnectCount = block.hasEntry("reconnectCount") ? block.getEntryValue("reconnectCount", IntegerConfigEntry.class) : 1;
|
||||
reconnectSleep = block.hasEntry("reconnectSleep") ? block.getEntryValue("reconnectSleep", IntegerConfigEntry.class) : 30000;
|
||||
syncAuth = block.hasEntry("syncAuth") ? block.getEntryValue("syncAuth", BooleanConfigEntry.class) : true;
|
||||
}
|
||||
}
|
||||
|
||||
public ClientProfile profile;
|
||||
}
|
||||
|
|
|
@ -5,12 +5,10 @@
|
|||
// FMLSecurityManager запрещает делать System.exit из классов
|
||||
// Не входящих в пакеты самого Forge
|
||||
public class SafeExitJVMLegacy {
|
||||
public static void exit(int code)
|
||||
{
|
||||
public static void exit(int code) {
|
||||
try {
|
||||
JVMHelper.RUNTIME.halt(code);
|
||||
} catch (Throwable e)
|
||||
{
|
||||
} catch (Throwable e) {
|
||||
System.exit(code);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,12 +5,10 @@
|
|||
// FMLSecurityManager запрещает делать System.exit из классов
|
||||
// Не входящих в пакеты самого Forge
|
||||
public class SafeExitJVM {
|
||||
public static void exit(int code)
|
||||
{
|
||||
public static void exit(int code) {
|
||||
try {
|
||||
JVMHelper.RUNTIME.halt(code);
|
||||
} catch (Throwable e)
|
||||
{
|
||||
} catch (Throwable e) {
|
||||
System.exit(code);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -83,9 +83,9 @@ public static LauncherConfig getConfig() {
|
|||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public static void setConfig(LauncherConfig cfg)
|
||||
{
|
||||
public static void setConfig(LauncherConfig cfg) {
|
||||
CONFIG.set(cfg);
|
||||
}
|
||||
|
||||
|
@ -105,7 +105,7 @@ public static URL getResourceURL(String name) throws IOException {
|
|||
return url;
|
||||
}
|
||||
|
||||
public static URL getResourceURL(String name,String prefix) throws IOException {
|
||||
public static URL getResourceURL(String name, String prefix) throws IOException {
|
||||
LauncherConfig config = getConfig();
|
||||
byte[] validDigest = config.runtime.get(name);
|
||||
if (validDigest == null)
|
||||
|
|
|
@ -50,8 +50,8 @@ public static void premain(String agentArgument, Instrumentation instrumentation
|
|||
}
|
||||
}
|
||||
}
|
||||
public static boolean isStarted()
|
||||
{
|
||||
|
||||
public static boolean isStarted() {
|
||||
return isAgentStarted;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,8 +7,9 @@
|
|||
//Набор стандартных событий
|
||||
public class ControlEvent implements EventInterface {
|
||||
private static final UUID uuid = UUID.fromString("f1051a64-0cd0-4ed8-8430-d856a196e91f");
|
||||
|
||||
public enum ControlCommand {
|
||||
STOP,START,PAUSE,CONTINUE,CRASH
|
||||
STOP, START, PAUSE, CONTINUE, CRASH
|
||||
}
|
||||
|
||||
public ControlEvent(ControlCommand signal) {
|
||||
|
@ -16,6 +17,7 @@ public ControlEvent(ControlCommand signal) {
|
|||
}
|
||||
|
||||
public ControlCommand signal;
|
||||
|
||||
@Override
|
||||
public UUID getUUID() {
|
||||
return uuid;
|
||||
|
|
|
@ -8,6 +8,7 @@
|
|||
//Все обработчики обязаны его игнорировать
|
||||
public final class PingEvent implements EventInterface {
|
||||
private static final UUID uuid = UUID.fromString("7c8be7e7-82ce-4c99-84cd-ee8fcce1b509");
|
||||
|
||||
@Override
|
||||
public UUID getUUID() {
|
||||
|
||||
|
|
|
@ -3,13 +3,16 @@
|
|||
import ru.gravit.utils.event.EventInterface;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
//Используется, что бы послать короткое сообщение, которое вмещается в int
|
||||
public class SignalEvent implements EventInterface {
|
||||
private static final UUID uuid = UUID.fromString("edc3afa1-2726-4da3-95c6-7e6994b981e1");
|
||||
public int signal;
|
||||
|
||||
public SignalEvent(int signal) {
|
||||
this.signal = signal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUUID() {
|
||||
return uuid;
|
||||
|
|
|
@ -71,14 +71,12 @@ private static void handleError(Throwable e) {
|
|||
LogHelper.error(e);
|
||||
try {
|
||||
SafeExitJVMLegacy.exit(-123);
|
||||
} catch (Throwable ignored)
|
||||
{
|
||||
} catch (Throwable ignored) {
|
||||
|
||||
}
|
||||
try {
|
||||
SafeExitJVM.exit(-123);
|
||||
} catch (Throwable ignored)
|
||||
{
|
||||
} catch (Throwable ignored) {
|
||||
|
||||
}
|
||||
NativeJVMHalt halt = new NativeJVMHalt(-123);
|
||||
|
|
|
@ -143,45 +143,43 @@ public Diff diff(HashedDir other, FileNameMatcher matcher) {
|
|||
HashedDir extra = other.sideDiff(this, matcher, new LinkedList<>(), false);
|
||||
return new Diff(mismatch, extra);
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public Diff compare(HashedDir other, FileNameMatcher matcher) {
|
||||
HashedDir mismatch = sideDiff(other, matcher, new LinkedList<>(), true);
|
||||
HashedDir extra = other.sideDiff(this, matcher, new LinkedList<>(), false);
|
||||
return new Diff(mismatch, extra);
|
||||
}
|
||||
public void remove(String name)
|
||||
{
|
||||
|
||||
public void remove(String name) {
|
||||
map.remove(name);
|
||||
}
|
||||
public void removeR(String name)
|
||||
{
|
||||
|
||||
public void removeR(String name) {
|
||||
LinkedList<String> dirs = new LinkedList<>();
|
||||
StringTokenizer t = new StringTokenizer(name,"/");
|
||||
while(t.hasMoreTokens())
|
||||
{
|
||||
StringTokenizer t = new StringTokenizer(name, "/");
|
||||
while (t.hasMoreTokens()) {
|
||||
dirs.add(t.nextToken());
|
||||
}
|
||||
Map<String,HashedEntry> current = map;
|
||||
for(String s : dirs)
|
||||
{
|
||||
Map<String, HashedEntry> current = map;
|
||||
for (String s : dirs) {
|
||||
HashedEntry e = current.get(s);
|
||||
if(e == null)
|
||||
{
|
||||
LogHelper.debug("Null %s",s);
|
||||
for(String x : current.keySet()) LogHelper.debug("Contains %s",x);
|
||||
if (e == null) {
|
||||
LogHelper.debug("Null %s", s);
|
||||
for (String x : current.keySet()) LogHelper.debug("Contains %s", x);
|
||||
break;
|
||||
}
|
||||
if(e.getType() == Type.DIR)
|
||||
{
|
||||
if (e.getType() == Type.DIR) {
|
||||
current = ((HashedDir) e).map;
|
||||
LogHelper.debug("Found dir %s",s);
|
||||
LogHelper.debug("Found dir %s", s);
|
||||
} else {
|
||||
current.remove(s);
|
||||
LogHelper.debug("Found filename %s",s);
|
||||
LogHelper.debug("Found filename %s", s);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public HashedEntry getEntry(String name) {
|
||||
return map.get(name);
|
||||
|
|
|
@ -16,8 +16,8 @@ public HashedEntryAdapter() {
|
|||
public HashedEntry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
|
||||
String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString();
|
||||
Class cls = null;
|
||||
if(typename.equals("dir")) cls = HashedDir.class;
|
||||
if(typename.equals("file")) cls = HashedFile.class;
|
||||
if (typename.equals("dir")) cls = HashedDir.class;
|
||||
if (typename.equals("file")) cls = HashedFile.class;
|
||||
|
||||
|
||||
return (HashedEntry) context.deserialize(json, cls);
|
||||
|
@ -29,9 +29,9 @@ public JsonElement serialize(HashedEntry src, Type typeOfSrc, JsonSerializationC
|
|||
JsonObject jo = context.serialize(src).getAsJsonObject();
|
||||
|
||||
HashedEntry.Type type = src.getType();
|
||||
if(type == HashedEntry.Type.DIR)
|
||||
jo.add(PROP_NAME, new JsonPrimitive("dir"));
|
||||
if(type == HashedEntry.Type.FILE)
|
||||
if (type == HashedEntry.Type.DIR)
|
||||
jo.add(PROP_NAME, new JsonPrimitive("dir"));
|
||||
if (type == HashedEntry.Type.FILE)
|
||||
jo.add(PROP_NAME, new JsonPrimitive("file"));
|
||||
|
||||
return jo;
|
||||
|
|
|
@ -75,6 +75,7 @@ public String toString() {
|
|||
private final StringConfigEntry serverAddress;
|
||||
|
||||
private final IntegerConfigEntry serverPort;
|
||||
|
||||
public static class MarkedString {
|
||||
@LauncherAPI
|
||||
public String string;
|
||||
|
@ -85,6 +86,7 @@ public MarkedString(String string, boolean mark) {
|
|||
this.string = string;
|
||||
this.mark = mark;
|
||||
}
|
||||
|
||||
public MarkedString(String string) {
|
||||
this.string = string;
|
||||
this.mark = false;
|
||||
|
@ -103,6 +105,7 @@ public int hashCode() {
|
|||
return Objects.hash(string);
|
||||
}
|
||||
}
|
||||
|
||||
// Updater and client watch service
|
||||
private final List<String> update = new ArrayList<>();
|
||||
private final List<String> updateExclusions = new ArrayList<>();
|
||||
|
@ -213,28 +216,34 @@ public String getServerAddress() {
|
|||
}
|
||||
|
||||
@LauncherAPI
|
||||
public Set<MarkedString> getOptional()
|
||||
{
|
||||
public Set<MarkedString> getOptional() {
|
||||
return updateOptional;
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public void markOptional(String opt)
|
||||
{
|
||||
if(!updateOptional.contains(new MarkedString(opt))) throw new SecurityException(String.format("Optional mod %s not found in optionalList",opt));
|
||||
updateOptional.forEach(e -> {if(e.string.equals(opt)) e.mark = true;});
|
||||
public void markOptional(String opt) {
|
||||
if (!updateOptional.contains(new MarkedString(opt)))
|
||||
throw new SecurityException(String.format("Optional mod %s not found in optionalList", opt));
|
||||
updateOptional.forEach(e -> {
|
||||
if (e.string.equals(opt)) e.mark = true;
|
||||
});
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public void unmarkOptional(String opt)
|
||||
{
|
||||
if(!updateOptional.contains(new MarkedString(opt))) throw new SecurityException(String.format("Optional mod %s not found in optionalList",opt));
|
||||
updateOptional.forEach(e -> {if(e.string.equals(opt)) e.mark = false;});
|
||||
public void unmarkOptional(String opt) {
|
||||
if (!updateOptional.contains(new MarkedString(opt)))
|
||||
throw new SecurityException(String.format("Optional mod %s not found in optionalList", opt));
|
||||
updateOptional.forEach(e -> {
|
||||
if (e.string.equals(opt)) e.mark = false;
|
||||
});
|
||||
}
|
||||
public void pushOptional(HashedDir dir,boolean digest) throws IOException {
|
||||
for(MarkedString opt : updateOptional)
|
||||
{
|
||||
if(!opt.mark) dir.removeR(opt.string);
|
||||
|
||||
public void pushOptional(HashedDir dir, boolean digest) throws IOException {
|
||||
for (MarkedString opt : updateOptional) {
|
||||
if (!opt.mark) dir.removeR(opt.string);
|
||||
}
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public int getServerPort() {
|
||||
return serverPort.getValue();
|
||||
|
|
|
@ -11,7 +11,7 @@ public enum RequestType implements EnumSerializer.Itf {
|
|||
LEGACYLAUNCHER(1), UPDATE(2), UPDATE_LIST(3), // Update requests
|
||||
AUTH(4), JOIN_SERVER(5), CHECK_SERVER(6), // Auth requests
|
||||
PROFILE_BY_USERNAME(7), PROFILE_BY_UUID(8), BATCH_PROFILE_BY_USERNAME(9), // Profile requests
|
||||
PROFILES(10),SERVERAUTH(11), SETPROFILE(12),LAUNCHER(13),CHANGESERVER(14),
|
||||
PROFILES(10), SERVERAUTH(11), SETPROFILE(12), LAUNCHER(13), CHANGESERVER(14),
|
||||
CUSTOM(255); // Custom requests
|
||||
private static final EnumSerializer<RequestType> SERIALIZER = new EnumSerializer<>(RequestType.class);
|
||||
|
||||
|
|
|
@ -16,7 +16,8 @@ public class DigestBytesHolder extends StreamObject {
|
|||
|
||||
@LauncherAPI
|
||||
public DigestBytesHolder(byte[] bytes, byte[] digest, SecurityHelper.DigestAlgorithm algorithm) throws SignatureException {
|
||||
if(Arrays.equals(SecurityHelper.digest(algorithm,bytes),digest)) throw new SignatureException("Invalid digest");
|
||||
if (Arrays.equals(SecurityHelper.digest(algorithm, bytes), digest))
|
||||
throw new SignatureException("Invalid digest");
|
||||
this.bytes = bytes.clone();
|
||||
this.digest = digest.clone();
|
||||
}
|
||||
|
@ -24,12 +25,12 @@ public DigestBytesHolder(byte[] bytes, byte[] digest, SecurityHelper.DigestAlgor
|
|||
@LauncherAPI
|
||||
public DigestBytesHolder(byte[] bytes, SecurityHelper.DigestAlgorithm algorithm) {
|
||||
this.bytes = bytes.clone();
|
||||
this.digest = SecurityHelper.digest(algorithm,bytes);
|
||||
this.digest = SecurityHelper.digest(algorithm, bytes);
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
public DigestBytesHolder(HInput input, SecurityHelper.DigestAlgorithm algorithm) throws IOException, SignatureException {
|
||||
this(input.readByteArray(0), input.readByteArray(-SecurityHelper.RSA_KEY_LENGTH),algorithm);
|
||||
this(input.readByteArray(0), input.readByteArray(-SecurityHelper.RSA_KEY_LENGTH), algorithm);
|
||||
}
|
||||
|
||||
@LauncherAPI
|
||||
|
|
|
@ -5,10 +5,11 @@
|
|||
public class NativeJVMHalt {
|
||||
public NativeJVMHalt(int haltCode) {
|
||||
this.haltCode = haltCode;
|
||||
LogHelper.error("JVM exit code %d",haltCode);
|
||||
LogHelper.error("JVM exit code %d", haltCode);
|
||||
halt();
|
||||
}
|
||||
|
||||
public int haltCode;
|
||||
|
||||
public native void halt();
|
||||
}
|
||||
|
|
|
@ -9,6 +9,7 @@ public class PublicURLClassLoader extends URLClassLoader {
|
|||
@LauncherAPI
|
||||
public static ClassLoader systemclassloader = ClassLoader.getSystemClassLoader();
|
||||
public String nativePath;
|
||||
|
||||
@LauncherAPI
|
||||
public static ClassLoader getSystemClassLoader() {
|
||||
return systemclassloader;
|
||||
|
@ -62,9 +63,9 @@ public PublicURLClassLoader(URL[] urls) {
|
|||
public PublicURLClassLoader(URL[] urls, ClassLoader parent) {
|
||||
super(urls, parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String findLibrary(String name)
|
||||
{
|
||||
public String findLibrary(String name) {
|
||||
return nativePath.concat(name);
|
||||
}
|
||||
|
||||
|
|
|
@ -20,186 +20,186 @@
|
|||
import ru.gravit.utils.helper.LogHelper;
|
||||
|
||||
public class Downloader implements Runnable {
|
||||
@FunctionalInterface
|
||||
public interface Handler {
|
||||
void check(Certificate[] certs) throws IOException;
|
||||
}
|
||||
@FunctionalInterface
|
||||
public interface Handler {
|
||||
void check(Certificate[] certs) throws IOException;
|
||||
}
|
||||
|
||||
public static final Map<String, String> requestClient = Collections.singletonMap("User-Agent",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
|
||||
public static final int INTERVAL = 300;
|
||||
public static final Map<String, String> requestClient = Collections.singletonMap("User-Agent",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
|
||||
public static final int INTERVAL = 300;
|
||||
|
||||
private final File file;
|
||||
private final URL url;
|
||||
private final String method;
|
||||
public final Map<String, String> requestProps;
|
||||
public AtomicInteger writed = new AtomicInteger(0);
|
||||
public final AtomicBoolean interrupt = new AtomicBoolean(false);
|
||||
public final AtomicBoolean interrupted = new AtomicBoolean(false);
|
||||
public AtomicReference<Throwable> ex = new AtomicReference<>(null);
|
||||
private final int skip;
|
||||
private final Handler handler;
|
||||
private final File file;
|
||||
private final URL url;
|
||||
private final String method;
|
||||
public final Map<String, String> requestProps;
|
||||
public AtomicInteger writed = new AtomicInteger(0);
|
||||
public final AtomicBoolean interrupt = new AtomicBoolean(false);
|
||||
public final AtomicBoolean interrupted = new AtomicBoolean(false);
|
||||
public AtomicReference<Throwable> ex = new AtomicReference<>(null);
|
||||
private final int skip;
|
||||
private final Handler handler;
|
||||
|
||||
public Downloader(URL url, File file) {
|
||||
this.requestProps = new HashMap<>(requestClient);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = 0;
|
||||
this.handler = null;
|
||||
this.method = null;
|
||||
}
|
||||
public Downloader(URL url, File file) {
|
||||
this.requestProps = new HashMap<>(requestClient);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = 0;
|
||||
this.handler = null;
|
||||
this.method = null;
|
||||
}
|
||||
|
||||
public Downloader(URL url, File file, int skip) {
|
||||
this.requestProps = new HashMap<>(requestClient);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = skip;
|
||||
this.handler = null;
|
||||
this.method = null;
|
||||
}
|
||||
public Downloader(URL url, File file, int skip) {
|
||||
this.requestProps = new HashMap<>(requestClient);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = skip;
|
||||
this.handler = null;
|
||||
this.method = null;
|
||||
}
|
||||
|
||||
public Downloader(URL url, File file, Handler handler) {
|
||||
this.requestProps = new HashMap<>(requestClient);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = 0;
|
||||
this.handler = handler;
|
||||
this.method = null;
|
||||
}
|
||||
public Downloader(URL url, File file, Handler handler) {
|
||||
this.requestProps = new HashMap<>(requestClient);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = 0;
|
||||
this.handler = handler;
|
||||
this.method = null;
|
||||
}
|
||||
|
||||
public Downloader(URL url, File file, int skip, Handler handler) {
|
||||
this.requestProps = new HashMap<>(requestClient);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = skip;
|
||||
this.handler = handler;
|
||||
this.method = null;
|
||||
}
|
||||
|
||||
public Downloader(URL url, File file, int skip, Handler handler, Map<String, String> requestProps) {
|
||||
this.requestProps = new HashMap<>(requestProps);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = skip;
|
||||
this.handler = handler;
|
||||
this.method = null;
|
||||
}
|
||||
|
||||
public Downloader(URL url, File file, int skip, Handler handler, Map<String, String> requestProps, String method) {
|
||||
this.requestProps = new HashMap<>(requestProps);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = skip;
|
||||
this.handler = handler;
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
public Downloader(URL url, File file, int skip, Handler handler, String method) {
|
||||
this.requestProps = new HashMap<>(requestClient);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = skip;
|
||||
this.handler = handler;
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
public Map<String, String> getProps() {
|
||||
return requestProps;
|
||||
}
|
||||
public Downloader(URL url, File file, int skip, Handler handler) {
|
||||
this.requestProps = new HashMap<>(requestClient);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = skip;
|
||||
this.handler = handler;
|
||||
this.method = null;
|
||||
}
|
||||
|
||||
public void addProp(String key, String value) {
|
||||
requestProps.put(key, value);
|
||||
}
|
||||
|
||||
public File getFile() {
|
||||
return file;
|
||||
}
|
||||
public Downloader(URL url, File file, int skip, Handler handler, Map<String, String> requestProps) {
|
||||
this.requestProps = new HashMap<>(requestProps);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = skip;
|
||||
this.handler = handler;
|
||||
this.method = null;
|
||||
}
|
||||
|
||||
public String getMethod() {
|
||||
return method;
|
||||
}
|
||||
|
||||
public Handler getHandler() {
|
||||
return handler;
|
||||
}
|
||||
|
||||
public void downloadFile() throws IOException {
|
||||
if (!(url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equalsIgnoreCase("https")))
|
||||
throw new IOException("Invalid protocol.");
|
||||
interrupted.set(false);
|
||||
if (url.getProtocol().equalsIgnoreCase("http")) {
|
||||
HttpURLConnection connect = (HttpURLConnection) (url).openConnection();
|
||||
if (method != null) connect.setRequestMethod(method);
|
||||
for (Map.Entry<String, String> ent : requestProps.entrySet()) {
|
||||
connect.setRequestProperty(ent.getKey(), ent.getValue());
|
||||
}
|
||||
connect.setInstanceFollowRedirects(true);
|
||||
if (!(connect.getResponseCode() >= 200 && connect.getResponseCode() < 300))
|
||||
throw new IOException(String.format("Invalid response of http server %d.", connect.getResponseCode()));
|
||||
try (BufferedInputStream in = new BufferedInputStream(connect.getInputStream(), IOHelper.BUFFER_SIZE);
|
||||
FileOutputStream fout = new FileOutputStream(file, skip != 0)) {
|
||||
byte data[] = new byte[IOHelper.BUFFER_SIZE];
|
||||
int count = -1;
|
||||
long timestamp = System.currentTimeMillis();
|
||||
int writed_local = 0;
|
||||
in.skip(skip);
|
||||
while ((count = in.read(data)) != -1) {
|
||||
fout.write(data, 0, count);
|
||||
writed_local += count;
|
||||
if (System.currentTimeMillis() - timestamp > INTERVAL) {
|
||||
writed.set(writed_local);
|
||||
LogHelper.debug("Downloaded %d", writed_local);
|
||||
if (interrupt.get()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
LogHelper.debug("Downloaded %d", writed_local);
|
||||
writed.set(writed_local);
|
||||
}
|
||||
} else {
|
||||
HttpsURLConnection connect = (HttpsURLConnection) (url).openConnection();
|
||||
if (method != null) connect.setRequestMethod(method);
|
||||
for (Map.Entry<String, String> ent : requestProps.entrySet()) {
|
||||
connect.setRequestProperty(ent.getKey(), ent.getValue());
|
||||
}
|
||||
connect.setInstanceFollowRedirects(true);
|
||||
if (handler != null)
|
||||
handler.check(connect.getServerCertificates());
|
||||
if (!(connect.getResponseCode() >= 200 && connect.getResponseCode() < 300))
|
||||
throw new IOException(String.format("Invalid response of http server %d.", connect.getResponseCode()));
|
||||
try (BufferedInputStream in = new BufferedInputStream(connect.getInputStream(), IOHelper.BUFFER_SIZE);
|
||||
FileOutputStream fout = new FileOutputStream(file, skip != 0)) {
|
||||
byte data[] = new byte[IOHelper.BUFFER_SIZE];
|
||||
int count = -1;
|
||||
long timestamp = System.currentTimeMillis();
|
||||
int writed_local = 0;
|
||||
in.skip(skip);
|
||||
while ((count = in.read(data)) != -1) {
|
||||
fout.write(data, 0, count);
|
||||
writed_local += count;
|
||||
if (System.currentTimeMillis() - timestamp > INTERVAL) {
|
||||
writed.set(writed_local);
|
||||
LogHelper.debug("Downloaded %d", writed_local);
|
||||
if (interrupt.get()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
LogHelper.debug("Downloaded %d", writed_local);
|
||||
writed.set(writed_local);
|
||||
}
|
||||
}
|
||||
interrupted.set(true);
|
||||
}
|
||||
public Downloader(URL url, File file, int skip, Handler handler, Map<String, String> requestProps, String method) {
|
||||
this.requestProps = new HashMap<>(requestProps);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = skip;
|
||||
this.handler = handler;
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
downloadFile();
|
||||
} catch (Throwable ex) {
|
||||
this.ex.set(ex);
|
||||
LogHelper.error(ex);
|
||||
}
|
||||
}
|
||||
public Downloader(URL url, File file, int skip, Handler handler, String method) {
|
||||
this.requestProps = new HashMap<>(requestClient);
|
||||
this.file = file;
|
||||
this.url = url;
|
||||
this.skip = skip;
|
||||
this.handler = handler;
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
public Map<String, String> getProps() {
|
||||
return requestProps;
|
||||
}
|
||||
|
||||
public void addProp(String key, String value) {
|
||||
requestProps.put(key, value);
|
||||
}
|
||||
|
||||
public File getFile() {
|
||||
return file;
|
||||
}
|
||||
|
||||
public String getMethod() {
|
||||
return method;
|
||||
}
|
||||
|
||||
public Handler getHandler() {
|
||||
return handler;
|
||||
}
|
||||
|
||||
public void downloadFile() throws IOException {
|
||||
if (!(url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equalsIgnoreCase("https")))
|
||||
throw new IOException("Invalid protocol.");
|
||||
interrupted.set(false);
|
||||
if (url.getProtocol().equalsIgnoreCase("http")) {
|
||||
HttpURLConnection connect = (HttpURLConnection) (url).openConnection();
|
||||
if (method != null) connect.setRequestMethod(method);
|
||||
for (Map.Entry<String, String> ent : requestProps.entrySet()) {
|
||||
connect.setRequestProperty(ent.getKey(), ent.getValue());
|
||||
}
|
||||
connect.setInstanceFollowRedirects(true);
|
||||
if (!(connect.getResponseCode() >= 200 && connect.getResponseCode() < 300))
|
||||
throw new IOException(String.format("Invalid response of http server %d.", connect.getResponseCode()));
|
||||
try (BufferedInputStream in = new BufferedInputStream(connect.getInputStream(), IOHelper.BUFFER_SIZE);
|
||||
FileOutputStream fout = new FileOutputStream(file, skip != 0)) {
|
||||
byte data[] = new byte[IOHelper.BUFFER_SIZE];
|
||||
int count = -1;
|
||||
long timestamp = System.currentTimeMillis();
|
||||
int writed_local = 0;
|
||||
in.skip(skip);
|
||||
while ((count = in.read(data)) != -1) {
|
||||
fout.write(data, 0, count);
|
||||
writed_local += count;
|
||||
if (System.currentTimeMillis() - timestamp > INTERVAL) {
|
||||
writed.set(writed_local);
|
||||
LogHelper.debug("Downloaded %d", writed_local);
|
||||
if (interrupt.get()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
LogHelper.debug("Downloaded %d", writed_local);
|
||||
writed.set(writed_local);
|
||||
}
|
||||
} else {
|
||||
HttpsURLConnection connect = (HttpsURLConnection) (url).openConnection();
|
||||
if (method != null) connect.setRequestMethod(method);
|
||||
for (Map.Entry<String, String> ent : requestProps.entrySet()) {
|
||||
connect.setRequestProperty(ent.getKey(), ent.getValue());
|
||||
}
|
||||
connect.setInstanceFollowRedirects(true);
|
||||
if (handler != null)
|
||||
handler.check(connect.getServerCertificates());
|
||||
if (!(connect.getResponseCode() >= 200 && connect.getResponseCode() < 300))
|
||||
throw new IOException(String.format("Invalid response of http server %d.", connect.getResponseCode()));
|
||||
try (BufferedInputStream in = new BufferedInputStream(connect.getInputStream(), IOHelper.BUFFER_SIZE);
|
||||
FileOutputStream fout = new FileOutputStream(file, skip != 0)) {
|
||||
byte data[] = new byte[IOHelper.BUFFER_SIZE];
|
||||
int count = -1;
|
||||
long timestamp = System.currentTimeMillis();
|
||||
int writed_local = 0;
|
||||
in.skip(skip);
|
||||
while ((count = in.read(data)) != -1) {
|
||||
fout.write(data, 0, count);
|
||||
writed_local += count;
|
||||
if (System.currentTimeMillis() - timestamp > INTERVAL) {
|
||||
writed.set(writed_local);
|
||||
LogHelper.debug("Downloaded %d", writed_local);
|
||||
if (interrupt.get()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
LogHelper.debug("Downloaded %d", writed_local);
|
||||
writed.set(writed_local);
|
||||
}
|
||||
}
|
||||
interrupted.set(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
downloadFile();
|
||||
} catch (Throwable ex) {
|
||||
this.ex.set(ex);
|
||||
LogHelper.error(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,31 +4,31 @@
|
|||
import java.net.URL;
|
||||
|
||||
public class DownloadingThread extends Thread {
|
||||
private final Downloader runnable;
|
||||
|
||||
public DownloadingThread(File file, URL url, String name) {
|
||||
super(name);
|
||||
runnable = new Downloader(url, file);
|
||||
}
|
||||
|
||||
public Downloader getDownloader() {
|
||||
return runnable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void interrupt() {
|
||||
runnable.interrupt.set(true);
|
||||
while (!runnable.interrupted.get()) {
|
||||
}
|
||||
super.interrupt();
|
||||
}
|
||||
|
||||
public void hardInterrupt() {
|
||||
super.interrupt();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
runnable.run();
|
||||
}
|
||||
private final Downloader runnable;
|
||||
|
||||
public DownloadingThread(File file, URL url, String name) {
|
||||
super(name);
|
||||
runnable = new Downloader(url, file);
|
||||
}
|
||||
|
||||
public Downloader getDownloader() {
|
||||
return runnable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void interrupt() {
|
||||
runnable.interrupt.set(true);
|
||||
while (!runnable.interrupted.get()) {
|
||||
}
|
||||
super.interrupt();
|
||||
}
|
||||
|
||||
public void hardInterrupt() {
|
||||
super.interrupt();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,8 +13,8 @@
|
|||
public class EventManager {
|
||||
public static final int QUEUE_MAX_SIZE = 2048;
|
||||
public static final int INITIAL_HANDLERS_SIZE = 16;
|
||||
public class Entry
|
||||
{
|
||||
|
||||
public class Entry {
|
||||
public Entry(EventHandler<EventInterface> func, UUID[] events) {
|
||||
this.func = func;
|
||||
this.events = events;
|
||||
|
@ -23,8 +23,8 @@ public Entry(EventHandler<EventInterface> func, UUID[] events) {
|
|||
EventHandler<EventInterface> func;
|
||||
UUID[] events;
|
||||
}
|
||||
public class QueueEntry
|
||||
{
|
||||
|
||||
public class QueueEntry {
|
||||
public QueueEntry(EventInterface event, UUID key) {
|
||||
this.event = event;
|
||||
this.key = key;
|
||||
|
@ -33,61 +33,65 @@ public QueueEntry(EventInterface event, UUID key) {
|
|||
EventInterface event;
|
||||
UUID key;
|
||||
}
|
||||
|
||||
private EventExecutor executor;
|
||||
private Thread executorThread;
|
||||
private AtomicBoolean isStarted = new AtomicBoolean(false);
|
||||
public synchronized void start()
|
||||
{
|
||||
if(isStarted.get()) return;
|
||||
|
||||
public synchronized void start() {
|
||||
if (isStarted.get()) return;
|
||||
executor = new EventExecutor();
|
||||
isStarted.set(true);
|
||||
executorThread = CommonHelper.newThread("EventExecutor",true,executor);
|
||||
executorThread = CommonHelper.newThread("EventExecutor", true, executor);
|
||||
executorThread.start();
|
||||
}
|
||||
public synchronized void stop()
|
||||
{
|
||||
if(!isStarted.get()) return;
|
||||
|
||||
public synchronized void stop() {
|
||||
if (!isStarted.get()) return;
|
||||
executorThread.interrupt();
|
||||
try {
|
||||
executorThread.join();
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
public ArrayList<Entry> handlers = new ArrayList<>(INITIAL_HANDLERS_SIZE);
|
||||
public BlockingQueue<QueueEntry> queue = new LinkedBlockingQueue<>(QUEUE_MAX_SIZE); //Максимальный размер очереди
|
||||
public int registerHandler(EventHandler<EventInterface> func, UUID[] events)
|
||||
{
|
||||
if(isStarted.get()) throw new IllegalThreadStateException("It is forbidden to add a handler during thread operation.");
|
||||
|
||||
public int registerHandler(EventHandler<EventInterface> func, UUID[] events) {
|
||||
if (isStarted.get())
|
||||
throw new IllegalThreadStateException("It is forbidden to add a handler during thread operation.");
|
||||
Arrays.sort(events);
|
||||
handlers.add(new Entry(func,events));
|
||||
handlers.add(new Entry(func, events));
|
||||
return handlers.size();
|
||||
}
|
||||
public void unregisterHandler(EventHandler<EventInterface> func)
|
||||
{
|
||||
if(isStarted.get()) throw new IllegalThreadStateException("It is forbidden to remove a handler during thread operation.");
|
||||
|
||||
public void unregisterHandler(EventHandler<EventInterface> func) {
|
||||
if (isStarted.get())
|
||||
throw new IllegalThreadStateException("It is forbidden to remove a handler during thread operation.");
|
||||
handlers.removeIf(e -> e.func.equals(func));
|
||||
}
|
||||
public void sendEvent(UUID key, EventInterface event, boolean blocking)
|
||||
{
|
||||
if(blocking) process(key,event);
|
||||
else queue.add(new QueueEntry(event,key));
|
||||
|
||||
public void sendEvent(UUID key, EventInterface event, boolean blocking) {
|
||||
if (blocking) process(key, event);
|
||||
else queue.add(new QueueEntry(event, key));
|
||||
}
|
||||
public void process(UUID key, EventInterface event)
|
||||
{
|
||||
for(Entry e : handlers)
|
||||
{
|
||||
if(Arrays.binarySearch(e.events,key) >= 0) e.func.run(key, event);
|
||||
|
||||
public void process(UUID key, EventInterface event) {
|
||||
for (Entry e : handlers) {
|
||||
if (Arrays.binarySearch(e.events, key) >= 0) e.func.run(key, event);
|
||||
}
|
||||
}
|
||||
|
||||
public class EventExecutor implements Runnable {
|
||||
public boolean enable = true;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while(enable && !Thread.interrupted())
|
||||
{
|
||||
while (enable && !Thread.interrupted()) {
|
||||
try {
|
||||
QueueEntry e = queue.take();
|
||||
process(e.key,e.event);
|
||||
process(e.key, e.event);
|
||||
} catch (InterruptedException e) {
|
||||
LogHelper.error(e);
|
||||
}
|
||||
|
|
|
@ -4,32 +4,32 @@
|
|||
import java.util.Map;
|
||||
|
||||
public class EnvHelper {
|
||||
public static final String[] toTest;
|
||||
public static final String[] toTest;
|
||||
|
||||
static {
|
||||
toTest = new String[] { "_JAVA_OPTIONS", "_JAVA_OPTS", "JAVA_OPTS", "JAVA_OPTIONS" };
|
||||
}
|
||||
static {
|
||||
toTest = new String[]{"_JAVA_OPTIONS", "_JAVA_OPTS", "JAVA_OPTS", "JAVA_OPTIONS"};
|
||||
}
|
||||
|
||||
public static void addEnv(ProcessBuilder builder) {
|
||||
Map<String, String> map = builder.environment();
|
||||
for (String env : toTest) {
|
||||
if(map.containsKey(env))
|
||||
map.put(env, "");
|
||||
String lower_env = env.toLowerCase(Locale.US);
|
||||
if(map.containsKey(lower_env))
|
||||
map.put(lower_env, "");
|
||||
}
|
||||
}
|
||||
public static void addEnv(ProcessBuilder builder) {
|
||||
Map<String, String> map = builder.environment();
|
||||
for (String env : toTest) {
|
||||
if (map.containsKey(env))
|
||||
map.put(env, "");
|
||||
String lower_env = env.toLowerCase(Locale.US);
|
||||
if (map.containsKey(lower_env))
|
||||
map.put(lower_env, "");
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkDangerousParams() {
|
||||
for (String t : toTest) {
|
||||
String env = System.getenv(t);
|
||||
if (env != null) {
|
||||
env = env.toLowerCase(Locale.US);
|
||||
if (env.contains("-cp") || env.contains("-classpath") || env.contains("-javaagent")
|
||||
|| env.contains("-agentpath") || env.contains("-agentlib"))
|
||||
throw new SecurityException("JavaAgent in global options not allow");
|
||||
}
|
||||
}
|
||||
}
|
||||
public static void checkDangerousParams() {
|
||||
for (String t : toTest) {
|
||||
String env = System.getenv(t);
|
||||
if (env != null) {
|
||||
env = env.toLowerCase(Locale.US);
|
||||
if (env.contains("-cp") || env.contains("-classpath") || env.contains("-javaagent")
|
||||
|| env.contains("-agentpath") || env.contains("-agentlib"))
|
||||
throw new SecurityException("JavaAgent in global options not allow");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -114,14 +114,13 @@ public static URL[] getClassPathURL() {
|
|||
}
|
||||
return list;
|
||||
}
|
||||
public static void checkStackTrace(Class mainClass)
|
||||
{
|
||||
|
||||
public static void checkStackTrace(Class mainClass) {
|
||||
LogHelper.debug("Testing stacktrace");
|
||||
Exception e = new Exception("Testing stacktrace");
|
||||
StackTraceElement[] list = e.getStackTrace();
|
||||
if(!list[list.length - 1].getClassName().equals(mainClass.getName()))
|
||||
{
|
||||
throw new SecurityException(String.format("Invalid StackTraceElement: %s",list[list.length - 1].getClassName()));
|
||||
if (!list[list.length - 1].getClassName().equals(mainClass.getName())) {
|
||||
throw new SecurityException(String.format("Invalid StackTraceElement: %s", list[list.length - 1].getClassName()));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -33,7 +33,7 @@
|
|||
import ru.gravit.launcher.LauncherAPI;
|
||||
|
||||
public final class SecurityHelper {
|
||||
|
||||
|
||||
public enum DigestAlgorithm {
|
||||
PLAIN("plain", -1), MD5("MD5", 128), SHA1("SHA-1", 160), SHA224("SHA-224", 224), SHA256("SHA-256", 256), SHA512("SHA-512", 512);
|
||||
private static final Map<String, DigestAlgorithm> ALGORITHMS;
|
||||
|
@ -78,9 +78,9 @@ public byte[] verify(byte[] digest) {
|
|||
}
|
||||
|
||||
// Algorithm constants
|
||||
|
||||
|
||||
public static final String RSA_ALGO = "RSA";
|
||||
|
||||
|
||||
public static final String RSA_SIGN_ALGO = "SHA256withRSA";
|
||||
|
||||
|
||||
|
@ -486,6 +486,7 @@ public static String verifyToken(String token) {
|
|||
|
||||
private SecurityHelper() {
|
||||
}
|
||||
|
||||
//AES
|
||||
public static byte[] encrypt(String seed, byte[] cleartext) throws Exception {
|
||||
byte[] rawKey = getRawKey(seed.getBytes());
|
||||
|
@ -520,6 +521,7 @@ public static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
|
|||
cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
|
||||
return cipher.doFinal(encrypted);
|
||||
}
|
||||
|
||||
public static byte[] HexToByte(String hexString) {
|
||||
int len = hexString.length() / 2;
|
||||
byte[] result = new byte[len];
|
||||
|
|
|
@ -9,15 +9,15 @@ public class UnpackHelper {
|
|||
@SuppressWarnings("ResultOfMethodCallIgnored")
|
||||
public static boolean unpack(URL resource, Path target) throws IOException {
|
||||
byte[] orig = IOHelper.read(resource);
|
||||
if(IOHelper.exists(target))
|
||||
{
|
||||
if(matches(target,orig)) return false;
|
||||
if (IOHelper.exists(target)) {
|
||||
if (matches(target, orig)) return false;
|
||||
}
|
||||
if (!IOHelper.exists(target))
|
||||
target.toFile().createNewFile();
|
||||
IOHelper.transfer(orig,target,false);
|
||||
IOHelper.transfer(orig, target, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean matches(Path target, byte[] in) {
|
||||
try {
|
||||
return Arrays.equals(SecurityHelper.digest(SecurityHelper.DigestAlgorithm.SHA256, in),
|
||||
|
|
Loading…
Reference in a new issue