/
ExHost.java
315 lines (281 loc) · 16.9 KB
/
ExHost.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package net.ME1312.SubServers.Host;
import com.dosse.upnp.UPnP;
import net.ME1312.Galaxi.Engine.GalaxiEngine;
import net.ME1312.Galaxi.Engine.GalaxiOption;
import net.ME1312.Galaxi.Event.GalaxiReloadEvent;
import net.ME1312.Galaxi.Galaxi;
import net.ME1312.Galaxi.Library.Config.YAMLConfig;
import net.ME1312.Galaxi.Library.Config.YAMLSection;
import net.ME1312.Galaxi.Library.Log.Logger;
import net.ME1312.Galaxi.Library.NamedContainer;
import net.ME1312.Galaxi.Library.UniversalFile;
import net.ME1312.Galaxi.Library.Util;
import net.ME1312.Galaxi.Library.Version.Version;
import net.ME1312.Galaxi.Library.Version.VersionType;
import net.ME1312.Galaxi.Plugin.Plugin;
import net.ME1312.Galaxi.Plugin.PluginInfo;
import net.ME1312.SubServers.Host.Executable.SubCreator;
import net.ME1312.SubServers.Host.Executable.SubServer;
import net.ME1312.SubServers.Host.Library.*;
import net.ME1312.SubServers.Host.Network.Cipher;
import net.ME1312.SubServers.Host.Network.SubDataClient;
import org.json.JSONObject;
import java.io.*;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.jar.Manifest;
/**
* SubServers.Host Main Class
*/
@Plugin(name = "SubServers.Host", version = "2.13.2c", authors = "ME1312", description = "Host SubServers from other Machines", website = "https://github.com/ME1312/SubServers-2")
public final class ExHost {
protected NamedContainer<Long, Map<String, Map<String, String>>> lang = null;
public HashMap<String, SubCreator.ServerTemplate> templates = new HashMap<String, SubCreator.ServerTemplate>();
public HashMap<String, SubServer> servers = new HashMap<String, SubServer>();
public SubCreator creator;
public Logger log;
public PluginInfo info;
public GalaxiEngine engine;
public YAMLConfig config;
public YAMLSection host = null;
public SubDataClient subdata = null;
public final SubAPI api = new SubAPI(this);
private boolean running = false;
/**
* SubServers.Host Launch
*
* @param args Args
* @throws Exception
*/
static void main(String[] args) throws Exception {
if (System.getProperty("RM.subservers", "true").equalsIgnoreCase("true")) {
joptsimple.OptionParser parser = new joptsimple.OptionParser();
parser.allowsUnrecognizedOptions();
parser.accepts("v");
parser.accepts("version");
parser.accepts("noconsole");
joptsimple.OptionSet options = parser.parse(args);
if(options.has("version") || options.has("v")) {
String osarch;
if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
String arch = System.getenv("PROCESSOR_ARCHITECTURE");
String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432");
osarch = arch != null && arch.endsWith("64") || wow64Arch != null && wow64Arch.endsWith("64")?"x64":"x86";
} else if (System.getProperty("os.arch").endsWith("86")) {
osarch = "x86";
} else if (System.getProperty("os.arch").endsWith("64")) {
osarch = "x64";
} else {
osarch = System.getProperty("os.arch");
}
String javaarch = null;
switch (System.getProperty("sun.arch.data.model")) {
case "32":
javaarch = "x86";
break;
case "64":
javaarch = "x64";
break;
default:
if (!System.getProperty("sun.arch.data.model").equalsIgnoreCase("unknown"))
javaarch = System.getProperty("sun.arch.data.model");
}
Version galaxi = Version.fromString(GalaxiEngine.class.getAnnotation(Plugin.class).version());
Version subservers = Version.fromString(ExHost.class.getAnnotation(Plugin.class).version());
Version galaxibuild = null;
Version subserversbuild = null;
try {
Manifest manifest = new Manifest(GalaxiEngine.class.getResourceAsStream("/META-INF/GalaxiEngine.MF"));
if (manifest.getMainAttributes().getValue("Implementation-Version") != null && manifest.getMainAttributes().getValue("Implementation-Version").length() > 0)
galaxibuild = new Version(manifest.getMainAttributes().getValue("Implementation-Version"));
} catch (Exception e) {} try {
if (Util.reflect(Version.class.getDeclaredField("type"), subservers) != VersionType.SNAPSHOT && ExHost.class.getPackage().getSpecificationTitle() != null)
subserversbuild = new Version(ExHost.class.getPackage().getSpecificationTitle());
} catch (Exception e) {}
System.out.println("");
System.out.println(System.getProperty("os.name") + ((!System.getProperty("os.name").toLowerCase().startsWith("windows"))?' ' + System.getProperty("os.version"):"") + ((osarch != null)?" [" + osarch + ']':"") + ',');
System.out.println("Java " + System.getProperty("java.version") + ((javaarch != null)?" [" + javaarch + ']':"") + ',');
System.out.println(GalaxiEngine.class.getAnnotation(Plugin.class).name() + " v" + galaxi.toExtendedString() + ((galaxibuild != null)?" (" + galaxibuild + ')':"")
+ ((GalaxiEngine.class.getProtectionDomain().getCodeSource().getLocation().equals(ExHost.class.getProtectionDomain().getCodeSource().getLocation()))?" [Patched]":"") + ',');
System.out.println(ExHost.class.getAnnotation(Plugin.class).name() + " v" + subservers.toExtendedString() + ((subserversbuild != null)?" (" + subserversbuild + ')':""));
System.out.println("");
} else {
new ExHost(options);
}
} else {
System.out.println(">> SubServers code has been disallowed to work on this machine");
System.out.println(">> Check with your provider for more information");
System.exit(1);
}
}
private ExHost(joptsimple.OptionSet options) {
log = new Logger("SubServers");
try {
info = PluginInfo.getPluginInfo(this);
info.setLogger(log);
if (ExHost.class.getPackage().getSpecificationTitle() != null) info.setSignature(new Version(ExHost.class.getPackage().getSpecificationTitle()));
info.setIcon(ExHost.class.getResourceAsStream("/net/ME1312/SubServers/Host/Library/Files/icon.png"));
engine = GalaxiEngine.init(info);
log.info.println("Loading SubServers.Host v" + info.getVersion().toString() + " Libraries");
if (!(new UniversalFile(engine.getRuntimeDirectory(), "config.yml").exists())) {
Util.copyFromJar(ExHost.class.getClassLoader(), "net/ME1312/SubServers/Host/Library/Files/config.yml", new UniversalFile(engine.getRuntimeDirectory(), "config.yml").getPath());
log.info.println("Created ~/config.yml");
} else if (((new YAMLConfig(new UniversalFile(engine.getRuntimeDirectory(), "config.yml"))).get().getSection("Settings").getVersion("Version", new Version(0)).compareTo(new Version("2.11.2a+"))) != 0) {
Files.move(new UniversalFile(engine.getRuntimeDirectory(), "config.yml").toPath(), new UniversalFile(engine.getRuntimeDirectory(), "config.old" + Math.round(Math.random() * 100000) + ".yml").toPath());
Util.copyFromJar(ExHost.class.getClassLoader(), "net/ME1312/SubServers/Host/Library/Files/config.yml", new UniversalFile(engine.getRuntimeDirectory(), "config.yml").getPath());
log.info.println("Updated ~/config.yml");
}
config = new YAMLConfig(new UniversalFile(engine.getRuntimeDirectory(), "config.yml"));
if (!(new UniversalFile(engine.getRuntimeDirectory(), "Templates").exists())) {
new UniversalFile(engine.getRuntimeDirectory(), "Templates").mkdir();
log.info.println("Created ~/Templates/");
}
if (new UniversalFile(engine.getRuntimeDirectory(), "Recently Deleted").exists()) {
int f = new UniversalFile(engine.getRuntimeDirectory(), "Recently Deleted").listFiles().length;
for (File file : new UniversalFile(engine.getRuntimeDirectory(), "Recently Deleted").listFiles()) {
try {
if (file.isDirectory()) {
if (new UniversalFile(engine.getRuntimeDirectory(), "Recently Deleted:" + file.getName() + ":info.json").exists()) {
FileReader reader = new FileReader(new UniversalFile(engine.getRuntimeDirectory(), "Recently Deleted:" + file.getName() + ":info.json"));
JSONObject json = new JSONObject(Util.readAll(reader));
reader.close();
if (json.keySet().contains("Timestamp")) {
if (TimeUnit.MILLISECONDS.toDays(Calendar.getInstance().getTime().getTime() - json.getLong("Timestamp")) >= 7) {
Util.deleteDirectory(file);
f--;
log.info.println("Removed ~/Recently Deleted/" + file.getName());
}
} else {
Util.deleteDirectory(file);
f--;
log.info.println("Removed ~/Recently Deleted/" + file.getName());
}
} else {
Util.deleteDirectory(file);
f--;
log.info.println("Removed ~/Recently Deleted/" + file.getName());
}
} else {
Files.delete(file.toPath());
f--;
log.info.println("Removed ~/Recently Deleted/" + file.getName());
}
} catch (Exception e) {
log.error.println(e);
}
}
if (f <= 0) {
Files.delete(new UniversalFile(engine.getRuntimeDirectory(), "Recently Deleted").toPath());
}
}
engine.getPluginManager().loadPlugins(new UniversalFile(engine.getRuntimeDirectory(), "Plugins"));
running = true;
Cipher cipher = null;
if (!config.get().getSection("Settings").getSection("SubData").getRawString("Encryption", "NONE").equalsIgnoreCase("NONE")) {
if (config.get().getSection("Settings").getSection("SubData").getString("Password", "").length() == 0) {
log.info.println("Cannot encrypt connection without a password");
} else if (!SubDataClient.getCiphers().keySet().contains(config.get().getSection("Settings").getSection("SubData").getRawString("Encryption").toUpperCase().replace('-', '_').replace(' ', '_'))) {
log.info.println("Unknown encryption type: " + config.get().getSection("Settings").getSection("SubData").getRawString("Encryption"));
} else {
cipher = SubDataClient.getCipher(config.get().getSection("Settings").getSection("SubData").getRawString("Encryption"));
}
}
subdata = new SubDataClient(this, config.get().getSection("Settings").getSection("SubData").getString("Name", "undefined"),
InetAddress.getByName(config.get().getSection("Settings").getSection("SubData").getString("Address", "127.0.0.1:4391").split(":")[0]),
Integer.parseInt(config.get().getSection("Settings").getSection("SubData").getString("Address", "127.0.0.1:4391").split(":")[1]), cipher);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
if (running) {
log.warn.println("Received request from system to shutdown");
engine.stop();
}
}, SubAPI.getInstance().getAppInfo().getName() + "::System_Shutdown"));
creator = new SubCreator(this);
loadDefaults();
new Metrics(this);
info.setUpdateChecker(() -> {
try {
YAMLSection tags = new YAMLSection(new JSONObject("{\"tags\":" + Util.readAll(new BufferedReader(new InputStreamReader(new URL("https://api.github.com/repos/ME1312/SubServers-2/git/refs/tags").openStream(), Charset.forName("UTF-8")))) + '}'));
List<Version> versions = new LinkedList<Version>();
Version updversion = info.getVersion();
int updcount = 0;
for (YAMLSection tag : tags.getSectionList("tags")) versions.add(Version.fromString(tag.getString("ref").substring(10)));
Collections.sort(versions);
for (Version version : versions) {
if (version.compareTo(updversion) > 0) {
updversion = version;
updcount++;
}
}
if (updcount > 0) log.info.println("SubServers.Host v" + updversion + " is available. You are " + updcount + " version" + ((updcount == 1)?"":"s") + " behind.");
} catch (Exception e) {}
});
engine.start(this::stop);
if (!UPnP.isUPnPAvailable()) {
log.warn.println("UPnP is currently unavailable; Ports may not be automatically forwarded on this device");
}
} catch (Exception e) {
log.error.println(e);
engine.stop(1);
}
}
public void reload() throws IOException {
if (subdata != null)
subdata.destroy(0);
config.reload();
Cipher cipher = null;
if (!config.get().getSection("Settings").getSection("SubData").getRawString("Encryption", "NONE").equalsIgnoreCase("NONE")) {
if (config.get().getSection("Settings").getSection("SubData").getString("Password", "").length() == 0) {
log.info.println("Cannot encrypt connection without a password");
} else if (!SubDataClient.getCiphers().keySet().contains(config.get().getSection("Settings").getSection("SubData").getRawString("Encryption").toUpperCase().replace('-', '_').replace(' ', '_'))) {
log.info.println("Unknown encryption type: " + config.get().getSection("Settings").getSection("SubData").getRawString("Encryption"));
} else {
cipher = SubDataClient.getCipher(config.get().getSection("Settings").getSection("SubData").getRawString("Encryption"));
}
}
subdata = new SubDataClient(this, config.get().getSection("Settings").getSection("SubData").getString("Name", "undefined"),
InetAddress.getByName(config.get().getSection("Settings").getSection("SubData").getString("Address", "127.0.0.1:4391").split(":")[0]),
Integer.parseInt(config.get().getSection("Settings").getSection("SubData").getString("Address", "127.0.0.1:4391").split(":")[1]), cipher);
engine.getPluginManager().executeEvent(new GalaxiReloadEvent(engine));
}
private void loadDefaults() {
SubCommand.load(this);
}
private void stop() {
if (running) {
log.info.println("Shutting down...");
List<String> subservers = new ArrayList<String>();
subservers.addAll(servers.keySet());
for (String server : subservers) {
servers.get(server).stop();
try {
servers.get(server).waitFor();
} catch (Exception e) {
log.error.println(e);
}
if (UPnP.isUPnPAvailable() && UPnP.isMappedTCP(servers.get(server).getPort())) UPnP.closePortTCP(servers.get(server).getPort());
}
servers.clear();
if (creator != null) {
creator.terminate();
try {
creator.waitFor();
} catch (Exception e) {
log.error.println(e);
}
}
running = false;
try {
Thread.sleep(500);
} catch (Exception e) {
log.error.println(e);
}
if (subdata != null) Util.isException(() -> subdata.destroy(0));
if (new File(engine.getRuntimeDirectory(), "Templates").exists()) Util.deleteDirectory(new File(engine.getRuntimeDirectory(), "Templates"));
}
}
}