forked from CloudburstMC/Nukkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.java
More file actions
2965 lines (2563 loc) · 101 KB
/
Server.java
File metadata and controls
2965 lines (2563 loc) · 101 KB
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.dispenser.DispenseBehaviorRegister;
import cn.nukkit.entity.Attribute;
import cn.nukkit.entity.Entity;
import cn.nukkit.entity.EntityHuman;
import cn.nukkit.entity.custom.EntityManager;
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.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.custom.CustomItemManager;
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.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.LevelDBProvider;
import cn.nukkit.level.generator.*;
import cn.nukkit.math.NukkitMath;
import cn.nukkit.math.Vector3;
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.BatchingHelper;
import cn.nukkit.network.Network;
import cn.nukkit.network.RakNetInterface;
import cn.nukkit.network.SourceInterface;
import cn.nukkit.network.protocol.*;
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.resourcepacks.loader.JarPluginResourcePackLoader;
import cn.nukkit.resourcepacks.loader.ZippedResourcePackLoader;
import cn.nukkit.scheduler.ServerScheduler;
import cn.nukkit.scheduler.Task;
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.awt.*;
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.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
/**
* The main server class
*
* @author MagicDroidX
* @author Box
*/
@Log4j2
public class Server {
/**
* Permission to receive admin broadcasts such as command usage.
*/
public static final String BROADCAST_CHANNEL_ADMINISTRATIVE = "nukkit.broadcast.admin";
/**
* Permission to receive common broadcasts such as join/quit/death/achievement messages.
*/
public static final String BROADCAST_CHANNEL_USERS = "nukkit.broadcast.user";
private static Server instance;
private final BanList banByName;
private final BanList banByIP;
private final Config operators;
private final Config whitelist;
private final Config properties;
private final Config config;
private final String filePath;
private final String dataPath;
private final String pluginPath;
private final PluginManager pluginManager;
private final ServerScheduler scheduler;
private final BaseLang baseLang;
private final NukkitConsole console;
private final ConsoleThread consoleThread;
private final SimpleCommandMap commandMap;
private final CraftingManager craftingManager;
private final ResourcePackManager resourcePackManager;
private final ConsoleCommandSender consoleSender;
private boolean hasStopped;
private final AtomicBoolean isRunning = new AtomicBoolean(true);
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;
private int baseTickRate;
private int autoSaveTicker;
private int maxPlayers; // setMaxPlayers
private boolean autoSave = true; // setAutoSave
private int difficulty; // setDifficulty
int spawnThresholdRadius;
private String ip;
private int port;
private final UUID serverID = UUID.randomUUID();
private RCON rcon;
private final Network network;
private QueryHandler queryHandler;
private QueryRegenerateEvent queryRegenerateEvent;
private final EntityMetadataStore entityMetadata;
private final PlayerMetadataStore playerMetadata;
private final LevelMetadataStore levelMetadata;
private final Map<InetSocketAddress, Player> players = new HashMap<>();
final Map<UUID, Player> playerList = new HashMap<>();
private static final Pattern UUID_PATTERN = Pattern.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}.dat$");
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;
private final Thread currentThread;
private Watchdog watchdog;
private final DB nameLookup;
private PlayerDataSerializer playerDataSerializer;
private final BatchingHelper batchingHelper;
private final Set<String> ignoredPackets = new HashSet<>();
/**
* The server's MOTD. Remember to call network.setName() when updated.
*/
private String motd;
/**
* Default player data saving enabled.
*/
boolean shouldSavePlayerData;
/**
* Anti fly checks enabled.
*/
private boolean allowFlight;
/**
* Hardcore mode enabled.
*/
private boolean isHardcore;
/**
* Force resource packs.
*/
private boolean forceResources;
/**
* Force player gamemode to default on every join.
*/
private boolean forceGamemode;
/**
* Whitelist enabled.
*/
public boolean whitelistEnabled;
/**
* Xbox authentication enabled.
*/
public boolean xboxAuth;
/**
* Server side achievements enabled.
*/
boolean achievementsEnabled;
/**
* Pvp enabled. Can be changed per world using game rules.
*/
boolean pvpEnabled;
/**
* Announce server side announcements to all players.
*/
boolean announceAchievements;
/**
* How many chunks are sent to player per tick.
*/
public int chunksPerTick;
/**
* How many chunks needs to be sent before the player can spawn.
*/
int spawnThreshold;
/**
* Zlib compression level for sent packets.
*/
public int networkCompressionLevel;
/**
* Maximum view distance in chunks.
*/
private int viewDistance;
/**
* Server's default gamemode.
*/
public int gamemode;
/**
* Minimum amount of time between player skin changes.
*/
private int skinChangeCooldown;
/**
* Spawn protection radius.
*/
private int spawnRadius;
/**
* How often auto save should happen.
*/
private int autoSaveTicks;
/**
* Limit automatic tick rate.
*/
private int autoTickRateLimit;
/**
* Showing plugins in query enabled.
*/
public boolean queryPlugins;
/**
* Chunk caching enabled.
*/
public boolean cacheChunks;
/**
* Whether attacking an entity should stop player from sprinting.
*/
boolean attackStopSprint;
/**
* Enable automatic tick rate adjustments.
*/
private boolean autoTickRate;
/**
* Force server side translations.
*/
private boolean forceLanguage;
/**
* Always tick players.
*/
private boolean alwaysTickPlayers;
/**
* Don't disable client's own packs when force-resources is enabled.
*/
boolean forceResourcesAllowOwnPacks;
/**
* Enable encryption.
*/
boolean encryptionEnabled;
/**
* Use Snappy for packet compression for 1.19.30+ clients.
*/
public final boolean useSnappy;
/**
* Batch packets smaller than this will not be compressed.
*/
public int networkCompressionThreshold;
/**
* Temporary disable world saving to allow safe backup of leveldb worlds.
*/
public boolean holdWorldSave;
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()) {
//noinspection ResultOfMethodCallIgnored
new File(dataPath + "worlds/").mkdirs();
}
if (!new File(dataPath + "players/").exists()) {
//noinspection ResultOfMethodCallIgnored
new File(dataPath + "players/").mkdirs();
}
if (!new File(pluginPath).exists()) {
//noinspection ResultOfMethodCallIgnored
new File(pluginPath).mkdirs();
}
this.dataPath = new File(dataPath).getAbsolutePath() + '/';
this.pluginPath = new File(pluginPath).getAbsolutePath() + '/';
this.playerDataSerializer = new DefaultPlayerDataSerializer(this);
this.console = new NukkitConsole();
this.consoleThread = new ConsoleThread();
this.consoleThread.start();
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.config = new Config(this.dataPath + "nukkit.yml", Config.YAML);
log.info("Loading server properties...");
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;
}
}
this.ignoredPackets.addAll(getConfig().getStringList("debug.ignored-packets"));
this.properties = new Config(this.dataPath + "server.properties", Config.PROPERTIES, new ServerProperties());
// Should not be modified after startup
this.useSnappy = this.getConfig("network.compression-use-snappy", false);
this.baseLang = new BaseLang(this.getConfig("settings.language", BaseLang.FALLBACK_LANGUAGE));
this.loadSettings();
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", "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.scheduler = new ServerScheduler();
this.console.setExecutingCommands(true); // Scheduler needs to be ready
this.batchingHelper = new BatchingHelper();
if (this.getPropertyBoolean("enable-rcon", false)) {
try {
this.rcon = new RCON(this, this.getPropertyString("rcon.password", ""), (!this.getIp().isEmpty()) ? this.getIp() : "0.0.0.0", this.getPropertyInt("rcon.port", this.getPort()));
} catch (IllegalArgumentException e) {
log.error(baseLang.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.consoleSender = new ConsoleCommandSender();
this.commandMap = new SimpleCommandMap(this);
registerEntities();
registerBlockEntities();
Block.init();
Enchantment.init();
GlobalBlockPalette.init();
RuntimeItems.init();
Item.init();
//noinspection ResultOfMethodCallIgnored
EnumBiome.values();
Effect.init();
Potion.init();
Attribute.init();
DispenseBehaviorRegister.init();
//noinspection ResultOfMethodCallIgnored
EntityManager.get();
//noinspection ResultOfMethodCallIgnored
BiomeDefinitionListPacket.getCachedPacket();
//noinspection ResultOfMethodCallIgnored
TrimDataPacket.getCachedPacket();
// 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 ZippedResourcePackLoader(new File(Nukkit.DATA_PATH, "resource_packs")),
new JarPluginResourcePackLoader(new File(this.pluginPath))
);
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);
log.info(this.baseLang.translateString("nukkit.server.networkStart", new String[]{this.getIp().isEmpty() ? "*" : this.getIp(), String.valueOf(this.getPort())}));
this.network = new Network(this);
this.network.setName(this.getMotd());
this.network.setSubName(this.getSubMotd());
this.network.registerInterface(new RakNetInterface(this));
if (!this.encryptionEnabled) {
this.getLogger().warning("Encryption is not enabled! For better security, it's recommended to enable it (network.encryption: true in nukkit.yml) if you don't use a proxy software.");
}
if (!this.xboxAuth) {
this.getLogger().warning("Xbox authentication is not enabled! It's recommended to enable it (xbox-auth=on in server.properties) if you don't use a proxy software or an authentication plugin.");
}
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()));
ExceptionHandler.registerExceptionHandler();
this.pluginManager.loadPlugins(this.pluginPath);
this.enablePlugins(PluginLoadOrder.STARTUP);
CustomItemManager.get().closeRegistry();
EntityManager.get().closeRegistry();
Item.initCreativeItems();
craftingManager.rebuildPacket();
LevelProviderManager.addProvider(this, Anvil.class);
LevelProviderManager.addProvider(this, LevelDBProvider.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);
Generator.addGenerator(TheEnd.class, "the_end", Generator.TYPE_THE_END);
Generator.addGenerator(cn.nukkit.level.generator.Void.class, "void", Generator.TYPE_VOID);
for (String name : this.getConfig("worlds", new HashMap<String, Object>()).keySet()) {
if (!this.loadLevel(name)) {
long seed;
String seedString = String.valueOf(this.getConfig("worlds." + name + ".seed", System.currentTimeMillis()));
try {
seed = Long.parseLong(seedString);
} catch (NumberFormatException e) {
seed = seedString.hashCode();
}
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));
}
if (this.defaultLevel == null) {
this.getLogger().emergency(this.baseLang.translateString("nukkit.level.defaultError"));
this.forceShutdown();
return;
}
this.properties.save(true);
//for (Map.Entry<Integer, Level> entry : this.getLevels().entrySet()) {
Level level = this.defaultLevel;//entry.getValue();
this.getLogger().debug("Preparing spawn region for level " + level.getName());
Vector3 spawn = level.getProvider().getSpawn();
level.populateChunk(spawn.getChunkX(), spawn.getChunkZ(), true);
//}
EnumLevel.initLevels();
this.enablePlugins(PluginLoadOrder.POSTWORLD);
if (Nukkit.DEBUG < 2) {
this.watchdog = new Watchdog(this, 60000);
this.watchdog.start();
}
// Initialize metrics
new NukkitMetrics(this);
this.start();
}
@SuppressWarnings("UnusedReturnValue")
public int broadcastMessage(String message) {
return this.broadcast(message, BROADCAST_CHANNEL_USERS);
}
@SuppressWarnings("UnusedReturnValue")
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;
}
@SuppressWarnings("UnusedReturnValue")
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);
}
}
public void batchPackets(Player[] players, DataPacket[] packets) {
this.batchingHelper.batchPackets(this, players, packets);
}
/**
* Enable all plugins with matching load order
* @param type load order
*/
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();
}
}
/**
* Enable a plugin
* @param plugin plugin
*/
public void enablePlugin(Plugin plugin) {
this.pluginManager.enablePlugin(plugin);
}
/**
* Disable all loaded plugins
*/
public void disablePlugins() {
this.pluginManager.disablePlugins();
}
/**
* Run a command as CommandSender. Use server.getConsoleSender() to run as CONSOLE.
* @param sender command sender
* @param commandLine command without slash
* @return command was found and attempted to be executed
*/
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 asynchronously: " + commandLine);
}
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;
}
/**
* Get server console CommandSender
* @return ConsoleCommandSender
*/
public ConsoleCommandSender getConsoleSender() {
return consoleSender;
}
/**
* Reload the server. Notice: may cause issues with some plugins.
*/
public void reload() {
log.info("Saving levels...");
for (Level level : this.levelArray) {
level.save();
}
this.pluginManager.clearPlugins();
this.commandMap.clearCommands();
log.info("Reloading server properties...");
this.properties.reload();
this.loadSettings();
this.banByIP.load();
this.banByName.load();
this.reloadWhitelist();
this.operators.reload();
for (BanEntry entry : this.banByIP.getEntires().values()) {
try {
this.network.blockAddress(InetAddress.getByName(entry.getName()));
} catch (UnknownHostException ignore) {}
}
log.info("Reloading plugins...");
this.pluginManager.registerInterface(JavaPluginLoader.class);
this.pluginManager.loadPlugins(this.pluginPath);
this.enablePlugins(PluginLoadOrder.STARTUP);
this.enablePlugins(PluginLoadOrder.POSTWORLD);
}
/**
* Mark the server to be shut down.
*/
public void shutdown() {
isRunning.compareAndSet(true, false);
}
/**
* Shut down the server immediately.
*/
public void forceShutdown() {
this.forceShutdown(this.getConfig("settings.shutdown-message", "Server closed"));
}
/**
* Shut down the server immediately.
*
* @param reason message that shows to players on disconnect
*/
public void forceShutdown(String reason) {
if (this.hasStopped) {
return;
}
try {
isRunning.compareAndSet(true, false);
this.hasStopped = true;
ServerStopEvent serverStopEvent = new ServerStopEvent();
pluginManager.callEvent(serverStopEvent);
if (this.holdWorldSave) {
this.getLogger().warning("World save hold was not released! Any backup currently being taken may be invalid");
}
if (this.rcon != null) {
this.getLogger().debug("Closing RCON...");
this.rcon.close();
}
this.getLogger().debug("Disconnecting all players...");
for (Player player : new ArrayList<>(this.players.values())) {
player.close(player.getLeaveMessage(), reason);
}
this.getLogger().debug("Disabling all plugins...");
this.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.nextTick = System.currentTimeMillis(); // Fix Watchdog killing the server while saving worlds
}
this.getLogger().debug("Closing console...");
this.consoleThread.interrupt();
this.getLogger().debug("Closing BatchingHelper...");
this.batchingHelper.shutdown();
this.getLogger().debug("Stopping network interfaces...");
for (SourceInterface interfaz : this.network.getInterfaces()) {
interfaz.shutdown();
this.network.unregisterInterface(interfaz);
}
if (nameLookup != null) {
this.getLogger().debug("Closing name lookup DB...");
nameLookup.close();
}
if (this.watchdog != null) {
this.getLogger().debug("Stopping Watchdog...");
this.watchdog.kill();
}
} catch (Exception e) {
log.fatal("Exception happened while shutting down, exiting the process", e);
System.exit(1);
}
}
/**
* Internal: Start the server
*/
public void start() {
if (this.getPropertyBoolean("enable-query", false)) {
this.queryHandler = new QueryHandler();
}
for (BanEntry entry : this.banByIP.getEntires().values()) {
try {
this.network.blockAddress(InetAddress.getByName(entry.getName()));
} catch (UnknownHostException ignore) {}
}
this.tickCounter = 0;
//log.info(this.getLanguage().translateString("nukkit.server.defaultGameMode", getGamemodeString(this.getGamemode())));
log.info(this.baseLang.translateString("nukkit.server.startFinished", String.valueOf((double) (System.currentTimeMillis() - Nukkit.START_TIME) / 1000)));
this.tickProcessor();
this.forceShutdown();
}
private static final byte[] QUERY_PREFIX = {(byte) 0xfe, (byte) 0xfd};
/**
* Internal: Handle query
* @param address sender address
* @param payload payload
*/
public void handlePacket(InetSocketAddress address, ByteBuf payload) {
try {
if (this.queryHandler == null || !payload.isReadable(3)) {
return;
}
byte[] prefix = new byte[2];
payload.readBytes(prefix);
if (Arrays.equals(prefix, QUERY_PREFIX)) {
this.queryHandler.handle(address, payload);
}
} catch (Exception e) {
log.error("Error whilst handling packet", e);
this.network.blockAddress(address.getAddress(), 300);
}
}
private int lastLevelGC;
/**
* Internal: Tick the server
*/
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];
if (!level.isBeingConverted) {
level.doGarbageCollection(allocated - 1);
}
allocated = next - System.currentTimeMillis();
if (allocated <= 0) break;
}
lastLevelGC = offset + 1;
if (allocated > 0) {
try {
Thread.sleep(allocated, 900000);
} catch (Exception e) {
this.getLogger().logException(e);
}
}
}