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