forked from CloudburstMC/Nukkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.java
2427 lines (1963 loc) · 85.2 KB
/
Server.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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cn.nukkit;
import cn.nukkit.block.Block;
import cn.nukkit.blockentity.*;
import cn.nukkit.command.*;
import cn.nukkit.console.NukkitConsole;
import cn.nukkit.entity.Attribute;
import cn.nukkit.entity.Entity;
import cn.nukkit.entity.EntityHuman;
import cn.nukkit.entity.data.Skin;
import cn.nukkit.entity.item.*;
import cn.nukkit.entity.mob.*;
import cn.nukkit.entity.passive.*;
import cn.nukkit.entity.projectile.*;
import cn.nukkit.entity.weather.EntityLightning;
import cn.nukkit.event.HandlerList;
import cn.nukkit.event.level.LevelInitEvent;
import cn.nukkit.event.level.LevelLoadEvent;
import cn.nukkit.event.server.BatchPacketsEvent;
import cn.nukkit.event.server.PlayerDataSerializeEvent;
import cn.nukkit.event.server.QueryRegenerateEvent;
import cn.nukkit.event.server.ServerStopEvent;
import cn.nukkit.inventory.CraftingManager;
import cn.nukkit.inventory.Recipe;
import cn.nukkit.item.Item;
import cn.nukkit.item.RuntimeItems;
import cn.nukkit.item.enchantment.Enchantment;
import cn.nukkit.lang.BaseLang;
import cn.nukkit.lang.TextContainer;
import cn.nukkit.lang.TranslationContainer;
import cn.nukkit.level.EnumLevel;
import cn.nukkit.level.GlobalBlockPalette;
import cn.nukkit.level.Level;
import cn.nukkit.level.Position;
import cn.nukkit.level.biome.EnumBiome;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.level.format.LevelProviderManager;
import cn.nukkit.level.format.anvil.Anvil;
import cn.nukkit.level.format.leveldb.LevelDB;
import cn.nukkit.level.format.mcregion.McRegion;
import cn.nukkit.level.generator.Flat;
import cn.nukkit.level.generator.Generator;
import cn.nukkit.level.generator.Nether;
import cn.nukkit.level.generator.Normal;
import cn.nukkit.math.NukkitMath;
import cn.nukkit.metadata.EntityMetadataStore;
import cn.nukkit.metadata.LevelMetadataStore;
import cn.nukkit.metadata.PlayerMetadataStore;
import cn.nukkit.metrics.NukkitMetrics;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.DoubleTag;
import cn.nukkit.nbt.tag.FloatTag;
import cn.nukkit.nbt.tag.ListTag;
import cn.nukkit.network.CompressBatchedTask;
import cn.nukkit.network.Network;
import cn.nukkit.network.RakNetInterface;
import cn.nukkit.network.SourceInterface;
import cn.nukkit.network.protocol.BatchPacket;
import cn.nukkit.network.protocol.DataPacket;
import cn.nukkit.network.protocol.PlayerListPacket;
import cn.nukkit.network.protocol.ProtocolInfo;
import cn.nukkit.network.query.QueryHandler;
import cn.nukkit.network.rcon.RCON;
import cn.nukkit.permission.BanEntry;
import cn.nukkit.permission.BanList;
import cn.nukkit.permission.DefaultPermissions;
import cn.nukkit.permission.Permissible;
import cn.nukkit.plugin.JavaPluginLoader;
import cn.nukkit.plugin.Plugin;
import cn.nukkit.plugin.PluginLoadOrder;
import cn.nukkit.plugin.PluginManager;
import cn.nukkit.plugin.service.NKServiceManager;
import cn.nukkit.plugin.service.ServiceManager;
import cn.nukkit.potion.Effect;
import cn.nukkit.potion.Potion;
import cn.nukkit.resourcepacks.ResourcePackManager;
import cn.nukkit.scheduler.ServerScheduler;
import cn.nukkit.scheduler.Task;
import cn.nukkit.spark.SparkInstaller;
import cn.nukkit.utils.*;
import cn.nukkit.utils.bugreport.ExceptionHandler;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import io.netty.buffer.ByteBuf;
import lombok.extern.log4j.Log4j2;
import org.iq80.leveldb.CompressionType;
import org.iq80.leveldb.DB;
import org.iq80.leveldb.Options;
import org.iq80.leveldb.impl.Iq80DBFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
/**
* @author MagicDroidX
* @author Box
*/
@Log4j2
public class Server {
public static final String BROADCAST_CHANNEL_ADMINISTRATIVE = "nukkit.broadcast.admin";
public static final String BROADCAST_CHANNEL_USERS = "nukkit.broadcast.user";
private static Server instance = null;
private BanList banByName;
private BanList banByIP;
private Config operators;
private Config whitelist;
private AtomicBoolean isRunning = new AtomicBoolean(true);
private boolean hasStopped = false;
private PluginManager pluginManager;
private int profilingTickrate = 20;
private ServerScheduler scheduler;
private int tickCounter;
private long nextTick;
private final float[] tickAverage = {20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20};
private final float[] useAverage = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
private float maxTick = 20;
private float maxUse = 0;
private int sendUsageTicker = 0;
private boolean dispatchSignals = false;
private final NukkitConsole console;
private final ConsoleThread consoleThread;
private SimpleCommandMap commandMap;
private CraftingManager craftingManager;
private ResourcePackManager resourcePackManager;
private ConsoleCommandSender consoleSender;
private int maxPlayers;
private boolean autoSave = true;
private RCON rcon;
private EntityMetadataStore entityMetadata;
private PlayerMetadataStore playerMetadata;
private LevelMetadataStore levelMetadata;
private Network network;
private boolean networkCompressionAsync = true;
public int networkCompressionLevel = 7;
private int networkZlibProvider = 0;
private boolean autoTickRate = true;
private int autoTickRateLimit = 20;
private boolean alwaysTickPlayers = false;
private int baseTickRate = 1;
private Boolean getAllowFlight = null;
private int difficulty = Integer.MAX_VALUE;
private int defaultGamemode = Integer.MAX_VALUE;
private int autoSaveTicker = 0;
private int autoSaveTicks = 6000;
private BaseLang baseLang;
private boolean forceLanguage = false;
private UUID serverID;
private final String filePath;
private final String dataPath;
private final String pluginPath;
private final Set<UUID> uniquePlayers = new HashSet<>();
private QueryHandler queryHandler;
private QueryRegenerateEvent queryRegenerateEvent;
private Config properties;
private Config config;
private final Map<InetSocketAddress, Player> players = new HashMap<>();
private final Map<UUID, Player> playerList = new HashMap<>();
private final Map<Integer, Level> levels = new HashMap<Integer, Level>() {
public Level put(Integer key, Level value) {
Level result = super.put(key, value);
levelArray = levels.values().toArray(new Level[0]);
return result;
}
public boolean remove(Object key, Object value) {
boolean result = super.remove(key, value);
levelArray = levels.values().toArray(new Level[0]);
return result;
}
public Level remove(Object key) {
Level result = super.remove(key);
levelArray = levels.values().toArray(new Level[0]);
return result;
}
};
private Level[] levelArray = new Level[0];
private final ServiceManager serviceManager = new NKServiceManager();
private Level defaultLevel = null;
private boolean allowNether;
private final Thread currentThread;
private Watchdog watchdog;
private DB nameLookup;
private PlayerDataSerializer playerDataSerializer;
private final Set<String> ignoredPackets = new HashSet<>();
Server(final String filePath, String dataPath, String pluginPath, String predefinedLanguage) {
Preconditions.checkState(instance == null, "Already initialized!");
currentThread = Thread.currentThread(); // Saves the current thread instance as a reference, used in Server#isPrimaryThread()
instance = this;
this.filePath = filePath;
if (!new File(dataPath + "worlds/").exists()) {
new File(dataPath + "worlds/").mkdirs();
}
if (!new File(dataPath + "players/").exists()) {
new File(dataPath + "players/").mkdirs();
}
if (!new File(pluginPath).exists()) {
new File(pluginPath).mkdirs();
}
this.dataPath = new File(dataPath).getAbsolutePath() + "/";
this.pluginPath = new File(pluginPath).getAbsolutePath() + "/";
this.console = new NukkitConsole(this);
this.consoleThread = new ConsoleThread();
this.consoleThread.start();
this.playerDataSerializer = new DefaultPlayerDataSerializer(this);
//todo: VersionString 现在不必要
if (!new File(this.dataPath + "nukkit.yml").exists()) {
this.getLogger().info(TextFormat.GREEN + "Welcome! Please choose a language first!");
try {
InputStream languageList = this.getClass().getClassLoader().getResourceAsStream("lang/language.list");
if (languageList == null) {
throw new IllegalStateException("lang/language.list is missing. If you are running a development version, make sure you have run 'git submodule update --init'.");
}
String[] lines = Utils.readFile(languageList).split("\n");
for (String line : lines) {
this.getLogger().info(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
String fallback = BaseLang.FALLBACK_LANGUAGE;
String language = null;
while (language == null) {
String lang;
if (predefinedLanguage != null) {
log.info("Trying to load language from predefined language: " + predefinedLanguage);
lang = predefinedLanguage;
} else {
lang = this.console.readLine();
}
InputStream conf = this.getClass().getClassLoader().getResourceAsStream("lang/" + lang + "/lang.ini");
if (conf != null) {
language = lang;
} else if(predefinedLanguage != null) {
log.warn("No language found for predefined language: " + predefinedLanguage + ", please choose a valid language");
predefinedLanguage = null;
}
}
InputStream advacedConf = this.getClass().getClassLoader().getResourceAsStream("lang/" + language + "/nukkit.yml");
if (advacedConf == null) {
advacedConf = this.getClass().getClassLoader().getResourceAsStream("lang/" + fallback + "/nukkit.yml");
}
try {
Utils.writeFile(this.dataPath + "nukkit.yml", advacedConf);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
this.console.setExecutingCommands(true);
log.info("Loading {} ...", TextFormat.GREEN + "nukkit.yml" + TextFormat.WHITE);
this.config = new Config(this.dataPath + "nukkit.yml", Config.YAML);
Nukkit.DEBUG = NukkitMath.clamp(this.getConfig("debug.level", 1), 1, 3);
int logLevel = (Nukkit.DEBUG + 3) * 100;
org.apache.logging.log4j.Level currentLevel = Nukkit.getLogLevel();
for (org.apache.logging.log4j.Level level : org.apache.logging.log4j.Level.values()) {
if (level.intLevel() == logLevel && level.intLevel() > currentLevel.intLevel()) {
Nukkit.setLogLevel(level);
break;
}
}
ignoredPackets.addAll(getConfig().getStringList("debug.ignored-packets"));
ignoredPackets.add("BatchPacket");
log.info("Loading {} ...", TextFormat.GREEN + "server.properties" + TextFormat.WHITE);
this.properties = new Config(this.dataPath + "server.properties", Config.PROPERTIES, new ConfigSection() {
{
put("motd", "A Nukkit Powered Server");
put("sub-motd", "https://nukkitx.com");
put("server-port", 19132);
put("server-ip", "0.0.0.0");
put("view-distance", 10);
put("white-list", false);
put("achievements", true);
put("announce-player-achievements", true);
put("spawn-protection", 16);
put("max-players", 20);
put("allow-flight", false);
put("spawn-animals", true);
put("spawn-mobs", true);
put("gamemode", 0);
put("force-gamemode", false);
put("hardcore", false);
put("pvp", true);
put("difficulty", 1);
put("generator-settings", "");
put("level-name", "world");
put("level-seed", "");
put("level-type", "DEFAULT");
put("allow-nether", true);
put("enable-query", true);
put("enable-rcon", false);
put("rcon.password", Base64.getEncoder().encodeToString(UUID.randomUUID().toString().replace("-", "").getBytes()).substring(3, 13));
put("auto-save", true);
put("force-resources", false);
put("xbox-auth", true);
}
});
// Allow Nether? (determines if we create a nether world if one doesn't exist on startup)
this.allowNether = this.properties.getBoolean("allow-nether", true);
this.forceLanguage = this.getConfig("settings.force-language", false);
this.baseLang = new BaseLang(this.getConfig("settings.language", BaseLang.FALLBACK_LANGUAGE));
log.info(this.getLanguage().translateString("language.selected", new String[]{getLanguage().getName(), getLanguage().getLang()}));
log.info(getLanguage().translateString("nukkit.server.start", TextFormat.AQUA + this.getVersion() + TextFormat.RESET));
Object poolSize = this.getConfig("settings.async-workers", (Object) "auto");
if (!(poolSize instanceof Integer)) {
try {
poolSize = Integer.valueOf((String) poolSize);
} catch (Exception e) {
poolSize = Math.max(Runtime.getRuntime().availableProcessors() + 1, 4);
}
}
ServerScheduler.WORKERS = (int) poolSize;
this.networkZlibProvider = this.getConfig("network.zlib-provider", 2);
Zlib.setProvider(this.networkZlibProvider);
this.networkCompressionLevel = this.getConfig("network.compression-level", 7);
this.networkCompressionAsync = this.getConfig("network.async-compression", true);
this.autoTickRate = this.getConfig("level-settings.auto-tick-rate", true);
this.autoTickRateLimit = this.getConfig("level-settings.auto-tick-rate-limit", 20);
this.alwaysTickPlayers = this.getConfig("level-settings.always-tick-players", false);
this.baseTickRate = this.getConfig("level-settings.base-tick-rate", 1);
this.scheduler = new ServerScheduler();
if (this.getPropertyBoolean("enable-rcon", false)) {
try {
this.rcon = new RCON(this, this.getPropertyString("rcon.password", ""), (!this.getIp().equals("")) ? this.getIp() : "0.0.0.0", this.getPropertyInt("rcon.port", this.getPort()));
} catch (IllegalArgumentException e) {
log.error(getLanguage().translateString(e.getMessage(), e.getCause().getMessage()));
}
}
this.entityMetadata = new EntityMetadataStore();
this.playerMetadata = new PlayerMetadataStore();
this.levelMetadata = new LevelMetadataStore();
this.operators = new Config(this.dataPath + "ops.txt", Config.ENUM);
this.whitelist = new Config(this.dataPath + "white-list.txt", Config.ENUM);
this.banByName = new BanList(this.dataPath + "banned-players.json");
this.banByName.load();
this.banByIP = new BanList(this.dataPath + "banned-ips.json");
this.banByIP.load();
this.maxPlayers = this.getPropertyInt("max-players", 20);
this.setAutoSave(this.getPropertyBoolean("auto-save", true));
if (this.getPropertyBoolean("hardcore", false) && this.getDifficulty() < 3) {
this.setPropertyInt("difficulty", 3);
}
boolean bugReport;
if (this.getConfig().exists("settings.bug-report")) {
bugReport = this.getConfig().getBoolean("settings.bug-report");
this.getProperties().remove("bug-report");
} else {
bugReport = this.getPropertyBoolean("bug-report", true); //backwards compat
}
if (bugReport) {
ExceptionHandler.registerExceptionHandler();
}
log.info(this.getLanguage().translateString("nukkit.server.networkStart", new String[]{this.getIp().equals("") ? "*" : this.getIp(), String.valueOf(this.getPort())}));
this.serverID = UUID.randomUUID();
this.network = new Network(this);
this.network.setName(this.getMotd());
this.network.setSubName(this.getSubMotd());
log.info(this.getLanguage().translateString("nukkit.server.info", this.getName(), TextFormat.YELLOW + this.getNukkitVersion() + TextFormat.WHITE, TextFormat.AQUA + this.getCodename() + TextFormat.WHITE, this.getApiVersion()));
log.info(this.getLanguage().translateString("nukkit.server.license", this.getName()));
this.consoleSender = new ConsoleCommandSender();
this.commandMap = new SimpleCommandMap(this);
// Initialize metrics
new NukkitMetrics(this);
this.registerEntities();
this.registerBlockEntities();
Block.init();
Enchantment.init();
RuntimeItems.init();
Item.init();
EnumBiome.values(); //load class, this also registers biomes
Effect.init();
Potion.init();
Attribute.init();
GlobalBlockPalette.getOrCreateRuntimeId(0, 0); //Force it to load
// Convert legacy data before plugins get the chance to mess with it.
try {
nameLookup = Iq80DBFactory.factory.open(new File(dataPath, "players"), new Options()
.createIfMissing(true)
.compressionType(CompressionType.ZLIB_RAW));
} catch (IOException e) {
throw new RuntimeException(e);
}
convertLegacyPlayerData();
this.craftingManager = new CraftingManager();
this.resourcePackManager = new ResourcePackManager(new File(Nukkit.DATA_PATH, "resource_packs"));
this.pluginManager = new PluginManager(this, this.commandMap);
this.pluginManager.subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this.consoleSender);
this.pluginManager.registerInterface(JavaPluginLoader.class);
this.queryRegenerateEvent = new QueryRegenerateEvent(this, 5);
this.network.registerInterface(new RakNetInterface(this));
this.pluginManager.loadPlugins(this.pluginPath);
SparkInstaller.initSpark(this);
this.enablePlugins(PluginLoadOrder.STARTUP);
LevelProviderManager.addProvider(this, Anvil.class);
LevelProviderManager.addProvider(this, McRegion.class);
LevelProviderManager.addProvider(this, LevelDB.class);
Generator.addGenerator(Flat.class, "flat", Generator.TYPE_FLAT);
Generator.addGenerator(Normal.class, "normal", Generator.TYPE_INFINITE);
Generator.addGenerator(Normal.class, "default", Generator.TYPE_INFINITE);
Generator.addGenerator(Nether.class, "nether", Generator.TYPE_NETHER);
//todo: add old generator and hell generator
for (String name : this.getConfig("worlds", new HashMap<String, Object>()).keySet()) {
if (!this.loadLevel(name)) {
long seed;
try {
seed = ((Integer) this.getConfig("worlds." + name + ".seed")).longValue();
} catch (Exception e) {
seed = System.currentTimeMillis();
}
Map<String, Object> options = new HashMap<>();
String[] opts = (this.getConfig("worlds." + name + ".generator", Generator.getGenerator("default").getSimpleName())).split(":");
Class<? extends Generator> generator = Generator.getGenerator(opts[0]);
if (opts.length > 1) {
StringBuilder preset = new StringBuilder();
for (int i = 1; i < opts.length; i++) {
preset.append(opts[i]).append(":");
}
preset = new StringBuilder(preset.substring(0, preset.length() - 1));
options.put("preset", preset.toString());
}
this.generateLevel(name, seed, generator, options);
}
}
if (this.getDefaultLevel() == null) {
String defaultName = this.getPropertyString("level-name", "world");
if (defaultName == null || defaultName.trim().isEmpty()) {
this.getLogger().warning("level-name cannot be null, using default");
defaultName = "world";
this.setPropertyString("level-name", defaultName);
}
if (!this.loadLevel(defaultName)) {
long seed;
String seedString = String.valueOf(this.getProperty("level-seed", System.currentTimeMillis()));
try {
seed = Long.parseLong(seedString);
} catch (NumberFormatException e) {
seed = seedString.hashCode();
}
this.generateLevel(defaultName, seed == 0 ? System.currentTimeMillis() : seed);
}
this.setDefaultLevel(this.getLevelByName(defaultName));
}
this.properties.save(true);
if (this.getDefaultLevel() == null) {
this.getLogger().emergency(this.getLanguage().translateString("nukkit.level.defaultError"));
this.forceShutdown();
return;
}
EnumLevel.initLevels();
if (this.getConfig("ticks-per.autosave", 6000) > 0) {
this.autoSaveTicks = this.getConfig("ticks-per.autosave", 6000);
}
this.enablePlugins(PluginLoadOrder.POSTWORLD);
if (Nukkit.DEBUG < 2) {
this.watchdog = new Watchdog(this, 60000);
this.watchdog.start();
}
this.start();
}
public int broadcastMessage(String message) {
return this.broadcast(message, BROADCAST_CHANNEL_USERS);
}
public int broadcastMessage(TextContainer message) {
return this.broadcast(message, BROADCAST_CHANNEL_USERS);
}
public int broadcastMessage(String message, CommandSender[] recipients) {
for (CommandSender recipient : recipients) {
recipient.sendMessage(message);
}
return recipients.length;
}
public int broadcastMessage(String message, Collection<? extends CommandSender> recipients) {
for (CommandSender recipient : recipients) {
recipient.sendMessage(message);
}
return recipients.size();
}
public int broadcastMessage(TextContainer message, Collection<? extends CommandSender> recipients) {
for (CommandSender recipient : recipients) {
recipient.sendMessage(message);
}
return recipients.size();
}
public int broadcast(String message, String permissions) {
Set<CommandSender> recipients = new HashSet<>();
for (String permission : permissions.split(";")) {
for (Permissible permissible : this.pluginManager.getPermissionSubscriptions(permission)) {
if (permissible instanceof CommandSender && permissible.hasPermission(permission)) {
recipients.add((CommandSender) permissible);
}
}
}
for (CommandSender recipient : recipients) {
recipient.sendMessage(message);
}
return recipients.size();
}
public int broadcast(TextContainer message, String permissions) {
Set<CommandSender> recipients = new HashSet<>();
for (String permission : permissions.split(";")) {
for (Permissible permissible : this.pluginManager.getPermissionSubscriptions(permission)) {
if (permissible instanceof CommandSender && permissible.hasPermission(permission)) {
recipients.add((CommandSender) permissible);
}
}
}
for (CommandSender recipient : recipients) {
recipient.sendMessage(message);
}
return recipients.size();
}
public static void broadcastPacket(Collection<Player> players, DataPacket packet) {
packet.tryEncode();
for (Player player : players) {
player.dataPacket(packet);
}
}
public static void broadcastPacket(Player[] players, DataPacket packet) {
packet.tryEncode();
for (Player player : players) {
player.dataPacket(packet);
}
}
@Deprecated
public void batchPackets(Player[] players, DataPacket[] packets) {
this.batchPackets(players, packets, false);
}
@Deprecated
public void batchPackets(Player[] players, DataPacket[] packets, boolean forceSync) {
if (players == null || packets == null || players.length == 0 || packets.length == 0) {
return;
}
BatchPacketsEvent ev = new BatchPacketsEvent(players, packets, forceSync);
getPluginManager().callEvent(ev);
if (ev.isCancelled()) {
return;
}
byte[][] payload = new byte[packets.length * 2][];
for (int i = 0; i < packets.length; i++) {
DataPacket p = packets[i];
int idx = i * 2;
p.tryEncode();
byte[] buf = p.getBuffer();
payload[idx] = Binary.writeUnsignedVarInt(buf.length);
payload[idx + 1] = buf;
packets[i] = null;
}
List<InetSocketAddress> targets = new ArrayList<>();
for (Player p : players) {
if (p.isConnected()) {
targets.add(p.getSocketAddress());
}
}
if (!forceSync && this.networkCompressionAsync) {
this.getScheduler().scheduleAsyncTask(new CompressBatchedTask(payload, targets, this.networkCompressionLevel));
} else {
try {
byte[] data = Binary.appendBytes(payload);
this.broadcastPacketsCallback(Network.deflateRaw(data, this.networkCompressionLevel), targets);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public void broadcastPacketsCallback(byte[] data, List<InetSocketAddress> targets) {
BatchPacket pk = new BatchPacket();
pk.payload = data;
for (InetSocketAddress i : targets) {
if (this.players.containsKey(i)) {
this.players.get(i).dataPacket(pk);
}
}
}
public void enablePlugins(PluginLoadOrder type) {
for (Plugin plugin : new ArrayList<>(this.pluginManager.getPlugins().values())) {
if (!plugin.isEnabled() && type == plugin.getDescription().getOrder()) {
this.enablePlugin(plugin);
}
}
if (type == PluginLoadOrder.POSTWORLD) {
this.commandMap.registerServerAliases();
DefaultPermissions.registerCorePermissions();
}
}
public void enablePlugin(Plugin plugin) {
this.pluginManager.enablePlugin(plugin);
}
public void disablePlugins() {
this.pluginManager.disablePlugins();
}
public boolean dispatchCommand(CommandSender sender, String commandLine) throws ServerException {
// First we need to check if this command is on the main thread or not, if not, warn the user
if (!this.isPrimaryThread()) {
getLogger().warning("Command Dispatched Async: " + commandLine);
getLogger().warning("Please notify author of plugin causing this execution to fix this bug!", new Throwable());
// TODO: We should sync the command to the main thread too!
}
if (sender == null) {
throw new ServerException("CommandSender is not valid");
}
if (this.commandMap.dispatch(sender, commandLine)) {
return true;
}
sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.unknown", commandLine));
return false;
}
//todo: use ticker to check console
public ConsoleCommandSender getConsoleSender() {
return consoleSender;
}
public void reload() {
log.info("Reloading...");
log.info("Saving levels...");
for (Level level : this.levelArray) {
level.save();
}
this.pluginManager.disablePlugins();
this.pluginManager.clearPlugins();
this.commandMap.clearCommands();
log.info("Reloading properties...");
this.properties.reload();
this.maxPlayers = this.getPropertyInt("max-players", 20);
if (this.getPropertyBoolean("hardcore", false) && this.getDifficulty() < 3) {
this.setPropertyInt("difficulty", difficulty = 3);
}
this.banByIP.load();
this.banByName.load();
this.reloadWhitelist();
this.operators.reload();
for (BanEntry entry : this.getIPBans().getEntires().values()) {
try {
this.getNetwork().blockAddress(InetAddress.getByName(entry.getName()), -1);
} catch (UnknownHostException e) {
// ignore
}
}
this.pluginManager.registerInterface(JavaPluginLoader.class);
this.pluginManager.loadPlugins(this.pluginPath);
SparkInstaller.initSpark(this);
this.enablePlugins(PluginLoadOrder.STARTUP);
this.enablePlugins(PluginLoadOrder.POSTWORLD);
}
public void shutdown() {
isRunning.compareAndSet(true, false);
}
public void forceShutdown() {
if (this.hasStopped) {
return;
}
try {
isRunning.compareAndSet(true, false);
this.hasStopped = true;
ServerStopEvent serverStopEvent = new ServerStopEvent();
getPluginManager().callEvent(serverStopEvent);
if (this.rcon != null) {
this.rcon.close();
}
for (Player player : new ArrayList<>(this.players.values())) {
player.close(player.getLeaveMessage(), this.getConfig("settings.shutdown-message", "Server closed"));
}
this.getLogger().debug("Disabling all plugins");
this.pluginManager.disablePlugins();
this.getLogger().debug("Removing event handlers");
HandlerList.unregisterAll();
this.getLogger().debug("Stopping all tasks");
this.scheduler.cancelAllTasks();
this.scheduler.mainThreadHeartbeat(Integer.MAX_VALUE);
this.getLogger().debug("Unloading all levels");
for (Level level : this.levelArray) {
this.unloadLevel(level, true);
}
this.getLogger().debug("Closing console");
this.consoleThread.interrupt();
this.getLogger().debug("Stopping network interfaces");
for (SourceInterface interfaz : this.network.getInterfaces()) {
interfaz.shutdown();
this.network.unregisterInterface(interfaz);
}
if (nameLookup != null) {
nameLookup.close();
}
this.getLogger().debug("Disabling timings");
if (this.watchdog != null) {
this.watchdog.kill();
}
//todo other things
} catch (Exception e) {
log.fatal("Exception happened while shutting down, exiting the process", e);
System.exit(1);
}
}
public void start() {
if (this.getPropertyBoolean("enable-query", true)) {
this.queryHandler = new QueryHandler();
}
for (BanEntry entry : this.getIPBans().getEntires().values()) {
try {
this.network.blockAddress(InetAddress.getByName(entry.getName()), -1);
} catch (UnknownHostException e) {
// ignore
}
}
//todo send usage setting
this.tickCounter = 0;
log.info(this.getLanguage().translateString("nukkit.server.defaultGameMode", getGamemodeString(this.getGamemode())));
log.info(this.getLanguage().translateString("nukkit.server.startFinished", String.valueOf((double) (System.currentTimeMillis() - Nukkit.START_TIME) / 1000)));
this.tickProcessor();
this.forceShutdown();
}
public void handlePacket(InetSocketAddress address, ByteBuf payload) {
try {
if (!payload.isReadable(3)) {
return;
}
byte[] prefix = new byte[2];
payload.readBytes(prefix);
if (!Arrays.equals(prefix, new byte[]{(byte) 0xfe, (byte) 0xfd})) {
return;
}
if (this.queryHandler != null) {
this.queryHandler.handle(address, payload);
}
} catch (Exception e) {
log.error("Error whilst handling packet", e);
this.network.blockAddress(address.getAddress(), -1);
}
}
private int lastLevelGC;
public void tickProcessor() {
this.nextTick = System.currentTimeMillis();
try {
while (this.isRunning.get()) {
try {
this.tick();
long next = this.nextTick;
long current = System.currentTimeMillis();
if (next - 0.1 > current) {
long allocated = next - current - 1;
{ // Instead of wasting time, do something potentially useful
int offset = 0;
for (int i = 0; i < levelArray.length; i++) {
offset = (i + lastLevelGC) % levelArray.length;
Level level = levelArray[offset];
level.doGarbageCollection(allocated - 1);
allocated = next - System.currentTimeMillis();
if (allocated <= 0) {
break;
}
}
lastLevelGC = offset + 1;
}
if (allocated > 0) {
Thread.sleep(allocated, 900000);
}
}
} catch (RuntimeException e) {
this.getLogger().logException(e);
}
}
} catch (Throwable e) {
log.fatal("Exception happened while ticking server", e);
log.fatal(Utils.getAllThreadDumps());
}
}
public void onPlayerCompleteLoginSequence(Player player) {
this.sendFullPlayerListData(player);
}
public void onPlayerLogin(Player player) {
if (this.sendUsageTicker > 0) {
this.uniquePlayers.add(player.getUniqueId());
}
}
public void addPlayer(InetSocketAddress socketAddress, Player player) {
this.players.put(socketAddress, player);
}
public void addOnlinePlayer(Player player) {
this.playerList.put(player.getUniqueId(), player);
this.updatePlayerListData(player.getUniqueId(), player.getId(), player.getDisplayName(), player.getSkin(), player.getLoginChainData().getXUID());
}
public void removeOnlinePlayer(Player player) {
if (this.playerList.containsKey(player.getUniqueId())) {
this.playerList.remove(player.getUniqueId());
PlayerListPacket pk = new PlayerListPacket();
pk.type = PlayerListPacket.TYPE_REMOVE;
pk.entries = new PlayerListPacket.Entry[]{new PlayerListPacket.Entry(player.getUniqueId())};