PocketMine-MP 5.25.1 git-694aa17cc916a954b10fe12721c81b1dc73eecd5
Loading...
Searching...
No Matches
src/Server.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
28namespace pocketmine;
29
76use pocketmine\player\GameMode;
85use pocketmine\plugin\PluginEnableOrder;
110use pocketmine\utils\NotCloneable;
111use pocketmine\utils\NotSerializable;
127use Ramsey\Uuid\UuidInterface;
128use Symfony\Component\Filesystem\Path;
129use function array_fill;
130use function array_sum;
131use function base64_encode;
132use function chr;
133use function cli_set_process_title;
134use function copy;
135use function count;
136use function date;
137use function fclose;
138use function file_exists;
139use function file_put_contents;
140use function filemtime;
141use function fopen;
142use function get_class;
143use function gettype;
144use function ini_set;
145use function is_array;
146use function is_dir;
147use function is_int;
148use function is_object;
149use function is_resource;
150use function is_string;
151use function json_decode;
152use function max;
153use function microtime;
154use function min;
155use function mkdir;
156use function ob_end_flush;
157use function preg_replace;
158use function realpath;
159use function register_shutdown_function;
160use function rename;
161use function round;
162use function sleep;
163use function spl_object_id;
164use function sprintf;
165use function str_repeat;
166use function str_replace;
167use function stripos;
168use function strlen;
169use function strrpos;
170use function strtolower;
171use function strval;
172use function time;
173use function touch;
174use function trim;
175use function yaml_parse;
176use const DIRECTORY_SEPARATOR;
177use const PHP_EOL;
178use const PHP_INT_MAX;
179
183class Server{
184 use NotCloneable;
185 use NotSerializable;
186
187 public const BROADCAST_CHANNEL_ADMINISTRATIVE = "pocketmine.broadcast.admin";
188 public const BROADCAST_CHANNEL_USERS = "pocketmine.broadcast.user";
189
190 public const DEFAULT_SERVER_NAME = VersionInfo::NAME . " Server";
191 public const DEFAULT_MAX_PLAYERS = 20;
192 public const DEFAULT_PORT_IPV4 = 19132;
193 public const DEFAULT_PORT_IPV6 = 19133;
194 public const DEFAULT_MAX_VIEW_DISTANCE = 16;
195
201 public const TARGET_TICKS_PER_SECOND = 20;
205 public const TARGET_SECONDS_PER_TICK = 1 / self::TARGET_TICKS_PER_SECOND;
206 public const TARGET_NANOSECONDS_PER_TICK = 1_000_000_000 / self::TARGET_TICKS_PER_SECOND;
207
211 private const TPS_OVERLOAD_WARNING_THRESHOLD = self::TARGET_TICKS_PER_SECOND * 0.6;
212
213 private const TICKS_PER_WORLD_CACHE_CLEAR = 5 * self::TARGET_TICKS_PER_SECOND;
214 private const TICKS_PER_TPS_OVERLOAD_WARNING = 5 * self::TARGET_TICKS_PER_SECOND;
215 private const TICKS_PER_STATS_REPORT = 300 * self::TARGET_TICKS_PER_SECOND;
216
217 private const DEFAULT_ASYNC_COMPRESSION_THRESHOLD = 10_000;
218
219 private static ?Server $instance = null;
220
221 private TimeTrackingSleeperHandler $tickSleeper;
222
223 private BanList $banByName;
224
225 private BanList $banByIP;
226
227 private Config $operators;
228
229 private Config $whitelist;
230
231 private bool $isRunning = true;
232
233 private bool $hasStopped = false;
234
235 private PluginManager $pluginManager;
236
237 private float $profilingTickRate = self::TARGET_TICKS_PER_SECOND;
238
239 private UpdateChecker $updater;
240
241 private AsyncPool $asyncPool;
242
244 private int $tickCounter = 0;
245 private float $nextTick = 0;
247 private array $tickAverage;
249 private array $useAverage;
250 private float $currentTPS = self::TARGET_TICKS_PER_SECOND;
251 private float $currentUse = 0;
252 private float $startTime;
253
254 private bool $doTitleTick = true;
255
256 private int $sendUsageTicker = 0;
257
258 private MemoryManager $memoryManager;
259
260 private ?ConsoleReaderChildProcessDaemon $console = null;
261 private ?ConsoleCommandSender $consoleSender = null;
262
263 private SimpleCommandMap $commandMap;
264
265 private CraftingManager $craftingManager;
266
267 private ResourcePackManager $resourceManager;
268
269 private WorldManager $worldManager;
270
271 private int $maxPlayers;
272
273 private bool $onlineMode = true;
274
275 private Network $network;
276 private bool $networkCompressionAsync = true;
277 private int $networkCompressionAsyncThreshold = self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD;
278
279 private Language $language;
280 private bool $forceLanguage = false;
281
282 private UuidInterface $serverID;
283
284 private string $dataPath;
285 private string $pluginPath;
286
287 private PlayerDataProvider $playerDataProvider;
288
293 private array $uniquePlayers = [];
294
295 private QueryInfo $queryInfo;
296
297 private ServerConfigGroup $configGroup;
298
300 private array $playerList = [];
301
302 private SignalHandler $signalHandler;
303
308 private array $broadcastSubscribers = [];
309
310 public function getName() : string{
311 return VersionInfo::NAME;
312 }
313
314 public function isRunning() : bool{
315 return $this->isRunning;
316 }
317
318 public function getPocketMineVersion() : string{
319 return VersionInfo::VERSION()->getFullVersion(true);
320 }
321
322 public function getVersion() : string{
323 return ProtocolInfo::MINECRAFT_VERSION;
324 }
325
326 public function getApiVersion() : string{
327 return VersionInfo::BASE_VERSION;
328 }
329
330 public function getFilePath() : string{
331 return \pocketmine\PATH;
332 }
333
334 public function getResourcePath() : string{
335 return \pocketmine\RESOURCE_PATH;
336 }
337
338 public function getDataPath() : string{
339 return $this->dataPath;
340 }
341
342 public function getPluginPath() : string{
343 return $this->pluginPath;
344 }
345
346 public function getMaxPlayers() : int{
347 return $this->maxPlayers;
348 }
349
350 public function setMaxPlayers(int $maxPlayers) : void{
351 $this->maxPlayers = $maxPlayers;
352 }
353
358 public function getOnlineMode() : bool{
359 return $this->onlineMode;
360 }
361
365 public function requiresAuthentication() : bool{
366 return $this->getOnlineMode();
367 }
368
369 public function getPort() : int{
370 return $this->configGroup->getConfigInt(ServerProperties::SERVER_PORT_IPV4, self::DEFAULT_PORT_IPV4);
371 }
372
373 public function getPortV6() : int{
374 return $this->configGroup->getConfigInt(ServerProperties::SERVER_PORT_IPV6, self::DEFAULT_PORT_IPV6);
375 }
376
377 public function getViewDistance() : int{
378 return max(2, $this->configGroup->getConfigInt(ServerProperties::VIEW_DISTANCE, self::DEFAULT_MAX_VIEW_DISTANCE));
379 }
380
384 public function getAllowedViewDistance(int $distance) : int{
385 return max(2, min($distance, $this->memoryManager->getViewDistance($this->getViewDistance())));
386 }
387
388 public function getIp() : string{
389 $str = $this->configGroup->getConfigString(ServerProperties::SERVER_IPV4);
390 return $str !== "" ? $str : "0.0.0.0";
391 }
392
393 public function getIpV6() : string{
394 $str = $this->configGroup->getConfigString(ServerProperties::SERVER_IPV6);
395 return $str !== "" ? $str : "::";
396 }
397
398 public function getServerUniqueId() : UuidInterface{
399 return $this->serverID;
400 }
401
402 public function getGamemode() : GameMode{
403 return GameMode::fromString($this->configGroup->getConfigString(ServerProperties::GAME_MODE)) ?? GameMode::SURVIVAL;
404 }
405
406 public function getForceGamemode() : bool{
407 return $this->configGroup->getConfigBool(ServerProperties::FORCE_GAME_MODE, false);
408 }
409
413 public function getDifficulty() : int{
414 return $this->configGroup->getConfigInt(ServerProperties::DIFFICULTY, World::DIFFICULTY_NORMAL);
415 }
416
417 public function hasWhitelist() : bool{
418 return $this->configGroup->getConfigBool(ServerProperties::WHITELIST, false);
419 }
420
421 public function isHardcore() : bool{
422 return $this->configGroup->getConfigBool(ServerProperties::HARDCORE, false);
423 }
424
425 public function getMotd() : string{
426 return $this->configGroup->getConfigString(ServerProperties::MOTD, self::DEFAULT_SERVER_NAME);
427 }
428
429 public function getLoader() : ThreadSafeClassLoader{
430 return $this->autoloader;
431 }
432
433 public function getLogger() : AttachableThreadSafeLogger{
434 return $this->logger;
435 }
436
437 public function getUpdater() : UpdateChecker{
438 return $this->updater;
439 }
440
441 public function getPluginManager() : PluginManager{
442 return $this->pluginManager;
443 }
444
445 public function getCraftingManager() : CraftingManager{
446 return $this->craftingManager;
447 }
448
449 public function getResourcePackManager() : ResourcePackManager{
450 return $this->resourceManager;
451 }
452
453 public function getWorldManager() : WorldManager{
454 return $this->worldManager;
455 }
456
457 public function getAsyncPool() : AsyncPool{
458 return $this->asyncPool;
459 }
460
461 public function getTick() : int{
462 return $this->tickCounter;
463 }
464
468 public function getTicksPerSecond() : float{
469 return round($this->currentTPS, 2);
470 }
471
475 public function getTicksPerSecondAverage() : float{
476 return round(array_sum($this->tickAverage) / count($this->tickAverage), 2);
477 }
478
482 public function getTickUsage() : float{
483 return round($this->currentUse * 100, 2);
484 }
485
489 public function getTickUsageAverage() : float{
490 return round((array_sum($this->useAverage) / count($this->useAverage)) * 100, 2);
491 }
492
493 public function getStartTime() : float{
494 return $this->startTime;
495 }
496
497 public function getCommandMap() : SimpleCommandMap{
498 return $this->commandMap;
499 }
500
504 public function getOnlinePlayers() : array{
505 return $this->playerList;
506 }
507
508 public function shouldSavePlayerData() : bool{
509 return $this->configGroup->getPropertyBool(Yml::PLAYER_SAVE_PLAYER_DATA, true);
510 }
511
512 public function getOfflinePlayer(string $name) : Player|OfflinePlayer|null{
513 $name = strtolower($name);
514 $result = $this->getPlayerExact($name);
515
516 if($result === null){
517 $result = new OfflinePlayer($name, $this->getOfflinePlayerData($name));
518 }
519
520 return $result;
521 }
522
526 public function hasOfflinePlayerData(string $name) : bool{
527 return $this->playerDataProvider->hasData($name);
528 }
529
530 public function getOfflinePlayerData(string $name) : ?CompoundTag{
531 return Timings::$syncPlayerDataLoad->time(function() use ($name) : ?CompoundTag{
532 try{
533 return $this->playerDataProvider->loadData($name);
534 }catch(PlayerDataLoadException $e){
535 $this->logger->debug("Failed to load player data for $name: " . $e->getMessage());
536 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_data_playerCorrupted($name)));
537 return null;
538 }
539 });
540 }
541
542 public function saveOfflinePlayerData(string $name, CompoundTag $nbtTag) : void{
543 $ev = new PlayerDataSaveEvent($nbtTag, $name, $this->getPlayerExact($name));
544 if(!$this->shouldSavePlayerData()){
545 $ev->cancel();
546 }
547
548 $ev->call();
549
550 if(!$ev->isCancelled()){
551 Timings::$syncPlayerDataSave->time(function() use ($name, $ev) : void{
552 try{
553 $this->playerDataProvider->saveData($name, $ev->getSaveData());
554 }catch(PlayerDataSaveException $e){
555 $this->logger->critical($this->language->translate(KnownTranslationFactory::pocketmine_data_saveError($name, $e->getMessage())));
556 $this->logger->logException($e);
557 }
558 });
559 }
560 }
561
565 public function createPlayer(NetworkSession $session, PlayerInfo $playerInfo, bool $authenticated, ?CompoundTag $offlinePlayerData) : Promise{
566 $ev = new PlayerCreationEvent($session);
567 $ev->call();
568 $class = $ev->getPlayerClass();
569
570 if($offlinePlayerData !== null && ($world = $this->worldManager->getWorldByName($offlinePlayerData->getString(Player::TAG_LEVEL, ""))) !== null){
571 $playerPos = EntityDataHelper::parseLocation($offlinePlayerData, $world);
572 }else{
573 $world = $this->worldManager->getDefaultWorld();
574 if($world === null){
575 throw new AssumptionFailedError("Default world should always be loaded");
576 }
577 $playerPos = null;
578 }
580 $playerPromiseResolver = new PromiseResolver();
581
582 $createPlayer = function(Location $location) use ($playerPromiseResolver, $class, $session, $playerInfo, $authenticated, $offlinePlayerData) : void{
584 $player = new $class($this, $session, $playerInfo, $authenticated, $location, $offlinePlayerData);
585 if(!$player->hasPlayedBefore()){
586 $player->onGround = true; //TODO: this hack is needed for new players in-air ticks - they don't get detected as on-ground until they move
587 }
588 $playerPromiseResolver->resolve($player);
589 };
590
591 if($playerPos === null){ //new player or no valid position due to world not being loaded
592 $world->requestSafeSpawn()->onCompletion(
593 function(Position $spawn) use ($createPlayer, $playerPromiseResolver, $session, $world) : void{
594 if(!$session->isConnected()){
595 $playerPromiseResolver->reject();
596 return;
597 }
598 $createPlayer(Location::fromObject($spawn, $world));
599 },
600 function() use ($playerPromiseResolver, $session) : void{
601 if($session->isConnected()){
602 $session->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
603 }
604 $playerPromiseResolver->reject();
605 }
606 );
607 }else{ //returning player with a valid position - safe spawn not required
608 $createPlayer($playerPos);
609 }
610
611 return $playerPromiseResolver->getPromise();
612 }
613
624 public function getPlayerByPrefix(string $name) : ?Player{
625 $found = null;
626 $name = strtolower($name);
627 $delta = PHP_INT_MAX;
628 foreach($this->getOnlinePlayers() as $player){
629 if(stripos($player->getName(), $name) === 0){
630 $curDelta = strlen($player->getName()) - strlen($name);
631 if($curDelta < $delta){
632 $found = $player;
633 $delta = $curDelta;
634 }
635 if($curDelta === 0){
636 break;
637 }
638 }
639 }
640
641 return $found;
642 }
643
647 public function getPlayerExact(string $name) : ?Player{
648 $name = strtolower($name);
649 foreach($this->getOnlinePlayers() as $player){
650 if(strtolower($player->getName()) === $name){
651 return $player;
652 }
653 }
654
655 return null;
656 }
657
661 public function getPlayerByRawUUID(string $rawUUID) : ?Player{
662 return $this->playerList[$rawUUID] ?? null;
663 }
664
668 public function getPlayerByUUID(UuidInterface $uuid) : ?Player{
669 return $this->getPlayerByRawUUID($uuid->getBytes());
670 }
671
672 public function getConfigGroup() : ServerConfigGroup{
673 return $this->configGroup;
674 }
675
680 public function getPluginCommand(string $name){
681 if(($command = $this->commandMap->getCommand($name)) instanceof PluginOwned){
682 return $command;
683 }else{
684 return null;
685 }
686 }
687
688 public function getNameBans() : BanList{
689 return $this->banByName;
690 }
691
692 public function getIPBans() : BanList{
693 return $this->banByIP;
694 }
695
696 public function addOp(string $name) : void{
697 $this->operators->set(strtolower($name), true);
698
699 if(($player = $this->getPlayerExact($name)) !== null){
700 $player->setBasePermission(DefaultPermissions::ROOT_OPERATOR, true);
701 }
702 $this->operators->save();
703 }
704
705 public function removeOp(string $name) : void{
706 $lowercaseName = strtolower($name);
707 foreach($this->operators->getAll() as $operatorName => $_){
708 $operatorName = (string) $operatorName;
709 if($lowercaseName === strtolower($operatorName)){
710 $this->operators->remove($operatorName);
711 }
712 }
713
714 if(($player = $this->getPlayerExact($name)) !== null){
715 $player->unsetBasePermission(DefaultPermissions::ROOT_OPERATOR);
716 }
717 $this->operators->save();
718 }
719
720 public function addWhitelist(string $name) : void{
721 $this->whitelist->set(strtolower($name), true);
722 $this->whitelist->save();
723 }
724
725 public function removeWhitelist(string $name) : void{
726 $this->whitelist->remove(strtolower($name));
727 $this->whitelist->save();
728 }
729
730 public function isWhitelisted(string $name) : bool{
731 return !$this->hasWhitelist() || $this->operators->exists($name, true) || $this->whitelist->exists($name, true);
732 }
733
734 public function isOp(string $name) : bool{
735 return $this->operators->exists($name, true);
736 }
737
738 public function getWhitelisted() : Config{
739 return $this->whitelist;
740 }
741
742 public function getOps() : Config{
743 return $this->operators;
744 }
745
750 public function getCommandAliases() : array{
751 $section = $this->configGroup->getProperty(Yml::ALIASES);
752 $result = [];
753 if(is_array($section)){
754 foreach(Utils::promoteKeys($section) as $key => $value){
755 //TODO: more validation needed here
756 //key might not be a string, value might not be list<string>
757 $commands = [];
758 if(is_array($value)){
759 $commands = $value;
760 }else{
761 $commands[] = (string) $value;
762 }
763
764 $result[(string) $key] = $commands;
765 }
766 }
767
768 return $result;
769 }
770
771 public static function getInstance() : Server{
772 if(self::$instance === null){
773 throw new \RuntimeException("Attempt to retrieve Server instance outside server thread");
774 }
775 return self::$instance;
776 }
777
778 public function __construct(
779 private ThreadSafeClassLoader $autoloader,
780 private AttachableThreadSafeLogger $logger,
781 string $dataPath,
782 string $pluginPath
783 ){
784 if(self::$instance !== null){
785 throw new \LogicException("Only one server instance can exist at once");
786 }
787 self::$instance = $this;
788 $this->startTime = microtime(true);
789 $this->tickAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, self::TARGET_TICKS_PER_SECOND);
790 $this->useAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, 0);
791
792 Timings::init();
793 $this->tickSleeper = new TimeTrackingSleeperHandler(Timings::$serverInterrupts);
794
795 $this->signalHandler = new SignalHandler(function() : void{
796 $this->logger->info("Received signal interrupt, stopping the server");
797 $this->shutdown();
798 });
799
800 try{
801 foreach([
802 $dataPath,
803 $pluginPath,
804 Path::join($dataPath, "worlds"),
805 Path::join($dataPath, "players")
806 ] as $neededPath){
807 if(!file_exists($neededPath)){
808 mkdir($neededPath, 0777);
809 }
810 }
811
812 $this->dataPath = realpath($dataPath) . DIRECTORY_SEPARATOR;
813 $this->pluginPath = realpath($pluginPath) . DIRECTORY_SEPARATOR;
814
815 $this->logger->info("Loading server configuration");
816 $pocketmineYmlPath = Path::join($this->dataPath, "pocketmine.yml");
817 if(!file_exists($pocketmineYmlPath)){
818 $content = Filesystem::fileGetContents(Path::join(\pocketmine\RESOURCE_PATH, "pocketmine.yml"));
819 if(VersionInfo::IS_DEVELOPMENT_BUILD){
820 $content = str_replace("preferred-channel: stable", "preferred-channel: beta", $content);
821 }
822 @file_put_contents($pocketmineYmlPath, $content);
823 }
824
825 $this->configGroup = new ServerConfigGroup(
826 new Config($pocketmineYmlPath, Config::YAML, []),
827 new Config(Path::join($this->dataPath, "server.properties"), Config::PROPERTIES, [
828 ServerProperties::MOTD => self::DEFAULT_SERVER_NAME,
829 ServerProperties::SERVER_PORT_IPV4 => self::DEFAULT_PORT_IPV4,
830 ServerProperties::SERVER_PORT_IPV6 => self::DEFAULT_PORT_IPV6,
831 ServerProperties::ENABLE_IPV6 => true,
832 ServerProperties::WHITELIST => false,
833 ServerProperties::MAX_PLAYERS => self::DEFAULT_MAX_PLAYERS,
834 ServerProperties::GAME_MODE => GameMode::SURVIVAL->name, //TODO: this probably shouldn't use the enum name directly
835 ServerProperties::FORCE_GAME_MODE => false,
836 ServerProperties::HARDCORE => false,
837 ServerProperties::PVP => true,
838 ServerProperties::DIFFICULTY => World::DIFFICULTY_NORMAL,
839 ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS => "",
840 ServerProperties::DEFAULT_WORLD_NAME => "world",
841 ServerProperties::DEFAULT_WORLD_SEED => "",
842 ServerProperties::DEFAULT_WORLD_GENERATOR => "DEFAULT",
843 ServerProperties::ENABLE_QUERY => true,
844 ServerProperties::AUTO_SAVE => true,
845 ServerProperties::VIEW_DISTANCE => self::DEFAULT_MAX_VIEW_DISTANCE,
846 ServerProperties::XBOX_AUTH => true,
847 ServerProperties::LANGUAGE => "eng"
848 ])
849 );
850
851 $debugLogLevel = $this->configGroup->getPropertyInt(Yml::DEBUG_LEVEL, 1);
852 if($this->logger instanceof MainLogger){
853 $this->logger->setLogDebug($debugLogLevel > 1);
854 }
855
856 $this->forceLanguage = $this->configGroup->getPropertyBool(Yml::SETTINGS_FORCE_LANGUAGE, false);
857 $selectedLang = $this->configGroup->getConfigString(ServerProperties::LANGUAGE, $this->configGroup->getPropertyString("settings.language", Language::FALLBACK_LANGUAGE));
858 try{
859 $this->language = new Language($selectedLang);
860 }catch(LanguageNotFoundException $e){
861 $this->logger->error($e->getMessage());
862 try{
863 $this->language = new Language(Language::FALLBACK_LANGUAGE);
864 }catch(LanguageNotFoundException $e){
865 $this->logger->emergency("Fallback language \"" . Language::FALLBACK_LANGUAGE . "\" not found");
866 return;
867 }
868 }
869
870 $this->logger->info($this->language->translate(KnownTranslationFactory::language_selected($this->language->getName(), $this->language->getLang())));
871
872 if(VersionInfo::IS_DEVELOPMENT_BUILD){
873 if(!$this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_DEV_BUILDS, false)){
874 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error1(VersionInfo::NAME)));
875 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error2()));
876 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error3()));
877 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error4(Yml::SETTINGS_ENABLE_DEV_BUILDS)));
878 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error5("https://github.com/pmmp/PocketMine-MP/releases")));
879 $this->forceShutdownExit();
880
881 return;
882 }
883
884 $this->logger->warning(str_repeat("-", 40));
885 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning1(VersionInfo::NAME)));
886 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning2()));
887 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning3()));
888 $this->logger->warning(str_repeat("-", 40));
889 }
890
891 $this->memoryManager = new MemoryManager($this);
892
893 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_start(TextFormat::AQUA . $this->getVersion() . TextFormat::RESET)));
894
895 if(($poolSize = $this->configGroup->getPropertyString(Yml::SETTINGS_ASYNC_WORKERS, "auto")) === "auto"){
896 $poolSize = 2;
897 $processors = Utils::getCoreCount() - 2;
898
899 if($processors > 0){
900 $poolSize = max(1, $processors);
901 }
902 }else{
903 $poolSize = max(1, (int) $poolSize);
904 }
905
906 TimingsHandler::setEnabled($this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_PROFILING, false));
907 $this->profilingTickRate = $this->configGroup->getPropertyInt(Yml::SETTINGS_PROFILE_REPORT_TRIGGER, self::TARGET_TICKS_PER_SECOND);
908
909 $this->asyncPool = new AsyncPool($poolSize, max(-1, $this->configGroup->getPropertyInt(Yml::MEMORY_ASYNC_WORKER_HARD_LIMIT, 256)), $this->autoloader, $this->logger, $this->tickSleeper);
910 $this->asyncPool->addWorkerStartHook(function(int $i) : void{
911 if(TimingsHandler::isEnabled()){
912 $this->asyncPool->submitTaskToWorker(TimingsControlTask::setEnabled(true), $i);
913 }
914 });
915 TimingsHandler::getToggleCallbacks()->add(function(bool $enable) : void{
916 foreach($this->asyncPool->getRunningWorkers() as $workerId){
917 $this->asyncPool->submitTaskToWorker(TimingsControlTask::setEnabled($enable), $workerId);
918 }
919 });
920 TimingsHandler::getReloadCallbacks()->add(function() : void{
921 foreach($this->asyncPool->getRunningWorkers() as $workerId){
922 $this->asyncPool->submitTaskToWorker(TimingsControlTask::reload(), $workerId);
923 }
924 });
925 TimingsHandler::getCollectCallbacks()->add(function() : array{
926 $promises = [];
927 foreach($this->asyncPool->getRunningWorkers() as $workerId){
929 $resolver = new PromiseResolver();
930 $this->asyncPool->submitTaskToWorker(new TimingsCollectionTask($resolver), $workerId);
931
932 $promises[] = $resolver->getPromise();
933 }
934
935 return $promises;
936 });
937
938 $netCompressionThreshold = -1;
939 if($this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256) >= 0){
940 $netCompressionThreshold = $this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256);
941 }
942 if($netCompressionThreshold < 0){
943 $netCompressionThreshold = null;
944 }
945
946 $netCompressionLevel = $this->configGroup->getPropertyInt(Yml::NETWORK_COMPRESSION_LEVEL, 6);
947 if($netCompressionLevel < 1 || $netCompressionLevel > 9){
948 $this->logger->warning("Invalid network compression level $netCompressionLevel set, setting to default 6");
949 $netCompressionLevel = 6;
950 }
951 ZlibCompressor::setInstance(new ZlibCompressor($netCompressionLevel, $netCompressionThreshold, ZlibCompressor::DEFAULT_MAX_DECOMPRESSION_SIZE));
952
953 $this->networkCompressionAsync = $this->configGroup->getPropertyBool(Yml::NETWORK_ASYNC_COMPRESSION, true);
954 $this->networkCompressionAsyncThreshold = max(
955 $this->configGroup->getPropertyInt(Yml::NETWORK_ASYNC_COMPRESSION_THRESHOLD, self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD),
956 $netCompressionThreshold ?? self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD
957 );
958
959 EncryptionContext::$ENABLED = $this->configGroup->getPropertyBool(Yml::NETWORK_ENABLE_ENCRYPTION, true);
960
961 $this->doTitleTick = $this->configGroup->getPropertyBool(Yml::CONSOLE_TITLE_TICK, true) && Terminal::hasFormattingCodes();
962
963 $this->operators = new Config(Path::join($this->dataPath, "ops.txt"), Config::ENUM);
964 $this->whitelist = new Config(Path::join($this->dataPath, "white-list.txt"), Config::ENUM);
965
966 $bannedTxt = Path::join($this->dataPath, "banned.txt");
967 $bannedPlayersTxt = Path::join($this->dataPath, "banned-players.txt");
968 if(file_exists($bannedTxt) && !file_exists($bannedPlayersTxt)){
969 @rename($bannedTxt, $bannedPlayersTxt);
970 }
971 @touch($bannedPlayersTxt);
972 $this->banByName = new BanList($bannedPlayersTxt);
973 $this->banByName->load();
974 $bannedIpsTxt = Path::join($this->dataPath, "banned-ips.txt");
975 @touch($bannedIpsTxt);
976 $this->banByIP = new BanList($bannedIpsTxt);
977 $this->banByIP->load();
978
979 $this->maxPlayers = $this->configGroup->getConfigInt(ServerProperties::MAX_PLAYERS, self::DEFAULT_MAX_PLAYERS);
980
981 $this->onlineMode = $this->configGroup->getConfigBool(ServerProperties::XBOX_AUTH, true);
982 if($this->onlineMode){
983 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_enabled()));
984 }else{
985 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_disabled()));
986 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authWarning()));
987 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authProperty_disabled()));
988 }
989
990 if($this->configGroup->getConfigBool(ServerProperties::HARDCORE, false) && $this->getDifficulty() < World::DIFFICULTY_HARD){
991 $this->configGroup->setConfigInt(ServerProperties::DIFFICULTY, World::DIFFICULTY_HARD);
992 }
993
994 @cli_set_process_title($this->getName() . " " . $this->getPocketMineVersion());
995
996 $this->serverID = Utils::getMachineUniqueId($this->getIp() . $this->getPort());
997
998 $this->logger->debug("Server unique id: " . $this->getServerUniqueId());
999 $this->logger->debug("Machine unique id: " . Utils::getMachineUniqueId());
1000
1001 $this->network = new Network($this->logger);
1002 $this->network->setName($this->getMotd());
1003
1004 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_info(
1005 $this->getName(),
1006 (VersionInfo::IS_DEVELOPMENT_BUILD ? TextFormat::YELLOW : "") . $this->getPocketMineVersion() . TextFormat::RESET
1007 )));
1008 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_license($this->getName())));
1009
1010 DefaultPermissions::registerCorePermissions();
1011
1012 $this->commandMap = new SimpleCommandMap($this);
1013
1014 $this->craftingManager = CraftingManagerFromDataHelper::make(BedrockDataFiles::RECIPES);
1015
1016 $this->resourceManager = new ResourcePackManager(Path::join($this->dataPath, "resource_packs"), $this->logger);
1017
1018 $pluginGraylist = null;
1019 $graylistFile = Path::join($this->dataPath, "plugin_list.yml");
1020 if(!file_exists($graylistFile)){
1021 copy(Path::join(\pocketmine\RESOURCE_PATH, 'plugin_list.yml'), $graylistFile);
1022 }
1023 try{
1024 $array = yaml_parse(Filesystem::fileGetContents($graylistFile));
1025 if(!is_array($array)){
1026 throw new \InvalidArgumentException("Expected array for root, but have " . gettype($array));
1027 }
1028 $pluginGraylist = PluginGraylist::fromArray($array);
1029 }catch(\InvalidArgumentException $e){
1030 $this->logger->emergency("Failed to load $graylistFile: " . $e->getMessage());
1031 $this->forceShutdownExit();
1032 return;
1033 }
1034 $this->pluginManager = new PluginManager($this, $this->configGroup->getPropertyBool(Yml::PLUGINS_LEGACY_DATA_DIR, true) ? null : Path::join($this->dataPath, "plugin_data"), $pluginGraylist);
1035 $this->pluginManager->registerInterface(new PharPluginLoader($this->autoloader));
1036 $this->pluginManager->registerInterface(new ScriptPluginLoader());
1037 $this->pluginManager->registerInterface(new FolderPluginLoader($this->autoloader));
1038
1039 $providerManager = new WorldProviderManager();
1040 if(
1041 ($format = $providerManager->getProviderByName($formatName = $this->configGroup->getPropertyString(Yml::LEVEL_SETTINGS_DEFAULT_FORMAT, ""))) !== null &&
1042 $format instanceof WritableWorldProviderManagerEntry
1043 ){
1044 $providerManager->setDefault($format);
1045 }elseif($formatName !== ""){
1046 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_level_badDefaultFormat($formatName)));
1047 }
1048
1049 $this->worldManager = new WorldManager($this, Path::join($this->dataPath, "worlds"), $providerManager);
1050 $this->worldManager->setAutoSave($this->configGroup->getConfigBool(ServerProperties::AUTO_SAVE, $this->worldManager->getAutoSave()));
1051 $this->worldManager->setAutoSaveInterval($this->configGroup->getPropertyInt(Yml::TICKS_PER_AUTOSAVE, $this->worldManager->getAutoSaveInterval()));
1052
1053 $this->updater = new UpdateChecker($this, $this->configGroup->getPropertyString(Yml::AUTO_UPDATER_HOST, "update.pmmp.io"));
1054
1055 $this->queryInfo = new QueryInfo($this);
1056
1057 $this->playerDataProvider = new DatFilePlayerDataProvider(Path::join($this->dataPath, "players"));
1058
1059 register_shutdown_function($this->crashDump(...));
1060
1061 $loadErrorCount = 0;
1062 $this->pluginManager->loadPlugins($this->pluginPath, $loadErrorCount);
1063 if($loadErrorCount > 0){
1064 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someLoadErrors()));
1065 $this->forceShutdownExit();
1066 return;
1067 }
1068 if(!$this->enablePlugins(PluginEnableOrder::STARTUP)){
1069 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1070 $this->forceShutdownExit();
1071 return;
1072 }
1073
1074 if(!$this->startupPrepareWorlds()){
1075 $this->forceShutdownExit();
1076 return;
1077 }
1078
1079 if(!$this->enablePlugins(PluginEnableOrder::POSTWORLD)){
1080 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1081 $this->forceShutdownExit();
1082 return;
1083 }
1084
1085 if(!$this->startupPrepareNetworkInterfaces()){
1086 $this->forceShutdownExit();
1087 return;
1088 }
1089
1090 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED, true)){
1091 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1092 $this->sendUsage(SendUsageTask::TYPE_OPEN);
1093 }
1094
1095 $this->configGroup->save();
1096
1097 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_defaultGameMode($this->getGamemode()->getTranslatableName())));
1098 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_donate(TextFormat::AQUA . "https://patreon.com/pocketminemp" . TextFormat::RESET)));
1099 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_startFinished(strval(round(microtime(true) - $this->startTime, 3)))));
1100
1101 $forwarder = new BroadcastLoggerForwarder($this, $this->logger, $this->language);
1102 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_ADMINISTRATIVE, $forwarder);
1103 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_USERS, $forwarder);
1104
1105 //TODO: move console parts to a separate component
1106 if($this->configGroup->getPropertyBool(Yml::CONSOLE_ENABLE_INPUT, true)){
1107 $this->console = new ConsoleReaderChildProcessDaemon($this->logger);
1108 }
1109
1110 $this->tickProcessor();
1111 $this->forceShutdown();
1112 }catch(\Throwable $e){
1113 $this->exceptionHandler($e);
1114 }
1115 }
1116
1117 private function startupPrepareWorlds() : bool{
1118 $getGenerator = function(string $generatorName, string $generatorOptions, string $worldName) : ?string{
1119 $generatorEntry = GeneratorManager::getInstance()->getGenerator($generatorName);
1120 if($generatorEntry === null){
1121 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1122 $worldName,
1123 KnownTranslationFactory::pocketmine_level_unknownGenerator($generatorName)
1124 )));
1125 return null;
1126 }
1127 try{
1128 $generatorEntry->validateGeneratorOptions($generatorOptions);
1129 }catch(InvalidGeneratorOptionsException $e){
1130 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1131 $worldName,
1132 KnownTranslationFactory::pocketmine_level_invalidGeneratorOptions($generatorOptions, $generatorName, $e->getMessage())
1133 )));
1134 return null;
1135 }
1136 return $generatorEntry->getGeneratorClass();
1137 };
1138
1139 $anyWorldFailedToLoad = false;
1140
1141 foreach(Utils::promoteKeys((array) $this->configGroup->getProperty(Yml::WORLDS, [])) as $name => $options){
1142 if(!is_string($name)){
1143 //TODO: this probably should be an error
1144 continue;
1145 }
1146 if($options === null){
1147 $options = [];
1148 }elseif(!is_array($options)){
1149 //TODO: this probably should be an error
1150 continue;
1151 }
1152 if(!$this->worldManager->loadWorld($name, true)){
1153 if($this->worldManager->isWorldGenerated($name)){
1154 //allow checking if other worlds are loadable, so the user gets all the errors in one go
1155 $anyWorldFailedToLoad = true;
1156 continue;
1157 }
1158 $creationOptions = WorldCreationOptions::create();
1159 //TODO: error checking
1160
1161 $generatorName = $options["generator"] ?? "default";
1162 $generatorOptions = isset($options["preset"]) && is_string($options["preset"]) ? $options["preset"] : "";
1163
1164 $generatorClass = $getGenerator($generatorName, $generatorOptions, $name);
1165 if($generatorClass === null){
1166 $anyWorldFailedToLoad = true;
1167 continue;
1168 }
1169 $creationOptions->setGeneratorClass($generatorClass);
1170 $creationOptions->setGeneratorOptions($generatorOptions);
1171
1172 $creationOptions->setDifficulty($this->getDifficulty());
1173 if(isset($options["difficulty"]) && is_string($options["difficulty"])){
1174 $creationOptions->setDifficulty(World::getDifficultyFromString($options["difficulty"]));
1175 }
1176
1177 if(isset($options["seed"])){
1178 $convertedSeed = Generator::convertSeed((string) ($options["seed"] ?? ""));
1179 if($convertedSeed !== null){
1180 $creationOptions->setSeed($convertedSeed);
1181 }
1182 }
1183
1184 $this->worldManager->generateWorld($name, $creationOptions);
1185 }
1186 }
1187
1188 if($this->worldManager->getDefaultWorld() === null){
1189 $default = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_NAME, "world");
1190 if(trim($default) === ""){
1191 $this->logger->warning("level-name cannot be null, using default");
1192 $default = "world";
1193 $this->configGroup->setConfigString(ServerProperties::DEFAULT_WORLD_NAME, "world");
1194 }
1195 if(!$this->worldManager->loadWorld($default, true)){
1196 if($this->worldManager->isWorldGenerated($default)){
1197 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1198
1199 return false;
1200 }
1201 $generatorName = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR);
1202 $generatorOptions = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS);
1203 $generatorClass = $getGenerator($generatorName, $generatorOptions, $default);
1204
1205 if($generatorClass === null){
1206 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1207 return false;
1208 }
1209 $creationOptions = WorldCreationOptions::create()
1210 ->setGeneratorClass($generatorClass)
1211 ->setGeneratorOptions($generatorOptions);
1212 $convertedSeed = Generator::convertSeed($this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_SEED));
1213 if($convertedSeed !== null){
1214 $creationOptions->setSeed($convertedSeed);
1215 }
1216 $creationOptions->setDifficulty($this->getDifficulty());
1217 $this->worldManager->generateWorld($default, $creationOptions);
1218 }
1219
1220 $world = $this->worldManager->getWorldByName($default);
1221 if($world === null){
1222 throw new AssumptionFailedError("We just loaded/generated the default world, so it must exist");
1223 }
1224 $this->worldManager->setDefaultWorld($world);
1225 }
1226
1227 return !$anyWorldFailedToLoad;
1228 }
1229
1230 private function startupPrepareConnectableNetworkInterfaces(
1231 string $ip,
1232 int $port,
1233 bool $ipV6,
1234 bool $useQuery,
1235 PacketBroadcaster $packetBroadcaster,
1236 EntityEventBroadcaster $entityEventBroadcaster,
1237 TypeConverter $typeConverter
1238 ) : bool{
1239 $prettyIp = $ipV6 ? "[$ip]" : $ip;
1240 try{
1241 $rakLibRegistered = $this->network->registerInterface(new RakLibInterface($this, $ip, $port, $ipV6, $packetBroadcaster, $entityEventBroadcaster, $typeConverter));
1242 }catch(NetworkInterfaceStartException $e){
1243 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStartFailed(
1244 $ip,
1245 (string) $port,
1246 $e->getMessage()
1247 )));
1248 return false;
1249 }
1250 if($rakLibRegistered){
1251 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStart($prettyIp, (string) $port)));
1252 }
1253 if($useQuery){
1254 if(!$rakLibRegistered){
1255 //RakLib would normally handle the transport for Query packets
1256 //if it's not registered we need to make sure Query still works
1257 $this->network->registerInterface(new DedicatedQueryNetworkInterface($ip, $port, $ipV6, new \PrefixedLogger($this->logger, "Dedicated Query Interface")));
1258 }
1259 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_query_running($prettyIp, (string) $port)));
1260 }
1261 return true;
1262 }
1263
1264 private function startupPrepareNetworkInterfaces() : bool{
1265 $useQuery = $this->configGroup->getConfigBool(ServerProperties::ENABLE_QUERY, true);
1266
1267 $typeConverter = TypeConverter::getInstance();
1268 $packetBroadcaster = new StandardPacketBroadcaster($this);
1269 $entityEventBroadcaster = new StandardEntityEventBroadcaster($packetBroadcaster, $typeConverter);
1270
1271 if(
1272 !$this->startupPrepareConnectableNetworkInterfaces($this->getIp(), $this->getPort(), false, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter) ||
1273 (
1274 $this->configGroup->getConfigBool(ServerProperties::ENABLE_IPV6, true) &&
1275 !$this->startupPrepareConnectableNetworkInterfaces($this->getIpV6(), $this->getPortV6(), true, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter)
1276 )
1277 ){
1278 return false;
1279 }
1280
1281 if($useQuery){
1282 $this->network->registerRawPacketHandler(new QueryHandler($this));
1283 }
1284
1285 foreach($this->getIPBans()->getEntries() as $entry){
1286 $this->network->blockAddress($entry->getName(), -1);
1287 }
1288
1289 if($this->configGroup->getPropertyBool(Yml::NETWORK_UPNP_FORWARDING, false)){
1290 $this->network->registerInterface(new UPnPNetworkInterface($this->logger, Internet::getInternalIP(), $this->getPort()));
1291 }
1292
1293 return true;
1294 }
1295
1300 public function subscribeToBroadcastChannel(string $channelId, CommandSender $subscriber) : void{
1301 $this->broadcastSubscribers[$channelId][spl_object_id($subscriber)] = $subscriber;
1302 }
1303
1307 public function unsubscribeFromBroadcastChannel(string $channelId, CommandSender $subscriber) : void{
1308 if(isset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)])){
1309 if(count($this->broadcastSubscribers[$channelId]) === 1){
1310 unset($this->broadcastSubscribers[$channelId]);
1311 }else{
1312 unset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)]);
1313 }
1314 }
1315 }
1316
1320 public function unsubscribeFromAllBroadcastChannels(CommandSender $subscriber) : void{
1321 foreach(Utils::stringifyKeys($this->broadcastSubscribers) as $channelId => $recipients){
1322 $this->unsubscribeFromBroadcastChannel($channelId, $subscriber);
1323 }
1324 }
1325
1332 public function getBroadcastChannelSubscribers(string $channelId) : array{
1333 return $this->broadcastSubscribers[$channelId] ?? [];
1334 }
1335
1339 public function broadcastMessage(Translatable|string $message, ?array $recipients = null) : int{
1340 $recipients = $recipients ?? $this->getBroadcastChannelSubscribers(self::BROADCAST_CHANNEL_USERS);
1341
1342 foreach($recipients as $recipient){
1343 $recipient->sendMessage($message);
1344 }
1345
1346 return count($recipients);
1347 }
1348
1352 private function getPlayerBroadcastSubscribers(string $channelId) : array{
1354 $players = [];
1355 foreach($this->broadcastSubscribers[$channelId] as $subscriber){
1356 if($subscriber instanceof Player){
1357 $players[spl_object_id($subscriber)] = $subscriber;
1358 }
1359 }
1360 return $players;
1361 }
1362
1366 public function broadcastTip(string $tip, ?array $recipients = null) : int{
1367 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1368
1369 foreach($recipients as $recipient){
1370 $recipient->sendTip($tip);
1371 }
1372
1373 return count($recipients);
1374 }
1375
1379 public function broadcastPopup(string $popup, ?array $recipients = null) : int{
1380 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1381
1382 foreach($recipients as $recipient){
1383 $recipient->sendPopup($popup);
1384 }
1385
1386 return count($recipients);
1387 }
1388
1395 public function broadcastTitle(string $title, string $subtitle = "", int $fadeIn = -1, int $stay = -1, int $fadeOut = -1, ?array $recipients = null) : int{
1396 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1397
1398 foreach($recipients as $recipient){
1399 $recipient->sendTitle($title, $subtitle, $fadeIn, $stay, $fadeOut);
1400 }
1401
1402 return count($recipients);
1403 }
1404
1418 public function prepareBatch(string $buffer, Compressor $compressor, ?bool $sync = null, ?TimingsHandler $timings = null) : CompressBatchPromise|string{
1419 $timings ??= Timings::$playerNetworkSendCompress;
1420 try{
1421 $timings->startTiming();
1422
1423 $threshold = $compressor->getCompressionThreshold();
1424 if($threshold === null || strlen($buffer) < $compressor->getCompressionThreshold()){
1425 $compressionType = CompressionAlgorithm::NONE;
1426 $compressed = $buffer;
1427
1428 }else{
1429 $sync ??= !$this->networkCompressionAsync;
1430
1431 if(!$sync && strlen($buffer) >= $this->networkCompressionAsyncThreshold){
1432 $promise = new CompressBatchPromise();
1433 $task = new CompressBatchTask($buffer, $promise, $compressor);
1434 $this->asyncPool->submitTask($task);
1435 return $promise;
1436 }
1437
1438 $compressionType = $compressor->getNetworkId();
1439 $compressed = $compressor->compress($buffer);
1440 }
1441
1442 return chr($compressionType) . $compressed;
1443 }finally{
1444 $timings->stopTiming();
1445 }
1446 }
1447
1448 public function enablePlugins(PluginEnableOrder $type) : bool{
1449 $allSuccess = true;
1450 foreach($this->pluginManager->getPlugins() as $plugin){
1451 if(!$plugin->isEnabled() && $plugin->getDescription()->getOrder() === $type){
1452 if(!$this->pluginManager->enablePlugin($plugin)){
1453 $allSuccess = false;
1454 }
1455 }
1456 }
1457
1458 if($type === PluginEnableOrder::POSTWORLD){
1459 $this->commandMap->registerServerAliases();
1460 }
1461
1462 return $allSuccess;
1463 }
1464
1468 public function dispatchCommand(CommandSender $sender, string $commandLine, bool $internal = false) : bool{
1469 if(!$internal){
1470 $ev = new CommandEvent($sender, $commandLine);
1471 $ev->call();
1472 if($ev->isCancelled()){
1473 return false;
1474 }
1475
1476 $commandLine = $ev->getCommand();
1477 }
1478
1479 return $this->commandMap->dispatch($sender, $commandLine);
1480 }
1481
1485 public function shutdown() : void{
1486 if($this->isRunning){
1487 $this->isRunning = false;
1488 $this->signalHandler->unregister();
1489 }
1490 }
1491
1492 private function forceShutdownExit() : void{
1493 $this->forceShutdown();
1494 Process::kill(Process::pid());
1495 }
1496
1497 public function forceShutdown() : void{
1498 if($this->hasStopped){
1499 return;
1500 }
1501
1502 if($this->doTitleTick){
1503 echo "\x1b]0;\x07";
1504 }
1505
1506 if($this->isRunning){
1507 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_forcingShutdown()));
1508 }
1509 try{
1510 if(!$this->isRunning()){
1511 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1512 }
1513
1514 $this->hasStopped = true;
1515
1516 $this->shutdown();
1517
1518 if(isset($this->pluginManager)){
1519 $this->logger->debug("Disabling all plugins");
1520 $this->pluginManager->disablePlugins();
1521 }
1522
1523 if(isset($this->network)){
1524 $this->network->getSessionManager()->close($this->configGroup->getPropertyString(Yml::SETTINGS_SHUTDOWN_MESSAGE, "Server closed"));
1525 }
1526
1527 if(isset($this->worldManager)){
1528 $this->logger->debug("Unloading all worlds");
1529 foreach($this->worldManager->getWorlds() as $world){
1530 $this->worldManager->unloadWorld($world, true);
1531 }
1532 }
1533
1534 $this->logger->debug("Removing event handlers");
1535 HandlerListManager::global()->unregisterAll();
1536
1537 if(isset($this->asyncPool)){
1538 $this->logger->debug("Shutting down async task worker pool");
1539 $this->asyncPool->shutdown();
1540 }
1541
1542 if(isset($this->configGroup)){
1543 $this->logger->debug("Saving properties");
1544 $this->configGroup->save();
1545 }
1546
1547 if($this->console !== null){
1548 $this->logger->debug("Closing console");
1549 $this->console->quit();
1550 }
1551
1552 if(isset($this->network)){
1553 $this->logger->debug("Stopping network interfaces");
1554 foreach($this->network->getInterfaces() as $interface){
1555 $this->logger->debug("Stopping network interface " . get_class($interface));
1556 $this->network->unregisterInterface($interface);
1557 }
1558 }
1559 }catch(\Throwable $e){
1560 $this->logger->logException($e);
1561 $this->logger->emergency("Crashed while crashing, killing process");
1562 @Process::kill(Process::pid());
1563 }
1564
1565 }
1566
1567 public function getQueryInformation() : QueryInfo{
1568 return $this->queryInfo;
1569 }
1570
1575 public function exceptionHandler(\Throwable $e, ?array $trace = null) : void{
1576 while(@ob_end_flush()){}
1577 global $lastError;
1578
1579 if($trace === null){
1580 $trace = $e->getTrace();
1581 }
1582
1583 //If this is a thread crash, this logs where the exception came from on the main thread, as opposed to the
1584 //crashed thread. This is intentional, and might be useful for debugging
1585 //Assume that the thread already logged the original exception with the correct stack trace
1586 $this->logger->logException($e, $trace);
1587
1588 if($e instanceof ThreadCrashException){
1589 $info = $e->getCrashInfo();
1590 $type = $info->getType();
1591 $errstr = $info->getMessage();
1592 $errfile = $info->getFile();
1593 $errline = $info->getLine();
1594 $printableTrace = $info->getTrace();
1595 $thread = $info->getThreadName();
1596 }else{
1597 $type = get_class($e);
1598 $errstr = $e->getMessage();
1599 $errfile = $e->getFile();
1600 $errline = $e->getLine();
1601 $printableTrace = Utils::printableTraceWithMetadata($trace);
1602 $thread = "Main";
1603 }
1604
1605 $errstr = preg_replace('/\s+/', ' ', trim($errstr));
1606
1607 $lastError = [
1608 "type" => $type,
1609 "message" => $errstr,
1610 "fullFile" => $errfile,
1611 "file" => Filesystem::cleanPath($errfile),
1612 "line" => $errline,
1613 "trace" => $printableTrace,
1614 "thread" => $thread
1615 ];
1616
1617 global $lastExceptionError, $lastError;
1618 $lastExceptionError = $lastError;
1619 $this->crashDump();
1620 }
1621
1622 private function writeCrashDumpFile(CrashDump $dump) : string{
1623 $crashFolder = Path::join($this->dataPath, "crashdumps");
1624 if(!is_dir($crashFolder)){
1625 mkdir($crashFolder);
1626 }
1627 $crashDumpPath = Path::join($crashFolder, date("D_M_j-H.i.s-T_Y", (int) $dump->getData()->time) . ".log");
1628
1629 $fp = @fopen($crashDumpPath, "wb");
1630 if(!is_resource($fp)){
1631 throw new \RuntimeException("Unable to open new file to generate crashdump");
1632 }
1633 $writer = new CrashDumpRenderer($fp, $dump->getData());
1634 $writer->renderHumanReadable();
1635 $dump->encodeData($writer);
1636
1637 fclose($fp);
1638 return $crashDumpPath;
1639 }
1640
1641 public function crashDump() : void{
1642 while(@ob_end_flush()){}
1643 if(!$this->isRunning){
1644 return;
1645 }
1646 if($this->sendUsageTicker > 0){
1647 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1648 }
1649 $this->hasStopped = false;
1650
1651 ini_set("error_reporting", '0');
1652 ini_set("memory_limit", '-1'); //Fix error dump not dumped on memory problems
1653 try{
1654 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_create()));
1655 $dump = new CrashDump($this, $this->pluginManager ?? null);
1656
1657 $crashDumpPath = $this->writeCrashDumpFile($dump);
1658
1659 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_submit($crashDumpPath)));
1660
1661 if($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_ENABLED, true)){
1662 $report = true;
1663
1664 $stamp = Path::join($this->dataPath, "crashdumps", ".last_crash");
1665 $crashInterval = 120; //2 minutes
1666 if(($lastReportTime = @filemtime($stamp)) !== false && $lastReportTime + $crashInterval >= time()){
1667 $report = false;
1668 $this->logger->debug("Not sending crashdump due to last crash less than $crashInterval seconds ago");
1669 }
1670 @touch($stamp); //update file timestamp
1671
1672 if($dump->getData()->error["type"] === \ParseError::class){
1673 $report = false;
1674 }
1675
1676 if(strrpos(VersionInfo::GIT_HASH(), "-dirty") !== false || VersionInfo::GIT_HASH() === str_repeat("00", 20)){
1677 $this->logger->debug("Not sending crashdump due to locally modified");
1678 $report = false; //Don't send crashdumps for locally modified builds
1679 }
1680
1681 if($report){
1682 $url = ($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_USE_HTTPS, true) ? "https" : "http") . "://" . $this->configGroup->getPropertyString(Yml::AUTO_REPORT_HOST, "crash.pmmp.io") . "/submit/api";
1683 $postUrlError = "Unknown error";
1684 $reply = Internet::postURL($url, [
1685 "report" => "yes",
1686 "name" => $this->getName() . " " . $this->getPocketMineVersion(),
1687 "email" => "[email protected]",
1688 "reportPaste" => base64_encode($dump->getEncodedData())
1689 ], 10, [], $postUrlError);
1690
1691 if($reply !== null && is_object($data = json_decode($reply->getBody()))){
1692 if(isset($data->crashId) && is_int($data->crashId) && isset($data->crashUrl) && is_string($data->crashUrl)){
1693 $reportId = $data->crashId;
1694 $reportUrl = $data->crashUrl;
1695 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_archive($reportUrl, (string) $reportId)));
1696 }elseif(isset($data->error) && is_string($data->error)){
1697 $this->logger->emergency("Automatic crash report submission failed: $data->error");
1698 }else{
1699 $this->logger->emergency("Invalid JSON response received from crash archive: " . $reply->getBody());
1700 }
1701 }else{
1702 $this->logger->emergency("Failed to communicate with crash archive: $postUrlError");
1703 }
1704 }
1705 }
1706 }catch(\Throwable $e){
1707 $this->logger->logException($e);
1708 try{
1709 $this->logger->critical($this->language->translate(KnownTranslationFactory::pocketmine_crash_error($e->getMessage())));
1710 }catch(\Throwable $e){}
1711 }
1712
1713 $this->forceShutdown();
1714 $this->isRunning = false;
1715
1716 //Force minimum uptime to be >= 120 seconds, to reduce the impact of spammy crash loops
1717 $uptime = time() - ((int) $this->startTime);
1718 $minUptime = 120;
1719 $spacing = $minUptime - $uptime;
1720 if($spacing > 0){
1721 echo "--- Uptime {$uptime}s - waiting {$spacing}s to throttle automatic restart (you can kill the process safely now) ---" . PHP_EOL;
1722 sleep($spacing);
1723 }
1724 @Process::kill(Process::pid());
1725 exit(1);
1726 }
1727
1731 public function __debugInfo() : array{
1732 return [];
1733 }
1734
1735 public function getTickSleeper() : SleeperHandler{
1736 return $this->tickSleeper;
1737 }
1738
1739 private function tickProcessor() : void{
1740 $this->nextTick = microtime(true);
1741
1742 while($this->isRunning){
1743 $this->tick();
1744
1745 //sleeps are self-correcting - if we undersleep 1ms on this tick, we'll sleep an extra ms on the next tick
1746 $this->tickSleeper->sleepUntil($this->nextTick);
1747 }
1748 }
1749
1750 public function addOnlinePlayer(Player $player) : bool{
1751 $ev = new PlayerLoginEvent($player, "Plugin reason");
1752 $ev->call();
1753 if($ev->isCancelled() || !$player->isConnected()){
1754 $player->disconnect($ev->getKickMessage());
1755
1756 return false;
1757 }
1758
1759 $session = $player->getNetworkSession();
1760 $position = $player->getPosition();
1761 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_player_logIn(
1762 TextFormat::AQUA . $player->getName() . TextFormat::RESET,
1763 $session->getIp(),
1764 (string) $session->getPort(),
1765 (string) $player->getId(),
1766 $position->getWorld()->getDisplayName(),
1767 (string) round($position->x, 4),
1768 (string) round($position->y, 4),
1769 (string) round($position->z, 4)
1770 )));
1771
1772 foreach($this->playerList as $p){
1773 $p->getNetworkSession()->onPlayerAdded($player);
1774 }
1775 $rawUUID = $player->getUniqueId()->getBytes();
1776 $this->playerList[$rawUUID] = $player;
1777
1778 if($this->sendUsageTicker > 0){
1779 $this->uniquePlayers[$rawUUID] = $rawUUID;
1780 }
1781
1782 return true;
1783 }
1784
1785 public function removeOnlinePlayer(Player $player) : void{
1786 if(isset($this->playerList[$rawUUID = $player->getUniqueId()->getBytes()])){
1787 unset($this->playerList[$rawUUID]);
1788 foreach($this->playerList as $p){
1789 $p->getNetworkSession()->onPlayerRemoved($player);
1790 }
1791 }
1792 }
1793
1794 public function sendUsage(int $type = SendUsageTask::TYPE_STATUS) : void{
1795 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED, true)){
1796 $this->asyncPool->submitTask(new SendUsageTask($this, $type, $this->uniquePlayers));
1797 }
1798 $this->uniquePlayers = [];
1799 }
1800
1801 public function getLanguage() : Language{
1802 return $this->language;
1803 }
1804
1805 public function isLanguageForced() : bool{
1806 return $this->forceLanguage;
1807 }
1808
1809 public function getNetwork() : Network{
1810 return $this->network;
1811 }
1812
1813 public function getMemoryManager() : MemoryManager{
1814 return $this->memoryManager;
1815 }
1816
1817 private function titleTick() : void{
1818 Timings::$titleTick->startTiming();
1819
1820 $u = Process::getAdvancedMemoryUsage();
1821 $usage = sprintf("%g/%g/%g MB @ %d threads", round(($u[0] / 1024) / 1024, 2), round(($u[1] / 1024) / 1024, 2), round(($u[2] / 1024) / 1024, 2), Process::getThreadCount());
1822
1823 $online = count($this->playerList);
1824 $connecting = $this->network->getConnectionCount() - $online;
1825 $bandwidthStats = $this->network->getBandwidthTracker();
1826
1827 echo "\x1b]0;" . $this->getName() . " " .
1828 $this->getPocketMineVersion() .
1829 " | Online $online/" . $this->maxPlayers .
1830 ($connecting > 0 ? " (+$connecting connecting)" : "") .
1831 " | Memory " . $usage .
1832 " | U " . round($bandwidthStats->getSend()->getAverageBytes() / 1024, 2) .
1833 " D " . round($bandwidthStats->getReceive()->getAverageBytes() / 1024, 2) .
1834 " kB/s | TPS " . $this->getTicksPerSecondAverage() .
1835 " | Load " . $this->getTickUsageAverage() . "%\x07";
1836
1837 Timings::$titleTick->stopTiming();
1838 }
1839
1843 private function tick() : void{
1844 $tickTime = microtime(true);
1845 if(($tickTime - $this->nextTick) < -0.025){ //Allow half a tick of diff
1846 return;
1847 }
1848
1849 Timings::$serverTick->startTiming();
1850
1851 ++$this->tickCounter;
1852
1853 Timings::$scheduler->startTiming();
1854 $this->pluginManager->tickSchedulers($this->tickCounter);
1855 Timings::$scheduler->stopTiming();
1856
1857 Timings::$schedulerAsync->startTiming();
1858 $this->asyncPool->collectTasks();
1859 Timings::$schedulerAsync->stopTiming();
1860
1861 $this->worldManager->tick($this->tickCounter);
1862
1863 Timings::$connection->startTiming();
1864 $this->network->tick();
1865 Timings::$connection->stopTiming();
1866
1867 if(($this->tickCounter % self::TARGET_TICKS_PER_SECOND) === 0){
1868 if($this->doTitleTick){
1869 $this->titleTick();
1870 }
1871 $this->currentTPS = self::TARGET_TICKS_PER_SECOND;
1872 $this->currentUse = 0;
1873
1874 $queryRegenerateEvent = new QueryRegenerateEvent(new QueryInfo($this));
1875 $queryRegenerateEvent->call();
1876 $this->queryInfo = $queryRegenerateEvent->getQueryInfo();
1877
1878 $this->network->updateName();
1879 $this->network->getBandwidthTracker()->rotateAverageHistory();
1880 }
1881
1882 if($this->sendUsageTicker > 0 && --$this->sendUsageTicker === 0){
1883 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1884 $this->sendUsage(SendUsageTask::TYPE_STATUS);
1885 }
1886
1887 if(($this->tickCounter % self::TICKS_PER_WORLD_CACHE_CLEAR) === 0){
1888 foreach($this->worldManager->getWorlds() as $world){
1889 $world->clearCache();
1890 }
1891 }
1892
1893 if(($this->tickCounter % self::TICKS_PER_TPS_OVERLOAD_WARNING) === 0 && $this->getTicksPerSecondAverage() < self::TPS_OVERLOAD_WARNING_THRESHOLD){
1894 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_tickOverload()));
1895 }
1896
1897 $this->memoryManager->check();
1898
1899 if($this->console !== null){
1900 Timings::$serverCommand->startTiming();
1901 while(($line = $this->console->readLine()) !== null){
1902 $this->consoleSender ??= new ConsoleCommandSender($this, $this->language);
1903 $this->dispatchCommand($this->consoleSender, $line);
1904 }
1905 Timings::$serverCommand->stopTiming();
1906 }
1907
1908 Timings::$serverTick->stopTiming();
1909
1910 $now = microtime(true);
1911 $totalTickTimeSeconds = $now - $tickTime + ($this->tickSleeper->getNotificationProcessingTime() / 1_000_000_000);
1912 $this->currentTPS = min(self::TARGET_TICKS_PER_SECOND, 1 / max(0.001, $totalTickTimeSeconds));
1913 $this->currentUse = min(1, $totalTickTimeSeconds / self::TARGET_SECONDS_PER_TICK);
1914
1915 TimingsHandler::tick($this->currentTPS <= $this->profilingTickRate);
1916
1917 $idx = $this->tickCounter % self::TARGET_TICKS_PER_SECOND;
1918 $this->tickAverage[$idx] = $this->currentTPS;
1919 $this->useAverage[$idx] = $this->currentUse;
1920 $this->tickSleeper->resetNotificationProcessingTime();
1921
1922 if(($this->nextTick - $tickTime) < -1){
1923 $this->nextTick = $tickTime;
1924 }else{
1925 $this->nextTick += self::TARGET_SECONDS_PER_TICK;
1926 }
1927 }
1928}
getBroadcastChannelSubscribers(string $channelId)
unsubscribeFromBroadcastChannel(string $channelId, CommandSender $subscriber)
getPlayerExact(string $name)
exceptionHandler(\Throwable $e, ?array $trace=null)
broadcastTitle(string $title, string $subtitle="", int $fadeIn=-1, int $stay=-1, int $fadeOut=-1, ?array $recipients=null)
getPlayerByUUID(UuidInterface $uuid)
getPlayerByPrefix(string $name)
unsubscribeFromAllBroadcastChannels(CommandSender $subscriber)
hasOfflinePlayerData(string $name)
getPluginCommand(string $name)
dispatchCommand(CommandSender $sender, string $commandLine, bool $internal=false)
getAllowedViewDistance(int $distance)
broadcastMessage(Translatable|string $message, ?array $recipients=null)
createPlayer(NetworkSession $session, PlayerInfo $playerInfo, bool $authenticated, ?CompoundTag $offlinePlayerData)
broadcastPopup(string $popup, ?array $recipients=null)
subscribeToBroadcastChannel(string $channelId, CommandSender $subscriber)
getPlayerByRawUUID(string $rawUUID)
broadcastTip(string $tip, ?array $recipients=null)