/
ExHost.java
341 lines (303 loc) · 17.2 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package net.ME1312.SubServers.Host;
import net.ME1312.Galaxi.Engine.GalaxiEngine;
import net.ME1312.Galaxi.Event.GalaxiReloadEvent;
import net.ME1312.Galaxi.Library.Config.YAMLConfig;
import net.ME1312.Galaxi.Library.Config.YAMLSection;
import net.ME1312.Galaxi.Library.Container.Pair;
import net.ME1312.Galaxi.Library.Log.Logger;
import net.ME1312.Galaxi.Library.Map.ObjectMap;
import net.ME1312.Galaxi.Library.Platform;
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.App;
import net.ME1312.Galaxi.Plugin.PluginInfo;
import net.ME1312.SubData.Client.DataClient;
import net.ME1312.SubData.Client.Encryption.AES;
import net.ME1312.SubData.Client.Encryption.DHE;
import net.ME1312.SubData.Client.Encryption.RSA;
import net.ME1312.SubData.Client.Library.DataSize;
import net.ME1312.SubData.Client.Library.DisconnectReason;
import net.ME1312.SubData.Client.SubDataClient;
import net.ME1312.SubServers.Host.Executable.SubCreatorImpl;
import net.ME1312.SubServers.Host.Executable.SubLoggerImpl;
import net.ME1312.SubServers.Host.Executable.SubServerImpl;
import net.ME1312.SubServers.Host.Library.ConfigUpdater;
import net.ME1312.SubServers.Host.Library.Metrics;
import net.ME1312.SubServers.Host.Network.SubProtocol;
import com.dosse.upnp.UPnP;
import org.json.JSONObject;
import java.io.*;
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
*/
@App(name = "SubServers.Host", version = "2.17a", authors = "ME1312", website = "https://github.com/ME1312/SubServers-2", description = "Host subservers on separate machines")
public final class ExHost {
HashMap<Integer, SubDataClient> subdata = new HashMap<Integer, SubDataClient>();
Pair<Long, Map<String, Map<String, String>>> lang = null;
public HashMap<String, SubCreatorImpl.ServerTemplate> templatesR = new HashMap<String, SubCreatorImpl.ServerTemplate>();
public HashMap<String, SubCreatorImpl.ServerTemplate> templates = new HashMap<String, SubCreatorImpl.ServerTemplate>();
public HashMap<String, SubServerImpl> servers = new HashMap<String, SubServerImpl>();
public SubCreatorImpl creator;
public Logger log;
public PluginInfo info;
public GalaxiEngine engine;
public YAMLConfig config;
public ObjectMap<String> host = null;
public SubProtocol subprotocol;
public final SubAPI api = new SubAPI(this);
private long resetDate = 0;
private boolean reconnect = true;
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")) {
Version galaxi = Version.fromString(GalaxiEngine.class.getAnnotation(App.class).version());
Version subservers = Version.fromString(ExHost.class.getAnnotation(App.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(Platform.getSystemName() + ' ' + Platform.getSystemVersion() + ((!Platform.getSystemArchitecture().equals("unknown"))?" [" + Platform.getSystemArchitecture() + ']':"") + ',');
System.out.println("Java " + Platform.getJavaVersion() + ((!Platform.getJavaArchitecture().equals("unknown"))?" [" + Platform.getJavaArchitecture() + ']':"") + ',');
System.out.println(GalaxiEngine.class.getAnnotation(App.class).name() + " v" + galaxi.toExtendedString() + ((galaxibuild != null)?" (" + galaxibuild + ')':"") + ',');
System.out.println(ExHost.class.getAnnotation(App.class).name() + " v" + subservers.toExtendedString() + ((subserversbuild != null)?" (" + subserversbuild + ')':""));
System.out.println("");
} else {
new ExHost(options);
}
} else {
System.out.println(">> SubServers' hosting capabilities have been disallowed 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");
ConfigUpdater.updateConfig(new UniversalFile(engine.getRuntimeDirectory(), "config.yml"));
config = new YAMLConfig(new UniversalFile(engine.getRuntimeDirectory(), "config.yml"));
if (!(new UniversalFile(engine.getRuntimeDirectory(), "Templates").exists())) {
new UniversalFile(engine.getRuntimeDirectory(), "Templates").mkdirs();
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());
}
}
Util.reflect(SubLoggerImpl.class.getDeclaredField("logn"), null, config.get().getMap("Settings").getBoolean("Network-Log", true));
Util.reflect(SubLoggerImpl.class.getDeclaredField("logc"), null, config.get().getMap("Settings").getBoolean("Console-Log", true));
loadDefaults();
engine.getPluginManager().loadPlugins(new UniversalFile(engine.getRuntimeDirectory(), "Plugins"));
running = true;
creator = new SubCreatorImpl(this);
reload(false);
subdata.put(0, null);
subprotocol = SubProtocol.get();
subprotocol.registerCipher("DHE", DHE.get(128));
subprotocol.registerCipher("DHE-128", DHE.get(128));
subprotocol.registerCipher("DHE-192", DHE.get(192));
subprotocol.registerCipher("DHE-256", DHE.get(256));
api.name = config.get().getMap("Settings").getMap("SubData").getString("Name", null);
Logger log = new Logger("SubData");
if (config.get().getMap("Settings").getMap("SubData").getRawString("Password", "").length() > 0) {
subprotocol.registerCipher("AES", new AES(128, config.get().getMap("Settings").getMap("SubData").getRawString("Password")));
subprotocol.registerCipher("AES-128", new AES(128, config.get().getMap("Settings").getMap("SubData").getRawString("Password")));
subprotocol.registerCipher("AES-192", new AES(192, config.get().getMap("Settings").getMap("SubData").getRawString("Password")));
subprotocol.registerCipher("AES-256", new AES(256, config.get().getMap("Settings").getMap("SubData").getRawString("Password")));
log.info.println("AES Encryption Available");
}
if (new UniversalFile(engine.getRuntimeDirectory(), "subdata.rsa.key").exists()) {
try {
subprotocol.registerCipher("RSA", new RSA(new UniversalFile(engine.getRuntimeDirectory(), "subdata.rsa.key")));
log.info.println("RSA Encryption Available");
} catch (Exception e) {
log.error.println(e);
}
}
reconnect = true;
log.info.println();
log.info.println("Connecting to /" + config.get().getMap("Settings").getMap("SubData").getRawString("Address", "127.0.0.1:4391"));
connect(log.toPrimitive(), null);
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 (ObjectMap<String> tag : tags.getMapList("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) {
if (engine == null) {
e.printStackTrace();
System.exit(1);
} else {
log.error.println(e);
engine.stop(1);
}
}
}
private void loadDefaults() {
new SubCommand(this).load();
}
public void reload(boolean notifyPlugins) throws IOException {
resetDate = Calendar.getInstance().getTime().getTime();
ConfigUpdater.updateConfig(new UniversalFile(engine.getRuntimeDirectory(), "config.yml"));
config.reload();
creator.load(false);
if (notifyPlugins) {
engine.getPluginManager().executeEvent(new GalaxiReloadEvent(engine));
}
}
private void connect(java.util.logging.Logger log, Pair<DisconnectReason, DataClient> disconnect) throws IOException {
int reconnect = config.get().getMap("Settings").getMap("SubData").getInt("Reconnect", 60);
if (disconnect == null || (this.reconnect && reconnect > 0 && disconnect.key() != DisconnectReason.PROTOCOL_MISMATCH && disconnect.key() != DisconnectReason.ENCRYPTION_MISMATCH)) {
long reset = resetDate;
Timer timer = new Timer(SubAPI.getInstance().getAppInfo().getName() + "::SubData_Reconnect_Handler");
if (disconnect != null) log.info("Attempting reconnect in " + reconnect + " seconds");
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
if (reset == resetDate && (subdata.getOrDefault(0, null) == null || subdata.get(0).isClosed())) {
SubDataClient open = subprotocol.open((config.get().getMap("Settings").getMap("SubData").getRawString("Address", "127.0.0.1:4391").split(":")[0].equals("0.0.0.0"))?
null:InetAddress.getByName(config.get().getMap("Settings").getMap("SubData").getRawString("Address", "127.0.0.1:4391").split(":")[0]),
Integer.parseInt(config.get().getMap("Settings").getMap("SubData").getRawString("Address", "127.0.0.1:4391").split(":")[1]));
if (subdata.getOrDefault(0, null) != null) subdata.get(0).reconnect(open);
subdata.put(0, open);
}
timer.cancel();
} catch (IOException e) {
log.info("Connection was unsuccessful, retrying in " + reconnect + " seconds");
}
}
}, (disconnect == null)?0:TimeUnit.SECONDS.toMillis(reconnect), TimeUnit.SECONDS.toMillis(reconnect));
}
}
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);
}
reconnect = false;
try {
ArrayList<SubDataClient> temp = new ArrayList<SubDataClient>();
temp.addAll(subdata.values());
for (SubDataClient client : temp) if (client != null) {
client.close();
client.waitFor();
}
subdata.clear();
subdata.put(0, null);
} catch (Exception e) {
log.error.println(e);
}
if (new UniversalFile(engine.getRuntimeDirectory(), "Cache:Remote").exists()) Util.deleteDirectory(new UniversalFile(engine.getRuntimeDirectory(), "Cache:Remote"));
}
}
}