-
Notifications
You must be signed in to change notification settings - Fork 0
/
GlobalServer.java
556 lines (499 loc) · 21 KB
/
GlobalServer.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
package de.cubeside.globalserver;
import de.cubeside.globalserver.command.AccountAddAllowedChannelCommand;
import de.cubeside.globalserver.command.AccountInfoCommand;
import de.cubeside.globalserver.command.AccountRemoveAllowedChannelCommand;
import de.cubeside.globalserver.command.AccountSetPasswordCommand;
import de.cubeside.globalserver.command.AccountSetRestrictedCommand;
import de.cubeside.globalserver.command.AccountsCommand;
import de.cubeside.globalserver.command.CreateAccountCommand;
import de.cubeside.globalserver.command.HelpCommand;
import de.cubeside.globalserver.command.ListCommand;
import de.cubeside.globalserver.command.PluginsCommand;
import de.cubeside.globalserver.command.ServersCommand;
import de.cubeside.globalserver.command.StopCommand;
import de.cubeside.globalserver.event.EventBus;
import de.cubeside.globalserver.event.clientconnection.ClientConnectionDissolveEvent;
import de.cubeside.globalserver.event.clientconnection.ClientConnectionEstablishedEvent;
import de.cubeside.globalserver.event.data.DataForwardEvent;
import de.cubeside.globalserver.event.globalserver.GlobalServerStartedEvent;
import de.cubeside.globalserver.event.globalserver.GlobalServerStoppedEvent;
import de.cubeside.globalserver.event.globalserver.GlobalServerStoppingEvent;
import de.cubeside.globalserver.event.player.PlayerJoinedEvent;
import de.cubeside.globalserver.event.player.PlayerQuitEvent;
import de.cubeside.globalserver.plugin.Plugin;
import de.cubeside.globalserver.plugin.PluginLoadException;
import de.cubeside.globalserver.plugin.PluginManager;
import de.cubeside.globalserver.plugin.PluginManagerWrapper;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.io.IoBuilder;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
public class GlobalServer {
static {
System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");
PrintStream logger = IoBuilder.forLogger("System.out").setLevel(Level.INFO).buildPrintStream();
PrintStream errorLogger = IoBuilder.forLogger("System.err").setLevel(Level.ERROR).buildPrintStream();
System.setOut(logger);
System.setErr(errorLogger);
}
public final static Logger LOGGER = LogManager.getLogger("Server");
private ServerListener listener;
private static ConsoleImpl console;
private boolean running;
private File configFile = new File("config.yml");
private Yaml configYaml;
private ServerConfig serverConfig;
private HashMap<String, ClientConfig> clientConfigs;
private ArrayList<ClientConnection> pendingConnections;
private ArrayList<ClientConnection> connections;
private HashMap<String, ClientConnection> connectionsByAccount;
private ConcurrentHashMap<String, ServerCommand> commands;
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
/**
* Required when a server is added/removed or a player is added/removed
*/
private final Lock readLock = lock.readLock();
/**
* Required when a command is executed/tab completed or data is sent
*/
private final Lock writeLock = lock.writeLock();
/**
* Used when accessing the field "running" and when waiting for/signaling the shutdownCondition
*/
private final Lock shutdownLock = new ReentrantLock();
private final Condition shutdownCondition = shutdownLock.newCondition();
private final EventBus eventBus = new EventBus();
private final PluginManagerWrapper pluginManagerWrapper;
private final PluginManager pluginManager;
private File pluginFolder;
private final ExecutorService executor;
public GlobalServer() throws PluginLoadException {
console = new JLineConsole(this);
LOGGER.info("Starting GlobalServer...");
executor = new ThreadPoolExecutor(1, Integer.MAX_VALUE, 300L, TimeUnit.SECONDS, new SynchronousQueue<>());
LoaderOptions loaderOptions = new LoaderOptions();
loaderOptions.setCodePointLimit(Integer.MAX_VALUE);
loaderOptions.setNestingDepthLimit(Integer.MAX_VALUE);
Constructor constructor = new Constructor(ServerConfig.class, loaderOptions);
TypeDescription serverConfigDescription = new TypeDescription(ServerConfig.class);
serverConfigDescription.addPropertyParameters("clientConfigs", ClientConfig.class);
constructor.addTypeDescription(serverConfigDescription);
configYaml = new Yaml(constructor);
if (configFile.exists()) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(configFile), Charset.forName("UTF-8")))) {
serverConfig = configYaml.loadAs(reader, ServerConfig.class);
saveConfig();
} catch (Exception e) {
LOGGER.error("Could not parse config!", e);
}
}
if (serverConfig == null) {
serverConfig = new ServerConfig();
LOGGER.info("Generating new config!");
if (!configFile.exists()) {
saveConfig();
}
}
clientConfigs = new HashMap<>();
for (ClientConfig cc : serverConfig.getClientConfigs()) {
clientConfigs.put(cc.getLogin(), cc);
}
pendingConnections = new ArrayList<>();
connections = new ArrayList<>();
connectionsByAccount = new HashMap<>();
commands = new ConcurrentHashMap<>();
addCommand(new HelpCommand());
addCommand(new StopCommand());
addCommand(new ServersCommand());
addCommand(new ListCommand());
addCommand(new AccountsCommand());
addCommand(new AccountInfoCommand());
addCommand(new CreateAccountCommand());
addCommand(new AccountSetPasswordCommand());
addCommand(new AccountSetRestrictedCommand());
addCommand(new AccountAddAllowedChannelCommand());
addCommand(new AccountRemoveAllowedChannelCommand());
addCommand(new PluginsCommand());
addCommand("pl", new PluginsCommand());
this.pluginFolder = new File("./plugins");
pluginFolder.mkdirs();
pluginManagerWrapper = new PluginManagerWrapper(this);
pluginManager = pluginManagerWrapper.getPluginManager();
pluginManagerWrapper.loadPlugins();
for (Plugin plugin : pluginManager.getPlugins()) {
LOGGER.info("Starting plugin " + plugin.getDescription().getName() + " " + plugin.getDescription().getVersion());
plugin.onLoad();
}
}
public File getPluginFolder() {
return pluginFolder;
}
public Collection<ServerCommand> getCommands() {
return Collections.unmodifiableCollection(commands.values());
}
public Collection<String> getCommandNames() {
return Collections.unmodifiableCollection(commands.keySet());
}
public ServerCommand getCommand(String name) {
return commands.get(name.toLowerCase());
}
public void addCommand(ServerCommand command) {
addCommand(command.getCommand(), command);
}
public void addCommand(String commandString, ServerCommand command) {
commands.put(commandString.toLowerCase().trim(), command);
}
public void addAccount(String login, String password) {
Objects.requireNonNull(login, "login must not be null");
Objects.requireNonNull(password, "password must not be null");
if (clientConfigs.containsKey(login)) {
throw new IllegalArgumentException("Login name in use: " + login);
}
ClientConfig cfg = new ClientConfig(login, password, false, new HashSet<>());
clientConfigs.put(login, cfg);
serverConfig.getClientConfigs().add(cfg);
saveConfig();
}
public void saveConfig() {
String output = configYaml.dumpAsMap(serverConfig);
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(configFile), Charset.forName("UTF-8")))) {
writer.write(output);
} catch (Exception e) {
LOGGER.error("Could not save config!", e);
}
}
public Collection<ClientConfig> getAccounts() {
return Collections.unmodifiableCollection(clientConfigs.values());
}
public ClientConfig getAccount(String name) {
return clientConfigs.get(name);
}
public List<ClientConnection> getConnections() {
return Collections.unmodifiableList(connections);
}
public ClientConnection getConnection(String account) {
return connectionsByAccount.get(account);
}
void run() {
running = true;
int port = serverConfig.getPort();
if (port <= 0) {
port = 25701;
serverConfig.setPort(port);
saveConfig();
}
try {
listener = new ServerListener(this, port);
listener.start();
} catch (IOException e) {
LOGGER.error("Could not bind to " + port + ": " + e.getMessage());
return;
}
readLock.lock();
try {
getEventBus().dispatchEvent(new GlobalServerStartedEvent(this));
} finally {
readLock.unlock();
}
while (true) {
readLock.lock();
try {
for (ClientConnection cc : connections) {
cc.sendPing();
}
} finally {
readLock.unlock();
}
shutdownLock.lock();
try {
if (running) {
try {
shutdownCondition.await(20, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// ignore
}
}
if (!running) {
break;
}
} finally {
shutdownLock.unlock();
}
}
writeLock.lock();
try {
listener.shutdown();
getEventBus().dispatchEvent(new GlobalServerStoppingEvent(this));
for (ClientConnection cc : new ArrayList<>(pendingConnections)) {
cc.closeConnection();
}
pendingConnections.clear();
for (ClientConnection cc : new ArrayList<>(connections)) {
cc.closeConnection();
}
connections.clear();
connectionsByAccount.clear();
getEventBus().dispatchEvent(new GlobalServerStoppedEvent(this));
for (Plugin plugin : pluginManager.getPlugins()) {
LOGGER.info("Unloading plugin " + plugin.getDescription().getName() + " " + plugin.getDescription().getVersion());
plugin.onUnload();
}
executor.shutdown();
try {
// wait 1 second without info, only print a message if this was not enough
if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
LOGGER.info("Waiting 60 seconds for all async tasks to finish...");
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
LOGGER.warn("Not all tasks were completed before unloading!");
} else {
LOGGER.info("All tasks have finished executing!");
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
pluginManagerWrapper.shutdown();
console.stop();
} finally {
writeLock.unlock();
}
}
public static void main(String[] args) {
try {
new GlobalServer().run();
} catch (PluginLoadException e) {
LOGGER.error("Could not load plugins", e);
}
LogManager.shutdown();
}
public void processCommand(String line) {
line = line.trim();
if (line.length() == 0) {
return;
}
int firstSpace = line.indexOf(' ');
String cmd = (firstSpace < 0 ? line : line.substring(0, firstSpace)).toLowerCase().trim();
String args = firstSpace < 0 ? "" : line.substring(firstSpace + 1);
ServerCommand command = commands.get(cmd);
if (command != null) {
ArrayList<String> splitArgs = new ArrayList<>();
for (String s : args.trim().split(" ++")) {
String s2 = s.trim();
if (s2.length() > 0) {
splitArgs.add(s2);
}
}
readLock.lock();
try {
command.execute(this, new ArgsParser(splitArgs.toArray(new String[splitArgs.size()])));
} finally {
readLock.unlock();
}
} else {
LOGGER.info("Unknown command: " + cmd);
}
}
public void stopServer() {
shutdownLock.lock();
try {
running = false;
shutdownCondition.signal();
} finally {
shutdownLock.unlock();
}
}
void addPendingConnection(ClientConnection connection) {
writeLock.lock();
try {
pendingConnections.add(connection);
} finally {
writeLock.unlock();
}
}
void removeConnection(ClientConnection connection) {
writeLock.lock();
try {
boolean wasOnline = connections.remove(connection);
pendingConnections.remove(connection);
if (wasOnline) {
connectionsByAccount.remove(connection.getAccount());
for (ClientConnection cc : connections) {
if (cc != connection) {
cc.sendServerOffline(connection.getAccount());
}
}
for (OnlinePlayer player : connection.getPlayers()) {
getEventBus().dispatchEvent(new PlayerQuitEvent(connection, player));
}
getEventBus().dispatchEvent(new ClientConnectionDissolveEvent(connection));
}
} finally {
writeLock.unlock();
}
}
ClientConfig processLogin(ClientConnection connection, String account, byte[] password, byte[] saltServer, byte[] saltClient) throws IOException {
writeLock.lock();
try {
ClientConfig config = clientConfigs.get(account);
if (config == null || !config.checkPassword(password, saltServer, saltClient)) {
LOGGER.info("Login failed for '" + account + "'.");
pendingConnections.remove(connection);
connection.sendLoginResultAndActivateEncryption(false, null);
return null;
}
LOGGER.info("Login successfull for '" + account + "'.");
for (ClientConnection cc : connections) {
if (cc.getAccount().equals(account)) {
cc.closeConnection();
removeConnection(cc);
break;
}
}
connection.setClient(config);
pendingConnections.remove(connection);
connections.add(connection);
connectionsByAccount.put(connection.getAccount(), connection);
connection.sendLoginResultAndActivateEncryption(true, config);
// send online servers
for (ClientConnection cc : connections) {
if (cc != connection) {
cc.sendServerOnline(account);
connection.sendServerOnline(cc.getAccount());
Collection<OnlinePlayer> players = cc.getPlayers();
for (OnlinePlayer e : players) {
connection.sendPlayerOnline(cc.getAccount(), e.getUuid(), e.getName(), e.getJoinTime());
}
}
}
getEventBus().dispatchEvent(new ClientConnectionEstablishedEvent(connection));
return config;
} finally {
writeLock.unlock();
}
}
void processPlayerOnline(ClientConnection connection, UUID uuid, String name, long joinTime) {
writeLock.lock();
try {
OnlinePlayer joined = connection.addPlayer(uuid, name, joinTime);
if (joined != null) {
for (ClientConnection cc : connections) {
if (cc != connection) {
cc.sendPlayerOnline(connection.getAccount(), uuid, name, joinTime);
}
}
getEventBus().dispatchEvent(new PlayerJoinedEvent(connection, joined));
}
} finally {
writeLock.unlock();
}
}
void processPlayerOffline(ClientConnection connection, UUID uuid) {
writeLock.lock();
try {
OnlinePlayer player = connection.removePlayer(uuid);
if (player != null) {
for (ClientConnection cc : connections) {
if (cc != connection) {
cc.sendPlayerOffline(connection.getAccount(), uuid);
}
}
getEventBus().dispatchEvent(new PlayerQuitEvent(connection, player));
}
} finally {
writeLock.unlock();
}
}
void processData(ClientConnection connection, String channel, UUID targetUuid, String targetServer, byte[] data, boolean allowRestricted, boolean toAllUnrestrictedServers) {
readLock.lock();
try {
HashSet<ClientConnection> targets = new HashSet<>();
ClientConnection targetServerConnection = targetServer == null ? null : connectionsByAccount.get(targetServer);
boolean fromRestricted = connection.getClient().isRestricted();
if (!fromRestricted || connection.getClient().getAllowedChannels().contains(channel)) {
for (ClientConnection cc : connections) {
if (cc != connection) {
boolean toRestricted = cc.getClient().isRestricted();
if (!toRestricted || cc.getClient().getAllowedChannels().contains(channel)) {
boolean explicitServer = cc == targetServerConnection;
if (targetServer == null || explicitServer) {
boolean explicitPlayer = targetUuid != null && cc.hasPlayer(targetUuid);
if (toAllUnrestrictedServers || targetUuid == null || explicitPlayer) {
if (allowRestricted || (!fromRestricted && !toRestricted) || explicitServer || explicitPlayer) {
targets.add(cc);
}
}
}
}
}
}
}
DataForwardEvent event = new DataForwardEvent(connection, targets, channel, targetUuid, targetServerConnection, data, allowRestricted, toAllUnrestrictedServers);
getEventBus().dispatchEvent(event);
if (!event.isCancelled()) {
channel = event.getChannel();
targetUuid = event.getTargetUuid();
targetServerConnection = event.getTargetServer();
data = event.getData();
for (ClientConnection target : event.getTargets()) {
target.sendData(connection, channel, targetUuid, targetServerConnection, data);
}
}
} finally {
readLock.unlock();
}
}
public void runWithReadLock(Runnable r) {
readLock.lock();
try {
r.run();
} finally {
readLock.unlock();
}
}
public static Console getConsole() {
return console;
}
Lock getReadLock() {
return readLock;
}
public EventBus getEventBus() {
return eventBus;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public ExecutorService getExecutor() {
return executor;
}
}