PocketMine-MP 5.39.3 git-21ae710729750cd637333d673bbbbbc598fc659e
Loading...
Searching...
No Matches
NetworkSession.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
24namespace pocketmine\network\mcpe;
25
26use pmmp\encoding\ByteBufferReader;
27use pmmp\encoding\ByteBufferWriter;
28use pmmp\encoding\DataDecodeException;
56use pocketmine\network\mcpe\handler\PacketHandlerAction;
108use pocketmine\player\GameMode;
111use pocketmine\player\UsedChunkStatus;
124use function array_filter;
125use function array_map;
126use function array_slice;
127use function array_values;
128use function base64_encode;
129use function bin2hex;
130use function count;
131use function get_class;
132use function implode;
133use function is_string;
134use function json_encode;
135use function ord;
136use function random_bytes;
137use function str_split;
138use function strcasecmp;
139use function strlen;
140use function strtolower;
141use function substr;
142use function time;
143use function ucfirst;
144use const JSON_THROW_ON_ERROR;
145
147 private const INCOMING_PACKET_BATCH_PER_TICK = 2; //usually max 1 per tick, but transactions arrive separately
148 private const INCOMING_PACKET_BATCH_BUFFER_TICKS = 100; //enough to account for a 5-second lag spike
149
150 private const INCOMING_GAME_PACKETS_PER_TICK = 2;
151 private const INCOMING_GAME_PACKETS_BUFFER_TICKS = 100;
152
153 private const INCOMING_PACKET_BATCH_HARD_LIMIT = 300;
154
155 private PacketRateLimiter $packetBatchLimiter;
156 private PacketRateLimiter $gamePacketLimiter;
157
158 private \PrefixedLogger $logger;
159 private ?Player $player = null;
160 private ?PlayerInfo $info = null;
161 private ?int $ping = null;
162
163 private ?PacketHandler $handler = null;
168 private ?array $handlerActions = null;
169
170 private bool $connected = true;
171 private bool $disconnectGuard = false;
172 private bool $loggedIn = false;
173 private bool $authenticated = false;
174 private int $connectTime;
175 private ?CompoundTag $cachedOfflinePlayerData = null;
176
177 private ?EncryptionContext $cipher = null;
178
183 private array $sendBuffer = [];
188 private array $sendBufferAckPromises = [];
189
191 private \SplQueue $compressedQueue;
192 private bool $forceAsyncCompression = true;
193 private bool $enableCompression = false; //disabled until handshake completed
194
195 private int $nextAckReceiptId = 0;
200 private array $ackPromisesByReceiptId = [];
201
202 private ?InventoryManager $invManager = null;
203
208 private ObjectSet $disposeHooks;
209
210 private string $noisyPacketBuffer = "";
211 private int $noisyPacketsDropped = 0;
212
213 public function __construct(
214 private Server $server,
215 private NetworkSessionManager $manager,
216 private PacketPool $packetPool,
217 private PacketSender $sender,
218 private PacketBroadcaster $broadcaster,
219 private EntityEventBroadcaster $entityEventBroadcaster,
220 private Compressor $compressor,
221 private TypeConverter $typeConverter,
222 private string $ip,
223 private int $port
224 ){
225 $this->logger = new \PrefixedLogger($this->server->getLogger(), $this->getLogPrefix());
226
227 $this->compressedQueue = new \SplQueue();
228
229 $this->disposeHooks = new ObjectSet();
230
231 $this->connectTime = time();
232 $this->packetBatchLimiter = new PacketRateLimiter("Packet Batches", self::INCOMING_PACKET_BATCH_PER_TICK, self::INCOMING_PACKET_BATCH_BUFFER_TICKS);
233 $this->gamePacketLimiter = new PacketRateLimiter("Game Packets", self::INCOMING_GAME_PACKETS_PER_TICK, self::INCOMING_GAME_PACKETS_BUFFER_TICKS);
234
235 $this->setHandler(new SessionStartPacketHandler(
236 $this,
237 $this->onSessionStartSuccess(...)
238 ));
239
240 $this->manager->add($this);
241 $this->logger->info($this->server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_open()));
242 }
243
244 private function getLogPrefix() : string{
245 return "NetworkSession: " . $this->getDisplayName();
246 }
247
248 public function getLogger() : \Logger{
249 return $this->logger;
250 }
251
252 private function onSessionStartSuccess() : void{
253 $this->logger->debug("Session start handshake completed, awaiting login packet");
254 $this->flushGamePacketQueue();
255 $this->enableCompression = true;
256 $this->setHandler(new LoginPacketHandler(
257 $this->server,
258 $this,
259 function(PlayerInfo $info) : void{
260 $this->info = $info;
261 $this->logger->info($this->server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_playerName(TextFormat::AQUA . $info->getUsername() . TextFormat::RESET)));
262 $this->logger->setPrefix($this->getLogPrefix());
263 $this->manager->markLoginReceived($this);
264 },
265 $this->setAuthenticationStatus(...)
266 ));
267 }
268
269 protected function createPlayer() : void{
270 $this->server->createPlayer($this, $this->info, $this->authenticated, $this->cachedOfflinePlayerData)->onCompletion(
271 $this->onPlayerCreated(...),
272 function() : void{
273 //TODO: this should never actually occur... right?
274 $this->disconnectWithError(
275 reason: "Failed to create player",
276 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_internal()
277 );
278 }
279 );
280 }
281
282 private function onPlayerCreated(Player $player) : void{
283 if(!$this->isConnected()){
284 //the remote player might have disconnected before spawn terrain generation was finished
285 return;
286 }
287 $this->player = $player;
288 if(!$this->server->addOnlinePlayer($player)){
289 return;
290 }
291
292 $this->invManager = new InventoryManager($this->player, $this);
293
294 $effectManager = $this->player->getEffects();
295 $effectManager->getEffectAddHooks()->add($effectAddHook = function(EffectInstance $effect, bool $replacesOldEffect) : void{
296 $this->entityEventBroadcaster->onEntityEffectAdded([$this], $this->player, $effect, $replacesOldEffect);
297 });
298 $effectManager->getEffectRemoveHooks()->add($effectRemoveHook = function(EffectInstance $effect) : void{
299 $this->entityEventBroadcaster->onEntityEffectRemoved([$this], $this->player, $effect);
300 });
301 $this->disposeHooks->add(static function() use ($effectManager, $effectAddHook, $effectRemoveHook) : void{
302 $effectManager->getEffectAddHooks()->remove($effectAddHook);
303 $effectManager->getEffectRemoveHooks()->remove($effectRemoveHook);
304 });
305
306 $permissionHooks = $this->player->getPermissionRecalculationCallbacks();
307 $permissionHooks->add($permHook = function() : void{
308 $this->logger->debug("Syncing available commands and abilities/permissions due to permission recalculation");
309 $this->syncAbilities($this->player);
310 $this->syncAvailableCommands();
311 });
312 $this->disposeHooks->add(static function() use ($permissionHooks, $permHook) : void{
313 $permissionHooks->remove($permHook);
314 });
315 $this->beginSpawnSequence();
316 }
317
318 public function getPlayer() : ?Player{
319 return $this->player;
320 }
321
322 public function getPlayerInfo() : ?PlayerInfo{
323 return $this->info;
324 }
325
326 public function isConnected() : bool{
327 return $this->connected && !$this->disconnectGuard;
328 }
329
330 public function getIp() : string{
331 return $this->ip;
332 }
333
334 public function getPort() : int{
335 return $this->port;
336 }
337
338 public function getDisplayName() : string{
339 return $this->info !== null ? $this->info->getUsername() : $this->ip . " " . $this->port;
340 }
341
345 public function getPing() : ?int{
346 return $this->ping;
347 }
348
352 public function updatePing(int $ping) : void{
353 $this->ping = $ping;
354 }
355
356 public function getHandler() : ?PacketHandler{
357 return $this->handler;
358 }
359
360 public function setHandler(?PacketHandler $handler) : void{
361 if($this->connected){ //TODO: this is fine since we can't handle anything from a disconnected session, but it might produce surprises in some cases
362 $this->handler = $handler;
363 if($this->handler !== null){
364 $this->handlerActions = PacketHandlerInspector::getHandlerActions($this->handler);
365 $this->handler->setUp();
366 }else{
367 $this->handlerActions = null;
368 }
369 }
370 }
371
372 private function checkRepeatedPacketFilter(string $buffer) : bool{
373 if($buffer === $this->noisyPacketBuffer){
374 $this->noisyPacketsDropped++;
375 return true;
376 }
377 //stop filtering once we see a packet with a different buffer
378 //this won't be any good for interleaved spammy packets, but we haven't seen any of those so far, and this
379 //is the simplest and most conservative filter we can do
380 $this->noisyPacketBuffer = "";
381 $this->noisyPacketsDropped = 0;
382
383 return false;
384 }
385
389 public function handleEncoded(string $payload) : void{
390 if(!$this->connected){
391 return;
392 }
393
394 Timings::$playerNetworkReceive->startTiming();
395 try{
396 $this->packetBatchLimiter->decrement();
397
398 if($this->cipher !== null){
399 Timings::$playerNetworkReceiveDecrypt->startTiming();
400 try{
401 $payload = $this->cipher->decrypt($payload);
402 }catch(DecryptionException $e){
403 $this->logger->debug("Encrypted packet: " . base64_encode($payload));
404 throw PacketHandlingException::wrap($e, "Packet decryption error");
405 }finally{
406 Timings::$playerNetworkReceiveDecrypt->stopTiming();
407 }
408 }
409
410 if(strlen($payload) < 1){
411 throw new PacketHandlingException("No bytes in payload");
412 }
413
414 if($this->enableCompression){
415 $compressionType = ord($payload[0]);
416 $compressed = substr($payload, 1);
417 if($compressionType === CompressionAlgorithm::NONE){
418 $decompressed = $compressed;
419 }elseif($compressionType === $this->compressor->getNetworkId()){
420 Timings::$playerNetworkReceiveDecompress->startTiming();
421 try{
422 $decompressed = $this->compressor->decompress($compressed);
423 }catch(DecompressionException $e){
424 $this->logger->debug("Failed to decompress packet: " . base64_encode($compressed));
425 throw PacketHandlingException::wrap($e, "Compressed packet batch decode error");
426 }finally{
427 Timings::$playerNetworkReceiveDecompress->stopTiming();
428 }
429 }else{
430 throw new PacketHandlingException("Packet compressed with unexpected compression type $compressionType");
431 }
432 }else{
433 $decompressed = $payload;
434 }
435
436 $count = 0;
437 try{
438 $stream = new ByteBufferReader($decompressed);
439 foreach(PacketBatch::decodeRaw($stream) as $buffer){
440 if(++$count >= self::INCOMING_PACKET_BATCH_HARD_LIMIT){
441 //this should be well more than enough; under normal conditions the game packet rate limiter
442 //will kick in well before this. This is only here to make sure we can't get huge batches of
443 //noisy packets to bog down the server, since those aren't counted by the regular limiter.
444 throw new PacketHandlingException("Reached hard limit of " . self::INCOMING_PACKET_BATCH_HARD_LIMIT . " per batch packet");
445 }
446
447 if($this->checkRepeatedPacketFilter($buffer)){
448 continue;
449 }
450
451 $this->gamePacketLimiter->decrement();
452 $packet = $this->packetPool->getPacket($buffer);
453 if($packet === null){
454 $this->logger->debug("Unknown packet: " . base64_encode($buffer));
455 throw new PacketHandlingException("Unknown packet received");
456 }
457 try{
458 $this->handleDataPacket($packet, $buffer);
459 }catch(PacketHandlingException $e){
460 $this->logger->debug($packet->getName() . ": " . base64_encode($buffer));
461 throw PacketHandlingException::wrap($e, "Error processing " . $packet->getName());
462 }catch(FilterNoisyPacketException){
463 $this->noisyPacketBuffer = $buffer;
464 }
465 if(!$this->isConnected()){
466 //handling this packet may have caused a disconnection
467 $this->logger->debug("Aborting batch processing due to server-side disconnection");
468 break;
469 }
470 }
471 }catch(PacketDecodeException|DataDecodeException $e){
472 $this->logger->logException($e);
473 throw PacketHandlingException::wrap($e, "Packet batch decode error");
474 }
475 }finally{
476 Timings::$playerNetworkReceive->stopTiming();
477 }
478 }
479
480 private function unhandledPacketDebug(Packet $packet, string $buffer, string $label) : void{
481 $this->logger->debug($label . ": " . $packet->getName() . ": " . base64_encode($buffer));
482 }
483
488 public function handleDataPacket(Packet $packet, string $buffer) : void{
489 if(!($packet instanceof ServerboundPacket)){
490 throw new PacketHandlingException("Unexpected non-serverbound packet");
491 }
492
493 $timings = Timings::getReceiveDataPacketTimings($packet);
494 $timings->startTiming();
495
496 try{
497 $handlerAction = PacketHandlerAction::DISCARD_WITH_DEBUG;
498 //TODO: it would be better to use packet ID and avoid the object allocation, but it's unavoidable for now
499 //because I don't want to copy paste packet header decoding
500 if($this->handlerActions !== null && isset($this->handlerActions[$packet::class])){
501 $handlerAction = $this->handlerActions[$packet::class];
502 }
503 if(DataPacketDecodeEvent::hasHandlers()){
504 $ev = new DataPacketDecodeEvent($this, $packet->pid(), $buffer);
505 $cancel = $handlerAction !== PacketHandlerAction::HANDLED;
506 if($cancel){
507 $ev->cancel();
508 }
509 $ev->call();
510 if($cancel && !$ev->isCancelled()){
511 //uncancelled by a plugin, let it through to DataPacketReceiveEvent
512 $handlerAction = PacketHandlerAction::HANDLED;
513 }elseif(!$cancel && $ev->isCancelled()){
514 //explicitly cancelled by plugin, drop it quietly
515 $handlerAction = PacketHandlerAction::DISCARD_SILENT;
516 }
517 }
518
519 if($handlerAction !== PacketHandlerAction::HANDLED){
520 if($handlerAction === PacketHandlerAction::DISCARD_WITH_DEBUG){
521 $this->unhandledPacketDebug($packet, $buffer, "Discarded without decoding");
522 }
523 return;
524 }
525
526 $decodeTimings = Timings::getDecodeDataPacketTimings($packet);
527 $decodeTimings->startTiming();
528 try{
529 $stream = new ByteBufferReader($buffer);
530 try{
531 $packet->decode($stream);
532 }catch(PacketDecodeException $e){
533 throw PacketHandlingException::wrap($e);
534 }
535 if($stream->getUnreadLength() > 0){
536 $remains = substr($stream->getData(), $stream->getOffset());
537 $this->logger->debug("Still " . strlen($remains) . " bytes unread in " . $packet->getName() . ": " . bin2hex($remains));
538 }
539 }finally{
540 $decodeTimings->stopTiming();
541 }
542
543 if(DataPacketReceiveEvent::hasHandlers()){
544 $ev = new DataPacketReceiveEvent($this, $packet);
545 $ev->call();
546 if($ev->isCancelled()){
547 return;
548 }
549 }
550 $handlerTimings = Timings::getHandleDataPacketTimings($packet);
551 $handlerTimings->startTiming();
552 try{
553 if($this->handler === null || !$packet->handle($this->handler)){
554 $this->unhandledPacketDebug($packet, $buffer, "Handler rejected");
555 }
556 }finally{
557 $handlerTimings->stopTiming();
558 }
559 }finally{
560 $timings->stopTiming();
561 }
562 }
563
564 public function handleAckReceipt(int $receiptId) : void{
565 if(!$this->connected){
566 return;
567 }
568 if(isset($this->ackPromisesByReceiptId[$receiptId])){
569 $promises = $this->ackPromisesByReceiptId[$receiptId];
570 unset($this->ackPromisesByReceiptId[$receiptId]);
571 foreach($promises as $promise){
572 $promise->resolve(true);
573 }
574 }
575 }
576
580 private function sendDataPacketInternal(ClientboundPacket $packet, bool $immediate, ?PromiseResolver $ackReceiptResolver) : bool{
581 if(!$this->connected){
582 return false;
583 }
584 //Basic safety restriction. TODO: improve this
585 if(!$this->loggedIn && !$packet->canBeSentBeforeLogin()){
586 throw new \InvalidArgumentException("Attempted to send " . get_class($packet) . " to " . $this->getDisplayName() . " too early");
587 }
588
589 $timings = Timings::getSendDataPacketTimings($packet);
590 $timings->startTiming();
591 try{
592 if(DataPacketSendEvent::hasHandlers()){
593 $ev = new DataPacketSendEvent([$this], [$packet]);
594 $ev->call();
595 if($ev->isCancelled()){
596 return false;
597 }
598 $packets = $ev->getPackets();
599 }else{
600 $packets = [$packet];
601 }
602
603 if($ackReceiptResolver !== null){
604 $this->sendBufferAckPromises[] = $ackReceiptResolver;
605 }
606 $writer = new ByteBufferWriter();
607 foreach($packets as $evPacket){
608 $writer->clear(); //memory reuse let's gooooo
609 $this->addToSendBuffer(self::encodePacketTimed($writer, $evPacket));
610 }
611 if($immediate){
612 $this->flushGamePacketQueue();
613 }
614
615 return true;
616 }finally{
617 $timings->stopTiming();
618 }
619 }
620
621 public function sendDataPacket(ClientboundPacket $packet, bool $immediate = false) : bool{
622 return $this->sendDataPacketInternal($packet, $immediate, null);
623 }
624
628 public function sendDataPacketWithReceipt(ClientboundPacket $packet, bool $immediate = false) : Promise{
630 $resolver = new PromiseResolver();
631
632 if(!$this->sendDataPacketInternal($packet, $immediate, $resolver)){
633 $resolver->reject();
634 }
635
636 return $resolver->getPromise();
637 }
638
642 public static function encodePacketTimed(ByteBufferWriter $serializer, ClientboundPacket $packet) : string{
643 $timings = Timings::getEncodeDataPacketTimings($packet);
644 $timings->startTiming();
645 try{
646 $packet->encode($serializer);
647 return $serializer->getData();
648 }finally{
649 $timings->stopTiming();
650 }
651 }
652
656 public function addToSendBuffer(string $buffer) : void{
657 $this->sendBuffer[] = $buffer;
658 }
659
660 private function flushGamePacketQueue() : void{
661 if(count($this->sendBuffer) > 0){
662 Timings::$playerNetworkSend->startTiming();
663 try{
664 $syncMode = null; //automatic
665 if($this->forceAsyncCompression){
666 $syncMode = false;
667 }
668
669 $stream = new ByteBufferWriter();
670 PacketBatch::encodeRaw($stream, $this->sendBuffer);
671
672 if($this->enableCompression){
673 $batch = $this->server->prepareBatch($stream->getData(), $this->compressor, $syncMode, Timings::$playerNetworkSendCompressSessionBuffer);
674 }else{
675 $batch = $stream->getData();
676 }
677 $this->sendBuffer = [];
678 $ackPromises = $this->sendBufferAckPromises;
679 $this->sendBufferAckPromises = [];
680 //these packets were already potentially buffered for up to 50ms - make sure the transport layer doesn't
681 //delay them any longer
682 $this->queueCompressedNoGamePacketFlush($batch, networkFlush: true, ackPromises: $ackPromises);
683 }finally{
684 Timings::$playerNetworkSend->stopTiming();
685 }
686 }
687 }
688
689 public function getBroadcaster() : PacketBroadcaster{ return $this->broadcaster; }
690
691 public function getEntityEventBroadcaster() : EntityEventBroadcaster{ return $this->entityEventBroadcaster; }
692
693 public function getCompressor() : Compressor{
694 return $this->compressor;
695 }
696
697 public function getTypeConverter() : TypeConverter{ return $this->typeConverter; }
698
699 public function queueCompressed(CompressBatchPromise|string $payload, bool $immediate = false) : void{
700 Timings::$playerNetworkSend->startTiming();
701 try{
702 //if the next packet causes a flush, avoid unnecessarily flushing twice
703 //however, if the next packet does *not* cause a flush, game packets should be flushed to avoid delays
704 $this->flushGamePacketQueue();
705 $this->queueCompressedNoGamePacketFlush($payload, $immediate);
706 }finally{
707 Timings::$playerNetworkSend->stopTiming();
708 }
709 }
710
716 private function queueCompressedNoGamePacketFlush(CompressBatchPromise|string $batch, bool $networkFlush = false, array $ackPromises = []) : void{
717 Timings::$playerNetworkSend->startTiming();
718 try{
719 $this->compressedQueue->enqueue([$batch, $ackPromises, $networkFlush]);
720 if(is_string($batch)){
721 $this->flushCompressedQueue();
722 }else{
723 $batch->onResolve(function() : void{
724 if($this->connected){
725 $this->flushCompressedQueue();
726 }
727 });
728 }
729 }finally{
730 Timings::$playerNetworkSend->stopTiming();
731 }
732 }
733
734 private function flushCompressedQueue() : void{
735 Timings::$playerNetworkSend->startTiming();
736 try{
737 while(!$this->compressedQueue->isEmpty()){
739 [$current, $ackPromises, $networkFlush] = $this->compressedQueue->bottom();
740 if(is_string($current)){
741 $this->compressedQueue->dequeue();
742 $this->sendEncoded($current, $networkFlush, $ackPromises);
743
744 }elseif($current->hasResult()){
745 $this->compressedQueue->dequeue();
746 $this->sendEncoded($current->getResult(), $networkFlush, $ackPromises);
747
748 }else{
749 //can't send any more queued until this one is ready
750 break;
751 }
752 }
753 }finally{
754 Timings::$playerNetworkSend->stopTiming();
755 }
756 }
757
762 private function sendEncoded(string $payload, bool $immediate, array $ackPromises) : void{
763 if($this->cipher !== null){
764 Timings::$playerNetworkSendEncrypt->startTiming();
765 $payload = $this->cipher->encrypt($payload);
766 Timings::$playerNetworkSendEncrypt->stopTiming();
767 }
768
769 if(count($ackPromises) > 0){
770 $ackReceiptId = $this->nextAckReceiptId++;
771 $this->ackPromisesByReceiptId[$ackReceiptId] = $ackPromises;
772 }else{
773 $ackReceiptId = null;
774 }
775 $this->sender->send($payload, $immediate, $ackReceiptId);
776 }
777
781 private function tryDisconnect(\Closure $func, Translatable|string $reason) : void{
782 if($this->connected && !$this->disconnectGuard){
783 $this->disconnectGuard = true;
784 $func();
785 $this->disconnectGuard = false;
786 $this->flushGamePacketQueue();
787 $this->sender->close("");
788 foreach($this->disposeHooks as $callback){
789 $callback();
790 }
791 $this->disposeHooks->clear();
792 $this->setHandler(null);
793 $this->connected = false;
794
795 $ackPromisesByReceiptId = $this->ackPromisesByReceiptId;
796 $this->ackPromisesByReceiptId = [];
797 foreach($ackPromisesByReceiptId as $resolvers){
798 foreach($resolvers as $resolver){
799 $resolver->reject();
800 }
801 }
802 $sendBufferAckPromises = $this->sendBufferAckPromises;
803 $this->sendBufferAckPromises = [];
804 foreach($sendBufferAckPromises as $resolver){
805 $resolver->reject();
806 }
807
808 $this->logger->info($this->server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_close($reason)));
809 }
810 }
811
816 private function dispose() : void{
817 $this->invManager = null;
818 }
819
820 private function sendDisconnectPacket(Translatable|string $message) : void{
821 if($message instanceof Translatable){
822 $translated = $this->server->getLanguage()->translate($message);
823 }else{
824 $translated = $message;
825 }
826 $this->sendDataPacket(DisconnectPacket::create(0, $translated, ""));
827 }
828
835 public function disconnect(Translatable|string $reason, Translatable|string|null $disconnectScreenMessage = null, bool $notify = true) : void{
836 $this->tryDisconnect(function() use ($reason, $disconnectScreenMessage, $notify) : void{
837 if($notify){
838 $this->sendDisconnectPacket($disconnectScreenMessage ?? $reason);
839 }
840 if($this->player !== null){
841 $this->player->onPostDisconnect($reason, null);
842 }
843 }, $reason);
844 }
845
846 public function disconnectWithError(Translatable|string $reason, Translatable|string|null $disconnectScreenMessage = null) : void{
847 $errorId = implode("-", str_split(bin2hex(random_bytes(6)), 4));
848
849 $this->disconnect(
850 reason: KnownTranslationFactory::pocketmine_disconnect_error($reason, $errorId)->prefix(TextFormat::RED),
851 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error($disconnectScreenMessage ?? $reason, $errorId),
852 );
853 }
854
855 public function disconnectIncompatibleProtocol(int $protocolVersion) : void{
856 $this->tryDisconnect(
857 function() use ($protocolVersion) : void{
858 $this->sendDataPacket(PlayStatusPacket::create($protocolVersion < ProtocolInfo::CURRENT_PROTOCOL ? PlayStatusPacket::LOGIN_FAILED_CLIENT : PlayStatusPacket::LOGIN_FAILED_SERVER), true);
859 },
860 KnownTranslationFactory::pocketmine_disconnect_incompatibleProtocol((string) $protocolVersion)
861 );
862 }
863
867 public function transfer(string $ip, int $port, Translatable|string|null $reason = null) : void{
868 $reason ??= KnownTranslationFactory::pocketmine_disconnect_transfer();
869 $this->tryDisconnect(function() use ($ip, $port, $reason) : void{
870 $this->sendDataPacket(TransferPacket::create($ip, $port, false), true);
871 if($this->player !== null){
872 $this->player->onPostDisconnect($reason, null);
873 }
874 }, $reason);
875 }
876
880 public function onPlayerDestroyed(Translatable|string $reason, Translatable|string $disconnectScreenMessage) : void{
881 $this->tryDisconnect(function() use ($disconnectScreenMessage) : void{
882 $this->sendDisconnectPacket($disconnectScreenMessage);
883 }, $reason);
884 }
885
890 public function onClientDisconnect(Translatable|string $reason) : void{
891 $this->tryDisconnect(function() use ($reason) : void{
892 if($this->player !== null){
893 $this->player->onPostDisconnect($reason, null);
894 }
895 }, $reason);
896 }
897
898 private function setAuthenticationStatus(bool $authenticated, bool $authRequired, Translatable|string|null $error, ?string $clientPubKey) : void{
899 if(!$this->connected){
900 return;
901 }
902 if($error === null){
903 if($authenticated && !($this->info instanceof XboxLivePlayerInfo)){
904 $error = "Expected XUID but none found";
905 }elseif($clientPubKey === null){
906 $error = "Missing client public key"; //failsafe
907 }
908 }
909
910 if($error !== null){
911 $this->disconnectWithError(
912 reason: KnownTranslationFactory::pocketmine_disconnect_invalidSession($error),
913 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_authentication()
914 );
915
916 return;
917 }
918
919 $this->authenticated = $authenticated;
920
921 if(!$this->authenticated){
922 if($authRequired){
923 $this->disconnect("Not authenticated", KnownTranslationFactory::disconnectionScreen_notAuthenticated());
924 return;
925 }
926 if($this->info instanceof XboxLivePlayerInfo){
927 $this->logger->warning("Discarding unexpected XUID for non-authenticated player");
928 $this->info = $this->info->withoutXboxData();
929 }
930 }
931 $this->logger->debug("Xbox Live authenticated: " . ($this->authenticated ? "YES" : "NO"));
932
933 $checkXUID = $this->server->getConfigGroup()->getPropertyBool(YmlServerProperties::PLAYER_VERIFY_XUID, true);
934 $myXUID = $this->info instanceof XboxLivePlayerInfo ? $this->info->getXuid() : "";
935 $kickForXUIDMismatch = function(string $xuid) use ($checkXUID, $myXUID) : bool{
936 if($checkXUID && $myXUID !== $xuid){
937 $this->logger->debug("XUID mismatch: expected '$xuid', but got '$myXUID'");
938 //TODO: Longer term, we should be identifying playerdata using something more reliable, like XUID or UUID.
939 //However, that would be a very disruptive change, so this will serve as a stopgap for now.
940 //Side note: this will also prevent offline players hijacking XBL playerdata on online servers, since their
941 //XUID will always be empty.
942 $this->disconnect("XUID does not match (possible impersonation attempt)");
943 return true;
944 }
945 return false;
946 };
947
948 foreach($this->manager->getSessions() as $existingSession){
949 if($existingSession === $this){
950 continue;
951 }
952 $info = $existingSession->getPlayerInfo();
953 if($info !== null && (strcasecmp($info->getUsername(), $this->info->getUsername()) === 0 || $info->getUuid()->equals($this->info->getUuid()))){
954 if($kickForXUIDMismatch($info instanceof XboxLivePlayerInfo ? $info->getXuid() : "")){
955 return;
956 }
957 $ev = new PlayerDuplicateLoginEvent($this, $existingSession, KnownTranslationFactory::disconnectionScreen_loggedinOtherLocation(), null);
958 $ev->call();
959 if($ev->isCancelled()){
960 $this->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
961 return;
962 }
963
964 $existingSession->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
965 }
966 }
967
968 //TODO: make player data loading async
969 //TODO: we shouldn't be loading player data here at all, but right now we don't have any choice :(
970 $this->cachedOfflinePlayerData = $this->server->getOfflinePlayerData($this->info->getUsername());
971 if($checkXUID){
972 $recordedXUID = $this->cachedOfflinePlayerData !== null ? $this->cachedOfflinePlayerData->getTag(Player::TAG_LAST_KNOWN_XUID) : null;
973 if(!($recordedXUID instanceof StringTag)){
974 $this->logger->debug("No previous XUID recorded, no choice but to trust this player");
975 }elseif(!$kickForXUIDMismatch($recordedXUID->getValue())){
976 $this->logger->debug("XUID match");
977 }
978 }
979
980 if(EncryptionContext::$ENABLED){
981 $this->server->getAsyncPool()->submitTask(new PrepareEncryptionTask($clientPubKey, function(string $encryptionKey, string $handshakeJwt) : void{
982 if(!$this->connected){
983 return;
984 }
985 $this->sendDataPacket(ServerToClientHandshakePacket::create($handshakeJwt), true); //make sure this gets sent before encryption is enabled
986
987 $this->cipher = EncryptionContext::fakeGCM($encryptionKey);
988
989 $this->setHandler(new HandshakePacketHandler($this->onServerLoginSuccess(...)));
990 $this->logger->debug("Enabled encryption");
991 }));
992 }else{
993 $this->onServerLoginSuccess();
994 }
995 }
996
997 private function onServerLoginSuccess() : void{
998 $this->loggedIn = true;
999
1000 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::LOGIN_SUCCESS));
1001
1002 $this->logger->debug("Initiating resource packs phase");
1003
1004 $packManager = $this->server->getResourcePackManager();
1005 $resourcePacks = $packManager->getResourceStack();
1006 $keys = [];
1007 foreach($resourcePacks as $resourcePack){
1008 $key = $packManager->getPackEncryptionKey($resourcePack->getPackId());
1009 if($key !== null){
1010 $keys[$resourcePack->getPackId()->toString()] = $key;
1011 }
1012 }
1013 $event = new PlayerResourcePackOfferEvent($this->info, $resourcePacks, $keys, $packManager->resourcePacksRequired());
1014 $event->call();
1015 $this->setHandler(new ResourcePacksPacketHandler($this, $event->getResourcePacks(), $event->getEncryptionKeys(), $event->mustAccept(), function() : void{
1016 $this->createPlayer();
1017 }));
1018 }
1019
1020 private function beginSpawnSequence() : void{
1021 $this->setHandler(new PreSpawnPacketHandler($this->server, $this->player, $this, $this->invManager));
1022 $this->player->setNoClientPredictions(); //TODO: HACK: fix client-side falling pre-spawn
1023
1024 $this->logger->debug("Waiting for chunk radius request");
1025 }
1026
1027 public function notifyTerrainReady() : void{
1028 $this->logger->debug("Sending spawn notification, waiting for spawn response");
1029 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::PLAYER_SPAWN));
1030 $this->setHandler(new SpawnResponsePacketHandler($this->onClientSpawnResponse(...)));
1031 }
1032
1033 private function onClientSpawnResponse() : void{
1034 $this->logger->debug("Received spawn response, entering in-game phase");
1035 $this->player->setNoClientPredictions(false); //TODO: HACK: we set this during the spawn sequence to prevent the client sending junk movements
1036 $this->player->doFirstSpawn();
1037 $this->forceAsyncCompression = false;
1038 $this->setHandler(new InGamePacketHandler($this->player, $this, $this->invManager));
1039 }
1040
1041 public function onServerDeath(Translatable|string $deathMessage) : void{
1042 if($this->handler instanceof InGamePacketHandler){ //TODO: this is a bad fix for pre-spawn death, this shouldn't be reachable at all at this stage :(
1043 $this->setHandler(new DeathPacketHandler($this->player, $this, $this->invManager ?? throw new AssumptionFailedError(), $deathMessage));
1044 }
1045 }
1046
1047 public function onServerRespawn() : void{
1048 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $this->player->getAttributeMap()->getAll());
1049 $this->player->sendData(null);
1050
1051 $this->syncAbilities($this->player);
1052 $this->invManager->syncAll();
1053 $this->setHandler(new InGamePacketHandler($this->player, $this, $this->invManager));
1054 }
1055
1056 public function syncMovement(Vector3 $pos, ?float $yaw = null, ?float $pitch = null, int $mode = MovePlayerPacket::MODE_NORMAL) : void{
1057 if($this->player !== null){
1058 $location = $this->player->getLocation();
1059 $yaw = $yaw ?? $location->getYaw();
1060 $pitch = $pitch ?? $location->getPitch();
1061
1062 $this->sendDataPacket(MovePlayerPacket::simple(
1063 $this->player->getId(),
1064 $this->player->getOffsetPosition($pos),
1065 $pitch,
1066 $yaw,
1067 $yaw, //TODO: head yaw
1068 $mode,
1069 $this->player->onGround,
1070 0, //TODO: riding entity ID
1071 0 //TODO: tick
1072 ));
1073
1074 if($this->handler instanceof InGamePacketHandler){
1075 $this->handler->forceMoveSync = true;
1076 }
1077 }
1078 }
1079
1080 public function syncViewAreaRadius(int $distance) : void{
1081 $this->sendDataPacket(ChunkRadiusUpdatedPacket::create($distance));
1082 }
1083
1084 public function syncViewAreaCenterPoint(Vector3 $newPos, int $viewDistance) : void{
1085 $this->sendDataPacket(NetworkChunkPublisherUpdatePacket::create(BlockPosition::fromVector3($newPos), $viewDistance * 16, [])); //blocks, not chunks >.>
1086 }
1087
1088 public function syncPlayerSpawnPoint(Position $newSpawn) : void{
1089 $newSpawnBlockPosition = BlockPosition::fromVector3($newSpawn);
1090 //TODO: respawn causing block position (bed, respawn anchor)
1091 $this->sendDataPacket(SetSpawnPositionPacket::playerSpawn($newSpawnBlockPosition, DimensionIds::OVERWORLD, $newSpawnBlockPosition));
1092 }
1093
1094 public function syncWorldSpawnPoint(Position $newSpawn) : void{
1095 $this->sendDataPacket(SetSpawnPositionPacket::worldSpawn(BlockPosition::fromVector3($newSpawn), DimensionIds::OVERWORLD));
1096 }
1097
1098 public function syncGameMode(GameMode $mode, bool $isRollback = false) : void{
1099 $this->sendDataPacket(SetPlayerGameTypePacket::create($this->typeConverter->coreGameModeToProtocol($mode)));
1100 if($this->player !== null){
1101 $this->syncAbilities($this->player);
1102 $this->syncAdventureSettings(); //TODO: we might be able to do this with the abilities packet alone
1103 }
1104 if(!$isRollback && $this->invManager !== null){
1105 $this->invManager->syncCreative();
1106 }
1107 }
1108
1109 public function syncAbilities(Player $for) : void{
1110 $isOp = $for->hasPermission(DefaultPermissions::ROOT_OPERATOR);
1111
1112 //ALL of these need to be set for the base layer, otherwise the client will cry
1113 $boolAbilities = [
1114 AbilitiesLayer::ABILITY_ALLOW_FLIGHT => $for->getAllowFlight(),
1115 AbilitiesLayer::ABILITY_FLYING => $for->isFlying(),
1116 AbilitiesLayer::ABILITY_NO_CLIP => !$for->hasBlockCollision(),
1117 AbilitiesLayer::ABILITY_OPERATOR => $isOp,
1118 AbilitiesLayer::ABILITY_TELEPORT => $for->hasPermission(DefaultPermissionNames::COMMAND_TELEPORT_SELF),
1119 AbilitiesLayer::ABILITY_INVULNERABLE => $for->isCreative(),
1120 AbilitiesLayer::ABILITY_MUTED => false,
1121 AbilitiesLayer::ABILITY_WORLD_BUILDER => false,
1122 AbilitiesLayer::ABILITY_INFINITE_RESOURCES => !$for->hasFiniteResources(),
1123 AbilitiesLayer::ABILITY_LIGHTNING => false,
1124 AbilitiesLayer::ABILITY_BUILD => !$for->isSpectator(),
1125 AbilitiesLayer::ABILITY_MINE => !$for->isSpectator(),
1126 AbilitiesLayer::ABILITY_DOORS_AND_SWITCHES => !$for->isSpectator(),
1127 AbilitiesLayer::ABILITY_OPEN_CONTAINERS => !$for->isSpectator(),
1128 AbilitiesLayer::ABILITY_ATTACK_PLAYERS => !$for->isSpectator(),
1129 AbilitiesLayer::ABILITY_ATTACK_MOBS => !$for->isSpectator(),
1130 AbilitiesLayer::ABILITY_PRIVILEGED_BUILDER => false,
1131 ];
1132
1133 $layers = [
1134 new AbilitiesLayer(AbilitiesLayer::LAYER_BASE, $boolAbilities, $for->getFlightSpeedMultiplier(), 1, 0.1),
1135 ];
1136 if(!$for->hasBlockCollision()){
1137 //TODO: HACK! In 1.19.80, the client starts falling in our faux spectator mode when it clips into a
1138 //block. We can't seem to prevent this short of forcing the player to always fly when block collision is
1139 //disabled. Also, for some reason the client always reads flight state from this layer if present, even
1140 //though the player isn't in spectator mode.
1141
1142 $layers[] = new AbilitiesLayer(AbilitiesLayer::LAYER_SPECTATOR, [
1143 AbilitiesLayer::ABILITY_FLYING => true,
1144 ], null, null, null);
1145 }
1146
1147 $this->sendDataPacket(UpdateAbilitiesPacket::create(new AbilitiesData(
1148 $isOp ? CommandPermissions::OPERATOR : CommandPermissions::NORMAL,
1149 $isOp ? PlayerPermissions::OPERATOR : PlayerPermissions::MEMBER,
1150 $for->getId(),
1151 $layers
1152 )));
1153 }
1154
1155 public function syncAdventureSettings() : void{
1156 if($this->player === null){
1157 throw new \LogicException("Cannot sync adventure settings for a player that is not yet created");
1158 }
1159 //everything except auto jump is handled via UpdateAbilitiesPacket
1160 $this->sendDataPacket(UpdateAdventureSettingsPacket::create(
1161 noAttackingMobs: false,
1162 noAttackingPlayers: false,
1163 worldImmutable: false,
1164 showNameTags: true,
1165 autoJump: $this->player->hasAutoJump()
1166 ));
1167 }
1168
1169 public function syncAvailableCommands() : void{
1170 $commandData = [];
1171 $globalAliasMap = $this->server->getCommandMap()->getAliasMap();
1172 $userAliasMap = $this->player->getCommandAliasMap();
1173 foreach($this->server->getCommandMap()->getUniqueCommands() as $command){
1174 if(!$command->testPermissionSilent($this->player)){
1175 continue;
1176 }
1177
1178 $userAliases = $userAliasMap->getMergedAliases($command->getId(), $globalAliasMap);
1179 //the client doesn't like it when we override /help
1180 $aliases = array_values(array_filter($userAliases, fn(string $alias) => $alias !== "help" && $alias !== "?"));
1181 if(count($aliases) === 0){
1182 continue;
1183 }
1184 $firstNetworkAlias = $aliases[0];
1185 //use filtered aliases for command name discovery - this allows /help to still be shown as /pocketmine:help
1186 //on the client without conflicting with the client's built-in /help command
1187 $lname = strtolower($firstNetworkAlias);
1188 $aliasObj = new CommandHardEnum(ucfirst($firstNetworkAlias) . "Aliases", $aliases);
1189
1190 $description = $command->getDescription();
1191 $data = new CommandData(
1192 $lname, //TODO: commands containing uppercase letters in the name crash 1.9.0 client
1193 $description instanceof Translatable ? $this->player->getLanguage()->translate($description) : $description,
1194 0,
1195 CommandPermissions::NORMAL,
1196 $aliasObj,
1197 [
1198 new CommandOverload(chaining: false, parameters: [CommandParameter::standard("args", AvailableCommandsPacket::ARG_TYPE_RAWTEXT, 0, true)])
1199 ],
1200 chainedSubCommandData: []
1201 );
1202
1203 $commandData[] = $data;
1204 }
1205
1206 $this->sendDataPacket(AvailableCommandsPacketAssembler::assemble($commandData, [], []));
1207 }
1208
1213 public function prepareClientTranslatableMessage(Translatable $message) : array{
1214 //we can't send nested translations to the client, so make sure they are always pre-translated by the server
1215 $language = $this->player->getLanguage();
1216 $parameters = array_map(fn(string|Translatable $p) => $p instanceof Translatable ? $language->translate($p) : $p, $message->getParameters());
1217 $untranslatedParameterCount = 0;
1218 $translated = $language->translateString($message->getText(), $parameters, "pocketmine.", $untranslatedParameterCount);
1219 return [$translated, array_slice($parameters, 0, $untranslatedParameterCount)];
1220 }
1221
1222 public function onChatMessage(Translatable|string $message) : void{
1223 if($message instanceof Translatable){
1224 if(!$this->server->isLanguageForced()){
1225 $this->sendDataPacket(TextPacket::translation(...$this->prepareClientTranslatableMessage($message)));
1226 }else{
1227 $this->sendDataPacket(TextPacket::raw($this->player->getLanguage()->translate($message)));
1228 }
1229 }else{
1230 $this->sendDataPacket(TextPacket::raw($message));
1231 }
1232 }
1233
1234 public function onJukeboxPopup(Translatable|string $message) : void{
1235 $parameters = [];
1236 if($message instanceof Translatable){
1237 if(!$this->server->isLanguageForced()){
1238 [$message, $parameters] = $this->prepareClientTranslatableMessage($message);
1239 }else{
1240 $message = $this->player->getLanguage()->translate($message);
1241 }
1242 }
1243 $this->sendDataPacket(TextPacket::jukeboxPopup($message, $parameters));
1244 }
1245
1246 public function onPopup(string $message) : void{
1247 $this->sendDataPacket(TextPacket::popup($message));
1248 }
1249
1250 public function onTip(string $message) : void{
1251 $this->sendDataPacket(TextPacket::tip($message));
1252 }
1253
1254 public function onFormSent(int $id, Form $form) : bool{
1255 return $this->sendDataPacket(ModalFormRequestPacket::create($id, json_encode($form, JSON_THROW_ON_ERROR)));
1256 }
1257
1258 public function onCloseAllForms() : void{
1259 $this->sendDataPacket(ClientboundCloseFormPacket::create());
1260 }
1261
1265 private function sendChunkPacket(string $chunkPacket, \Closure $onCompletion, World $world) : void{
1266 $world->timings->syncChunkSend->startTiming();
1267 try{
1268 $this->queueCompressed($chunkPacket);
1269 $onCompletion();
1270 }finally{
1271 $world->timings->syncChunkSend->stopTiming();
1272 }
1273 }
1274
1280 public function startUsingChunk(int $chunkX, int $chunkZ, \Closure $onCompletion) : void{
1281 $world = $this->player->getLocation()->getWorld();
1282 $promiseOrPacket = ChunkCache::getInstance($world, $this->compressor)->request($chunkX, $chunkZ);
1283 if(is_string($promiseOrPacket)){
1284 $this->sendChunkPacket($promiseOrPacket, $onCompletion, $world);
1285 return;
1286 }
1287 $promiseOrPacket->onResolve(
1288 //this callback may be called synchronously or asynchronously, depending on whether the promise is resolved yet
1289 function(CompressBatchPromise $promise) use ($world, $onCompletion, $chunkX, $chunkZ) : void{
1290 if(!$this->isConnected()){
1291 return;
1292 }
1293 $currentWorld = $this->player->getLocation()->getWorld();
1294 if($world !== $currentWorld || ($status = $this->player->getUsedChunkStatus($chunkX, $chunkZ)) === null){
1295 $this->logger->debug("Tried to send no-longer-active chunk $chunkX $chunkZ in world " . $world->getFolderName());
1296 return;
1297 }
1298 if($status !== UsedChunkStatus::REQUESTED_SENDING){
1299 //TODO: make this an error
1300 //this could be triggered due to the shitty way that chunk resends are handled
1301 //right now - not because of the spammy re-requesting, but because the chunk status reverts
1302 //to NEEDED if they want to be resent.
1303 return;
1304 }
1305 $this->sendChunkPacket($promise->getResult(), $onCompletion, $world);
1306 }
1307 );
1308 }
1309
1310 public function stopUsingChunk(int $chunkX, int $chunkZ) : void{
1311
1312 }
1313
1314 public function onEnterWorld() : void{
1315 if($this->player !== null){
1316 $world = $this->player->getWorld();
1317 $this->syncWorldTime($world->getTime());
1318 $this->syncWorldDifficulty($world->getDifficulty());
1319 $this->syncWorldSpawnPoint($world->getSpawnLocation());
1320 //TODO: weather needs to be synced here (when implemented)
1321 }
1322 }
1323
1324 public function syncWorldTime(int $worldTime) : void{
1325 $this->sendDataPacket(SetTimePacket::create($worldTime));
1326 }
1327
1328 public function syncWorldDifficulty(int $worldDifficulty) : void{
1329 $this->sendDataPacket(SetDifficultyPacket::create($worldDifficulty));
1330 }
1331
1332 public function getInvManager() : ?InventoryManager{
1333 return $this->invManager;
1334 }
1335
1339 public function syncPlayerList(array $players) : void{
1340 $this->sendDataPacket(PlayerListPacket::add(array_map(function(Player $player) : PlayerListEntry{
1341 return PlayerListEntry::createAdditionEntry($player->getUniqueId(), $player->getId(), $player->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($player->getSkin()), $player->getXuid());
1342 }, $players)));
1343 }
1344
1345 public function onPlayerAdded(Player $p) : void{
1346 $this->sendDataPacket(PlayerListPacket::add([PlayerListEntry::createAdditionEntry($p->getUniqueId(), $p->getId(), $p->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($p->getSkin()), $p->getXuid())]));
1347 }
1348
1349 public function onPlayerRemoved(Player $p) : void{
1350 if($p !== $this->player){
1351 $this->sendDataPacket(PlayerListPacket::remove([PlayerListEntry::createRemovalEntry($p->getUniqueId())]));
1352 }
1353 }
1354
1355 public function onTitle(string $title) : void{
1356 $this->sendDataPacket(SetTitlePacket::title($title));
1357 }
1358
1359 public function onSubTitle(string $subtitle) : void{
1360 $this->sendDataPacket(SetTitlePacket::subtitle($subtitle));
1361 }
1362
1363 public function onActionBar(string $actionBar) : void{
1364 $this->sendDataPacket(SetTitlePacket::actionBarMessage($actionBar));
1365 }
1366
1367 public function onClearTitle() : void{
1368 $this->sendDataPacket(SetTitlePacket::clearTitle());
1369 }
1370
1371 public function onResetTitleOptions() : void{
1372 $this->sendDataPacket(SetTitlePacket::resetTitleOptions());
1373 }
1374
1375 public function onTitleDuration(int $fadeIn, int $stay, int $fadeOut) : void{
1376 $this->sendDataPacket(SetTitlePacket::setAnimationTimes($fadeIn, $stay, $fadeOut));
1377 }
1378
1379 public function onToastNotification(string $title, string $body) : void{
1380 $this->sendDataPacket(ToastRequestPacket::create($title, $body));
1381 }
1382
1383 public function onOpenSignEditor(Vector3 $signPosition, bool $frontSide) : void{
1384 $this->sendDataPacket(OpenSignPacket::create(BlockPosition::fromVector3($signPosition), $frontSide));
1385 }
1386
1387 public function onItemCooldownChanged(Item $item, int $ticks) : void{
1388 $this->sendDataPacket(PlayerStartItemCooldownPacket::create(
1389 GlobalItemDataHandlers::getSerializer()->serializeType($item)->getName(),
1390 $ticks
1391 ));
1392 }
1393
1394 public function tick() : void{
1395 if(!$this->isConnected()){
1396 $this->dispose();
1397 return;
1398 }
1399
1400 if($this->info === null){
1401 if(time() >= $this->connectTime + 10){
1402 $this->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_loginTimeout());
1403 }
1404
1405 return;
1406 }
1407
1408 if($this->player !== null){
1409 $this->player->doChunkRequests();
1410
1411 $dirtyAttributes = $this->player->getAttributeMap()->needSend();
1412 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $dirtyAttributes);
1413 foreach($dirtyAttributes as $attribute){
1414 //TODO: we might need to send these to other players in the future
1415 //if that happens, this will need to become more complex than a flag on the attribute itself
1416 $attribute->markSynchronized();
1417 }
1418 }
1419 Timings::$playerNetworkSendInventorySync->startTiming();
1420 try{
1421 $this->invManager?->flushPendingUpdates();
1422 }finally{
1423 Timings::$playerNetworkSendInventorySync->stopTiming();
1424 }
1425
1426 $this->flushGamePacketQueue();
1427 }
1428}
handleDataPacket(Packet $packet, string $buffer)
prepareClientTranslatableMessage(Translatable $message)
onPlayerDestroyed(Translatable|string $reason, Translatable|string $disconnectScreenMessage)
sendDataPacketWithReceipt(ClientboundPacket $packet, bool $immediate=false)
onClientDisconnect(Translatable|string $reason)
transfer(string $ip, int $port, Translatable|string|null $reason=null)
disconnect(Translatable|string $reason, Translatable|string|null $disconnectScreenMessage=null, bool $notify=true)
startUsingChunk(int $chunkX, int $chunkZ, \Closure $onCompletion)