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