/
TASServer.java
930 lines (797 loc) · 30 KB
/
TASServer.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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
/*
* Created on 2005.6.16
*/
package com.springrts.tasserver;
import com.springrts.tasserver.commands.CommandProcessingException;
import com.springrts.tasserver.commands.CommandProcessor;
import com.springrts.tasserver.commands.CommandProcessors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.regex.PatternSyntaxException;
/**
* @author Betalord
*/
public class TASServer implements LiveStateListener {
private final String UPDATE_PROPERTIES_FILENAME = "updates.xml";
/**
* If true, the server will keep a log of all conversations from
* the channel #main (in file "MainChanLog.log")
*/
//boolean logMainChannel = false;
//private List<String> whiteList = new LinkedList<String>();
/**
* In this interval, all channel mute lists will be checked
* for expirations and purged accordingly. In milliseconds.
*/
private long purgeMutesInterval = 1000 * 3;
/**
* Time when we last purged mute lists of all channels.
* @see System.currentTimeMillis()
*/
private long lastMutesPurgeTime = System.currentTimeMillis();
private static final Log s_log = LogFactory.getLog(TASServer.class);
private final int READ_BUFFER_SIZE = 256; // size of the ByteBuffer used to read data from the socket channel. This size doesn't really matter - server will work with any size (tested with READ_BUFFER_SIZE==1), but too small buffer size may impact the performance.
private final int SEND_BUFFER_SIZE = 8192 * 2; // socket's send buffer size
private final long MAIN_LOOP_SLEEP = 10L;
private ServerSocketChannel sSockChan;
private Selector readSelector;
private boolean running;
/**
* See
* <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/ByteBuffer.html">
* ByteBuffer JavaDoc</a> for the difference between direct and non-direct
* buffers. In this case, we should use direct buffers. They are also used
* by the author of the <code>java.nio</code> chat example (see links) upon
* which this code is built on.
*/
private ByteBuffer readBuffer = ByteBuffer.allocateDirect(READ_BUFFER_SIZE);
private Context context = null;
private CommandProcessors commandProcessors = null;
/**
* In 'updateProperties' we store a list of Spring versions and server responses to them.
* We use it when client doesn't have the latest Spring version or the lobby program
* and requests an update from us. The XML file should normally contain at least the "default" key
* which contains a standard response in case no suitable response is found.
* Each text field associated with a key contains a full string that will be send to the client
* as a response, so it should contain a full server command.
*/
private Properties updateProperties = new Properties();
private boolean readUpdateProperties(String fileName) {
boolean success = false;
FileInputStream fStream = null;
try {
fStream = new FileInputStream(fileName);
updateProperties.loadFromXML(fStream);
success = true;
} catch (IOException ex) {
s_log.warn("Could not find or read from file '" + fileName + "'.", ex);
} finally {
if (fStream != null) {
try {
fStream.close();
} catch (IOException ex) {
s_log.debug("unimportant", ex);
}
}
}
return success;
}
@Override
public void starting() {
s_log.info("starting...");
}
@Override
public void started() {
// As DateFormats are generally not-thread save,
// we always create a new one.
DateFormat dateTimeFormat = new SimpleDateFormat("yyyy.MM.dd 'at' hh:mm:ss z");
s_log.info(new StringBuilder("TASServer ")
.append(Misc.getAppVersion()).append(" started on ")
.append(dateTimeFormat.format(new Date())).toString());
createAdminIfNoUsers();
}
@Override
public void stopping() {
s_log.info("stopping...");
}
@Override
public void stopped() {
// As DateFormats are generally not-thread save,
// we always create a new one.
DateFormat dateTimeFormat = new SimpleDateFormat("yyyy.MM.dd 'at' hh:mm:ss z");
running = false;
s_log.info("stopped on " + dateTimeFormat.format(new Date()));
}
private boolean startServer() {
context.starting();
int port = context.getServer().getPort();
try {
context.getServer().setCharset("ISO-8859-1"); // initializes asciiDecoder and asciiEncoder
// open a non-blocking server socket channel
sSockChan = ServerSocketChannel.open();
sSockChan.configureBlocking(false);
// bind to localhost on designated port
//***InetAddress addr = InetAddress.getLocalHost();
//***sSockChan.socket().bind(new InetSocketAddress(addr, port));
sSockChan.socket().bind(new InetSocketAddress(port));
// get a selector for multiplexing the client channels
readSelector = Selector.open();
} catch (IOException e) {
s_log.error(new StringBuilder("Could not listen on port: ").append(port).toString(), e);
return false;
}
s_log.info(new StringBuilder("Listening for connections on TCP port ")
.append(port)
.append(" ...").toString());
context.started();
return true;
}
private void acceptNewConnections() {
try {
SocketChannel clientChannel;
// since sSockChan is non-blocking, this will return immediately
// regardless of whether there is a connection available
while ((clientChannel = sSockChan.accept()) != null) {
if (context.getServer().isRedirectActive()) {
if (s_log.isDebugEnabled()) {
s_log.debug(new StringBuilder("Client redirected to ")
.append(context.getServer().getRedirectAddress().getHostAddress()).append(": ")
.append(clientChannel.socket().getInetAddress().getHostAddress()).toString());
}
redirectAndKill(clientChannel.socket());
continue;
}
Client client = context.getClients().addNewClient(clientChannel, readSelector, SEND_BUFFER_SIZE);
if (client == null) {
continue;
}
// from this point on, we know that client has been successfully connected
client.sendWelcomeMessage();
if (s_log.isDebugEnabled()) {
s_log.debug(new StringBuilder("New client connected: ").append(client.getIp()).toString());
}
}
} catch (IOException ioe) {
s_log.error(new StringBuilder("Error during accept(): ").append(ioe.toString()).toString(), ioe);
} catch (Exception e) {
s_log.error(new StringBuilder("Exception in acceptNewConnections()").append(e.toString()).toString(), e);
}
}
private void readIncomingMessages() {
Client client = null;
try {
// non-blocking select, returns immediately regardless of how many keys are ready
readSelector.selectNow();
// fetch the keys
Set<SelectionKey> readyKeys = readSelector.selectedKeys();
// run through the keys and process each one
while (!readyKeys.isEmpty()) {
SelectionKey key = readyKeys.iterator().next();
readyKeys.remove(key);
SocketChannel channel = (SocketChannel) key.channel();
client = (Client) key.attachment();
if (client.isHalfDead()) {
continue;
}
readBuffer.clear();
client.setTimeOfLastReceive(System.currentTimeMillis());
// read from the channel into our buffer
long nbytes = channel.read(readBuffer);
client.addToDataOverLastTimePeriod(nbytes);
// basic anti-flood protection:
if (context.getServer().getFloodProtection().isFlooding(client)) {
s_log.warn(new StringBuilder("Flooding detected from ")
.append(client.getIp()).append(" (")
.append(client.getAccount().getName()).append(")").toString());
context.getClients().sendToAllAdministrators(new StringBuilder("SERVERMSG [broadcast to all admins]: Flooding has been detected from ")
.append(client.getIp()).append(" (")
.append(client.getAccount().getName()).append("). User has been kicked.").toString());
context.getClients().killClient(client, "Disconnected due to excessive flooding");
// add server notification:
ServerNotification sn = new ServerNotification("Flooding detected");
sn.addLine(new StringBuilder("Flooding detected from ")
.append(client.getIp()).append(" (")
.append(client.getAccount().getName()).append(").").toString());
sn.addLine("User has been kicked from the server.");
context.getServerNotifications().addNotification(sn);
continue;
}
// check for end-of-stream
if (nbytes == -1) {
if (s_log.isDebugEnabled()) {
s_log.debug("Socket disconnected - killing client");
}
channel.close();
context.getClients().killClient(client); // will also close the socket channel
} else {
// use a CharsetDecoder to turn those bytes into a string
// and append to client's StringBuilder
readBuffer.flip();
String str = context.getServer().getAsciiDecoder().decode(readBuffer).toString();
readBuffer.clear();
client.getRecvBuf().append(str);
// check for a full line
String line = client.getRecvBuf().toString();
while ((line.indexOf('\n') != -1) || (line.indexOf('\r') != -1)) {
int pos = line.indexOf('\r');
int npos = line.indexOf('\n');
if (pos == -1 || ((npos != -1) && (npos < pos))) {
pos = npos;
}
String command = line.substring(0, pos);
while (pos + 1 < line.length() && (line.charAt(pos + 1) == '\r' || line.charAt(pos + 1) == '\n')) {
++pos;
}
client.getRecvBuf().delete(0, pos + 1);
long time = System.currentTimeMillis();
tryToExecCommand(command, client);
time = System.currentTimeMillis() - time;
if (time > 200) {
context.getClients().sendToAllAdministrators(new StringBuilder("SERVERMSG [broadcast to all admins]: (DEBUG) User <")
.append(client.getAccount().getName()).append("> caused ")
.append(time).append(" ms load on the server. Command issued: ")
.append(command).toString());
}
if (!client.isAlive()) {
break; // in case client was killed within tryToExecCommand() method
}
line = client.getRecvBuf().toString();
}
}
}
} catch (IOException ioe) {
s_log.info("exception during select(): possibly due to force disconnect. Killing the client ...");
try {
if (client != null) {
context.getClients().killClient(client, "Quit: connection lost");
}
} catch (Exception e) {
// do nothing
}
s_log.debug("... the exception was:", ioe);
} catch (Exception e) {
s_log.info("exception in readIncomingMessages(): killing the client ... ", e);
try {
if (client != null) {
context.getClients().killClient(client, "Quit: connection lost");
}
} catch (Exception ex) {
// do nothing
}
s_log.debug("... the exception was:", e);
}
}
public boolean redirectAndKill(Socket socket) {
if (!context.getServer().isRedirectActive()) {
return false;
}
try {
(new PrintWriter(socket.getOutputStream(), true)).println("REDIRECT " + context.getServer().getRedirectAddress().getHostAddress());
socket.close();
} catch (Exception e) {
return false;
}
return true;
}
/* Note: this method is not synchronized!
* Note2: this method may be called recursively! */
public boolean tryToExecCommand(String command, Client client) {
command = command.trim();
if (command.equals("")) {
return false;
}
if (s_log.isDebugEnabled()) {
if (client.getAccount().getAccess() != Account.Access.NONE) {
s_log.debug(new StringBuilder("[<-")
.append(client.getAccount().getName()).append("] \"")
.append(command).append("\"").toString());
} else {
s_log.debug(new StringBuilder("[<-")
.append(client.getIp()).append("] \"")
.append(command).append("\"").toString());
}
}
int msgId = Client.NO_MSG_ID;
if (command.charAt(0) == '#') {
try {
if (!command.matches("^#\\d+\\s[\\s\\S]*")) {
return false; // malformed command
}
msgId = Integer.parseInt(command.substring(1).split("\\s")[0]);
// remove id field from the rest of command:
command = command.replaceFirst("#\\d+\\s", "");
} catch (NumberFormatException e) {
return false; // this means that the command is malformed
} catch (PatternSyntaxException e) {
return false; // this means that the command is malformed
}
}
// parse command into tokens:
String[] commands = command.split(" ");
commands[0] = commands[0].toUpperCase();
client.setSendMsgId(msgId);
try {
CommandProcessor cp = commandProcessors.get(commands[0]);
if (cp != null) {
List<String> args = new ArrayList<String>(Arrays.asList(commands));
args.remove(0);
try {
boolean ret = cp.process(client, args);
if (!ret) {
return false;
}
} catch (CommandProcessingException ex) {
s_log.debug(cp.getClass().getCanonicalName() +
" failed to handle command from client: \"" +
Misc.makeSentence(commands) + "\"", ex);
return false;
}
} else if (commands[0].equals("WHITELIST")) {
if (client.getAccount().getAccess().compareTo(Account.Access.ADMIN) < 0) {
return false;
}
// if (commands.length == 2) {
// whiteList.add(commands[1]);
// client.sendLine("SERVERMSG IP successfully whitelisted from REGISTER constraints");
// } else {
// client.sendLine(new StringBuilder("SERVERMSG Whitelist is: ").append(whiteList.toString()).toString());
// }
client.sendLine("SERVERMSG IP white-listing is disabled");
} else if (commands[0].equals("UNWHITELIST")) {
if (client.getAccount().getAccess().compareTo(Account.Access.ADMIN) < 0) {
return false;
}
// if (commands.length == 2) {
// client.sendLine((whiteList.remove(commands[1])) ? "SERVERMSG IP removed from whitelist" : "SERVERMSG IP not in whitelist");
// } else {
// client.sendLine("SERVERMSG Bad command- UNWHITELIST IP");
// }
client.sendLine("SERVERMSG IP white-listing is disabled");
} else if (commands[0].equals("STOPSERVER")) {
// stop server gracefully:
if (client.getAccount().getAccess().compareTo(Account.Access.ADMIN) < 0) {
return false;
}
running = false;
} else if (commands[0].equals("FORGEREVERSEMSG")) {
/* this command is used only for debugging purposes. It forces server to process
* string passed to this command as if it were sent by the user specified
* in this command. */
if (client.getAccount().getAccess().compareTo(Account.Access.ADMIN) < 0) {
return false;
}
if (commands.length < 3) {
return false;
}
Client targetClient = context.getClients().getClient(commands[1]);
if (targetClient == null) {
return false;
}
tryToExecCommand(Misc.makeSentence(commands, 2), targetClient);
} else if (commands[0].equals("RETRIEVELATESTBANLIST")) {
if (client.getAccount().getAccess().compareTo(Account.Access.ADMIN) < 0) {
return false;
}
client.sendLine("SERVERMSG Fetching ban entries is not needed anymore. Therefore, this is a no-op now.");
} else if (commands[0].equals("RELOADUPDATEPROPERTIES")) {
if (client.getAccount().getAccess().compareTo(Account.Access.ADMIN) < 0) {
return false;
}
if (readUpdateProperties(UPDATE_PROPERTIES_FILENAME)) {
s_log.info("\"Update properties\" read from " + UPDATE_PROPERTIES_FILENAME);
client.sendLine("SERVERMSG \"Update properties\" have been successfully loaded from " + UPDATE_PROPERTIES_FILENAME);
} else {
client.sendLine(new StringBuilder("SERVERMSG Unable to load \"Update properties\" from ")
.append(UPDATE_PROPERTIES_FILENAME).append("!").toString());
}
} else if (commands[0].equals("OUTPUTDBDRIVERSTATUS")) {
if (client.getAccount().getAccess().compareTo(Account.Access.ADMIN) < 0) {
return false;
}
client.sendLine("SERVERMSG This command is not supported anymore, as JPA is used for DB access for bans. Therefore, this is a no-op now.");
} else if (commands[0].equals("CHANNELS")) {
if (client.getAccount().getAccess().compareTo(Account.Access.NORMAL) < 0) {
return false;
}
context.getChannels().sendChannelListToClient(client);
} else if (commands[0].equals("REQUESTUPDATEFILE")) {
//***if (client.account.getAccess() > Account.Access.NONE) return false;
if (commands.length < 2) {
return false;
}
String version = Misc.makeSentence(commands, 1);
String response = updateProperties.getProperty(version);
if (response == null) {
response = updateProperties.getProperty("default"); // use general response ("default"), if it exists.
} // if still no response has been found, use some default response:
if (response == null) {
response = "SERVERMSGBOX No update available. Please download the latest version of the software from official Spring web site: http://spring.clan-sy.com";
}
// send a response to the client:
client.sendLine(response);
// kill client if no update has been found for him:
if (response.substring(0, 12).toUpperCase().equals("SERVERMSGBOX")) {
context.getClients().killClient(client);
}
} else if (commands[0].equals("KICKFROMBATTLE")) {
if (commands.length != 2) {
return false;
}
if (client.getAccount().getAccess().compareTo(Account.Access.NORMAL) < 0) {
return false;
}
if (client.getBattleID() == Battle.NO_BATTLE_ID) {
return false;
}
Battle bat = context.getBattles().getBattleByID(client.getBattleID());
if (bat == null) {
return false;
}
if (bat.getFounder() != client) {
return false; // only founder can kick other clients
}
Client target = context.getClients().getClient(commands[1]);
if (target == null) {
return false;
}
if (!bat.isClientInBattle(target)) {
return false;
}
bat.sendToAllClients(new StringBuilder("SAIDBATTLEEX ")
.append(client.getAccount().getName()).append(" kicked ")
.append(target.getAccount().getName()).append(" from battle").toString());
// notify client that he was kicked from the battle:
target.sendLine("FORCEQUITBATTLE");
// force client to leave battle:
tryToExecCommand("LEAVEBATTLE", target);
} else if (commands[0].equals("SCRIPTSTART")) {
if (commands.length != 1) {
return false;
}
if (client.getAccount().getAccess().compareTo(Account.Access.NORMAL) < 0) {
return false;
}
if (client.getBattleID() == Battle.NO_BATTLE_ID) {
return false;
}
Battle bat = context.getBattles().getBattleByID(client.getBattleID());
context.getBattles().verify(bat);
bat.getTempReplayScript().clear();
} else if (commands[0].equals("SCRIPT")) {
if (client.getAccount().getAccess().compareTo(Account.Access.NORMAL) < 0) {
return false;
}
if (client.getBattleID() == Battle.NO_BATTLE_ID) {
return false;
}
Battle bat = context.getBattles().getBattleByID(client.getBattleID());
context.getBattles().verify(bat);
bat.getTempReplayScript().add(Misc.makeSentence(commands, 1));
} else if (commands[0].equals("SCRIPTEND")) {
if (client.getAccount().getAccess().compareTo(Account.Access.NORMAL) < 0) {
return false;
}
if (client.getBattleID() == Battle.NO_BATTLE_ID) {
return false;
}
Battle bat = context.getBattles().getBattleByID(client.getBattleID());
context.getBattles().verify(bat);
// copy temp script to active script:
bat.ratifyTempScript();
bat.sendScriptToAllExceptFounder();
} else if (commands[0].equals("SETSCRIPTTAGS")) {
if (client.getAccount().getAccess().compareTo(Account.Access.NORMAL) < 0) {
return false;
}
if (client.getBattleID() == Battle.NO_BATTLE_ID) {
return false;
}
Battle bat = context.getBattles().getBattleByID(client.getBattleID());
context.getBattles().verify(bat);
if (bat.getFounder() != client) {
return false;
}
if (commands.length < 2) {
// kill client since it is not using this command correctly
client.sendLine(new StringBuilder("SERVERMSG Serious error: inconsistent data (")
.append(commands[0]).append(" command). You will now be disconnected ...").toString());
context.getClients().killClient(client, "Quit: inconsistent data");
return false;
}
int pairsStart = command.indexOf(' ');
if (pairsStart < 0) {
return false;
}
String[] pairs = command.substring(pairsStart + 1).split("\t");
StringBuilder validPairs = new StringBuilder();
for (int i = 0; i < pairs.length; i++) {
String s = pairs[i];
int equalPos = s.indexOf('=');
if (equalPos < 1) {
continue;
}
// parse the key
String key = s.substring(0, equalPos).toLowerCase();
if (key.length() <= 0) {
continue;
}
if (key.indexOf(' ') >= 0) {
continue;
}
if (key.indexOf('=') >= 0) {
continue;
}
if (key.indexOf(';') >= 0) {
continue;
}
if (key.indexOf('{') >= 0) {
continue;
}
if (key.indexOf('}') >= 0) {
continue;
}
if (key.indexOf('[') >= 0) {
continue;
}
if (key.indexOf(']') >= 0) {
continue;
}
if (key.indexOf('\n') >= 0) {
continue;
}
if (key.indexOf('\r') >= 0) {
continue;
}
// parse the value
String value = s.substring(equalPos + 1);
if (value.equals(value.trim())) {
continue;
} // forbid trailing/leading spaces
if (value.indexOf(';') >= 0) {
continue;
}
if (value.indexOf('}') >= 0) {
continue;
}
if (value.indexOf('[') >= 0) {
continue;
}
if (value.indexOf('\n') >= 0) {
continue;
}
if (value.indexOf('\r') >= 0) {
continue;
}
// insert the tag data into the map
bat.getScriptTags().put(key, value);
// add to the validPairs string
if (validPairs.length() > 0) {
validPairs.append("\t");
}
validPairs.append(key).append("=").append(value);
}
// relay the valid pairs
if (validPairs.length() > 0) {
bat.sendToAllClients(new StringBuilder("SETSCRIPTTAGS ").append(validPairs).toString());
}
} else if (commands[0].equals("REMOVESCRIPTTAGS")) {
if (client.getAccount().getAccess().compareTo(Account.Access.NORMAL) < 0) {
return false;
}
if (client.getBattleID() == Battle.NO_BATTLE_ID) {
return false;
}
Battle bat = context.getBattles().getBattleByID(client.getBattleID());
context.getBattles().verify(bat);
if (bat.getFounder() != client) {
return false;
}
if (commands.length < 2) {
// kill client since it is not using this command correctly
client.sendLine(new StringBuilder("SERVERMSG Serious error: inconsistent data (")
.append(commands[0]).append(" command). You will now be disconnected ...").toString());
context.getClients().killClient(client, "Quit: inconsistent data");
return false;
}
StringBuilder loweyKeyCommand = new StringBuilder("REMOVESCRIPTTAGS");
for (int i = 1; i < commands.length; i++) {
String lowerKey = commands[i].toLowerCase();
loweyKeyCommand.append(" ").append(lowerKey);
bat.getScriptTags().remove(lowerKey);
}
// relay the command
bat.sendToAllClients(loweyKeyCommand.toString());
} else {
// unknown command!
return false;
}
} finally {
client.setSendMsgId(Client.NO_MSG_ID);
}
return true;
} // tryToExecCommand()
/**
* Adds a default administrator account, if not running in LAN mode,
* and if there are no accounts in the active accounts service.
*/
private void createAdminIfNoUsers() {
if (!context.getServer().isLanMode()) {
AccountsService accountsService = context.getAccountsService();
if (accountsService.getAccountsSize() == 0) {
String username = "admin";
String password = "admin";
s_log.info("As there are no accounts yet, we are creating an admin account: username=\"" + username + "\", password=\"" + password + "\"");
Account admin = createAdmin(username, password);
accountsService.addAccount(admin);
accountsService.saveAccountsIfNeeded();
}
}
}
/**
* Creates a simple account with administrator rights.
*/
private static Account createAdmin(String username, String password) {
Account admin = new Account(username, Misc.encodePassword(password), Account.NO_ACCOUNT_LAST_IP, Account.NO_ACCOUNT_LAST_COUNTRY);
admin.setAccess(Account.Access.ADMIN);
return admin;
}
public TASServer(Context context) {
this.context = context;
this.commandProcessors = new CommandProcessors();
context.addLiveStateListener(this);
context.addContextReceiver(commandProcessors);
AccountsService accountsService = null;
if (!context.getServer().isLanMode() && context.getServer().isUseUserDB()) {
accountsService = new JPAAccountsService();
} else {
accountsService = new FSAccountsService();
}
context.setAccountsService(accountsService);
BanService banService = null;
if (!context.getServer().isLanMode()) {
try {
banService = new JPABanService();
} catch (Exception pex) {
banService = new DummyBanService();
s_log.warn("Failed to access database for ban entries, bans are not supported!", pex);
}
} else {
banService = new DummyBanService();
}
context.setBanService(banService);
context.push();
commandProcessors.init();
// switch to LAN mode if user accounts information is not present:
if (!context.getServer().isLanMode()) {
if (!context.getAccountsService().isReadyToOperate()) {
s_log.warn("Accounts service not ready, switching to \"LAN mode\" ...");
context.getServer().setLanMode(true);
}
}
if (!context.getServer().isLanMode()) {
context.getAccountsService().loadAccounts();
context.getBanService();
context.getAgreement().read();
} else {
s_log.info("LAN mode enabled");
}
context.getMessageOfTheDay().read();
context.getServer().setStartTime(System.currentTimeMillis());
if (readUpdateProperties(UPDATE_PROPERTIES_FILENAME)) {
s_log.info(new StringBuilder("\"Update properties\" read from ").append(UPDATE_PROPERTIES_FILENAME).toString());
}
long tempTime = System.currentTimeMillis();
if (IP2Country.getInstance().initializeAll()) {
tempTime = System.currentTimeMillis() - tempTime;
s_log.info(new StringBuilder("<IP2Country> loaded in ")
.append(tempTime).append(" ms.").toString());
}
// start "help UDP" server:
context.getNatHelpServer().startServer();
// start server:
if (!startServer()) {
context.getServer().closeServerAndExit();
}
// add server notification:
ServerNotification sn = new ServerNotification("Server started");
sn.addLine(new StringBuilder("Server has been started on port ")
.append(context.getServer().getPort()).append(". There are ")
.append(context.getAccountsService().getAccountsSize())
.append(" accounts currently loaded. See server log for more info.").toString());
context.getServerNotifications().addNotification(sn);
running = true;
while (running) { // main loop
// check for new client connections
acceptNewConnections();
// check for incoming messages
readIncomingMessages();
// flush any data that is waiting to be sent
context.getClients().flushData();
// reset received bytes count every n seconds
if (context.getServer().getFloodProtection().hasFloodCheckPeriodPassed()) {
for (int i = 0; i < context.getClients().getClientsSize(); i++) {
context.getClients().getClient(i).setDataOverLastTimePeriod(0);
}
}
// check for timeouts:
Collection<Client> timedOutClients = context.getServer().getTimedOutClients();
for (Client client : timedOutClients) {
if (client.isHalfDead()) {
continue; // already scheduled for kill
}
s_log.warn(new StringBuilder("Timeout detected from ")
.append(client.getAccount().getName()).append(" (")
.append(client.getIp()).append("). Client has been scheduled for kill ...").toString());
context.getClients().killClientDelayed(client, "Quit: timeout");
}
// kill all clients scheduled to be killed:
context.getClients().processKillList();
context.getStatistics().update();
// check UDP server for any new packets:
DatagramPacket packet;
while ((packet = context.getNatHelpServer().fetchNextPackage()) != null) {
InetAddress address = packet.getAddress();
int p = packet.getPort();
String data = new String(packet.getData(), packet.getOffset(), packet.getLength());
if (s_log.isDebugEnabled()) {
s_log.debug(new StringBuilder("*** UDP packet received from ")
.append(address.getHostAddress()).append(" from port ")
.append(p).toString());
}
Client client = context.getClients().getClient(data);
if (client == null) {
continue;
}
client.setUdpSourcePort(p);
client.sendLine(new StringBuilder("UDPSOURCEPORT ").append(p).toString());
}
// save accounts info to disk on regular intervals:
context.getAccountsService().saveAccountsIfNeeded();
// purge mute lists of all channels on regular intervals:
if (System.currentTimeMillis() - lastMutesPurgeTime > purgeMutesInterval) {
lastMutesPurgeTime = System.currentTimeMillis();
for (int i = 0; i < context.getChannels().getChannelsSize(); i++) {
context.getChannels().getChannel(i).getMuteList().clearExpiredOnes();
}
}
// sleep a bit
try {
Thread.sleep(MAIN_LOOP_SLEEP);
} catch (InterruptedException ie) {
}
}
// close everything:
if (!context.getServer().isLanMode()) {
context.getAccountsService().saveAccounts(true);
}
if (context.getNatHelpServer().isRunning()) {
context.getNatHelpServer().stopServer();
}
// add server notification:
sn = new ServerNotification("Server stopped");
sn.addLine("Server has just been stopped gracefully. See server log for more info.");
context.getServerNotifications().addNotification(sn);
s_log.info("Server closed gracefully!");
}
}