PocketMine-MP 5.23.3 git-f7687af337d001ddbcc47b8e773f014a33faa662
Loading...
Searching...
No Matches
InGamePacketHandler.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\handler;
25
110use function array_push;
111use function count;
112use function fmod;
113use function get_debug_type;
114use function implode;
115use function in_array;
116use function is_infinite;
117use function is_nan;
118use function json_decode;
119use function max;
120use function mb_strlen;
121use function microtime;
122use function sprintf;
123use function str_starts_with;
124use function strlen;
125use const JSON_THROW_ON_ERROR;
126
131 private const MAX_FORM_RESPONSE_DEPTH = 2; //modal/simple will be 1, custom forms 2 - they will never contain anything other than string|int|float|bool|null
132
133 protected float $lastRightClickTime = 0.0;
134 protected ?UseItemTransactionData $lastRightClickData = null;
135
136 protected ?Vector3 $lastPlayerAuthInputPosition = null;
137 protected ?float $lastPlayerAuthInputYaw = null;
138 protected ?float $lastPlayerAuthInputPitch = null;
139 protected ?BitSet $lastPlayerAuthInputFlags = null;
140
141 public bool $forceMoveSync = false;
142
143 protected ?string $lastRequestedFullSkinId = null;
144
145 public function __construct(
146 private Player $player,
147 private NetworkSession $session,
148 private InventoryManager $inventoryManager
149 ){}
150
151 public function handleText(TextPacket $packet) : bool{
152 if($packet->type === TextPacket::TYPE_CHAT){
153 return $this->player->chat($packet->message);
154 }
155
156 return false;
157 }
158
159 public function handleMovePlayer(MovePlayerPacket $packet) : bool{
160 //The client sends this every time it lands on the ground, even when using PlayerAuthInputPacket.
161 //Silence the debug spam that this causes.
162 return true;
163 }
164
165 private function resolveOnOffInputFlags(BitSet $inputFlags, int $startFlag, int $stopFlag) : ?bool{
166 $enabled = $inputFlags->get($startFlag);
167 $disabled = $inputFlags->get($stopFlag);
168 if($enabled !== $disabled){
169 return $enabled;
170 }
171 //neither flag was set, or both were set
172 return null;
173 }
174
175 public function handlePlayerAuthInput(PlayerAuthInputPacket $packet) : bool{
176 $rawPos = $packet->getPosition();
177 $rawYaw = $packet->getYaw();
178 $rawPitch = $packet->getPitch();
179 foreach([$rawPos->x, $rawPos->y, $rawPos->z, $rawYaw, $packet->getHeadYaw(), $rawPitch] as $float){
180 if(is_infinite($float) || is_nan($float)){
181 $this->session->getLogger()->debug("Invalid movement received, contains NAN/INF components");
182 return false;
183 }
184 }
185
186 if($rawYaw !== $this->lastPlayerAuthInputYaw || $rawPitch !== $this->lastPlayerAuthInputPitch){
187 $this->lastPlayerAuthInputYaw = $rawYaw;
188 $this->lastPlayerAuthInputPitch = $rawPitch;
189
190 $yaw = fmod($rawYaw, 360);
191 $pitch = fmod($rawPitch, 360);
192 if($yaw < 0){
193 $yaw += 360;
194 }
195
196 $this->player->setRotation($yaw, $pitch);
197 }
198
199 $hasMoved = $this->lastPlayerAuthInputPosition === null || !$this->lastPlayerAuthInputPosition->equals($rawPos);
200 $newPos = $rawPos->subtract(0, 1.62, 0)->round(4);
201
202 if($this->forceMoveSync && $hasMoved){
203 $curPos = $this->player->getLocation();
204
205 if($newPos->distanceSquared($curPos) > 1){ //Tolerate up to 1 block to avoid problems with client-sided physics when spawning in blocks
206 $this->session->getLogger()->debug("Got outdated pre-teleport movement, received " . $newPos . ", expected " . $curPos);
207 //Still getting movements from before teleport, ignore them
208 return true;
209 }
210
211 // Once we get a movement within a reasonable distance, treat it as a teleport ACK and remove position lock
212 $this->forceMoveSync = false;
213 }
214
215 $inputFlags = $packet->getInputFlags();
216 if($inputFlags !== $this->lastPlayerAuthInputFlags){
217 $this->lastPlayerAuthInputFlags = $inputFlags;
218
219 $sneaking = $inputFlags->get(PlayerAuthInputFlags::SNEAKING);
220 if($this->player->isSneaking() === $sneaking){
221 $sneaking = null;
222 }
223 $sprinting = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SPRINTING, PlayerAuthInputFlags::STOP_SPRINTING);
224 $swimming = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SWIMMING, PlayerAuthInputFlags::STOP_SWIMMING);
225 $gliding = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_GLIDING, PlayerAuthInputFlags::STOP_GLIDING);
226 $flying = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_FLYING, PlayerAuthInputFlags::STOP_FLYING);
227 $mismatch =
228 ($sneaking !== null && !$this->player->toggleSneak($sneaking)) |
229 ($sprinting !== null && !$this->player->toggleSprint($sprinting)) |
230 ($swimming !== null && !$this->player->toggleSwim($swimming)) |
231 ($gliding !== null && !$this->player->toggleGlide($gliding)) |
232 ($flying !== null && !$this->player->toggleFlight($flying));
233 if((bool) $mismatch){
234 $this->player->sendData([$this->player]);
235 }
236
237 if($inputFlags->get(PlayerAuthInputFlags::START_JUMPING)){
238 $this->player->jump();
239 }
240 if($inputFlags->get(PlayerAuthInputFlags::MISSED_SWING)){
241 $this->player->missSwing();
242 }
243 }
244
245 if(!$this->forceMoveSync && $hasMoved){
246 $this->lastPlayerAuthInputPosition = $rawPos;
247 //TODO: this packet has WAYYYYY more useful information that we're not using
248 $this->player->handleMovement($newPos);
249 }
250
251 $packetHandled = true;
252
253 $blockActions = $packet->getBlockActions();
254 if($blockActions !== null){
255 if(count($blockActions) > 100){
256 throw new PacketHandlingException("Too many block actions in PlayerAuthInputPacket");
257 }
258 foreach(Utils::promoteKeys($blockActions) as $k => $blockAction){
259 $actionHandled = false;
260 if($blockAction instanceof PlayerBlockActionStopBreak){
261 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), new BlockPosition(0, 0, 0), Facing::DOWN);
262 }elseif($blockAction instanceof PlayerBlockActionWithBlockInfo){
263 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), $blockAction->getBlockPosition(), $blockAction->getFace());
264 }
265
266 if(!$actionHandled){
267 $packetHandled = false;
268 $this->session->getLogger()->debug("Unhandled player block action at offset $k in PlayerAuthInputPacket");
269 }
270 }
271 }
272
273 $useItemTransaction = $packet->getItemInteractionData();
274 if($useItemTransaction !== null){
275 if(count($useItemTransaction->getTransactionData()->getActions()) > 100){
276 throw new PacketHandlingException("Too many actions in item use transaction");
277 }
278
279 $this->inventoryManager->setCurrentItemStackRequestId($useItemTransaction->getRequestId());
280 $this->inventoryManager->addRawPredictedSlotChanges($useItemTransaction->getTransactionData()->getActions());
281 if(!$this->handleUseItemTransaction($useItemTransaction->getTransactionData())){
282 $packetHandled = false;
283 $this->session->getLogger()->debug("Unhandled transaction in PlayerAuthInputPacket (type " . $useItemTransaction->getTransactionData()->getActionType() . ")");
284 }else{
285 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
286 }
287 $this->inventoryManager->setCurrentItemStackRequestId(null);
288 }
289
290 $itemStackRequest = $packet->getItemStackRequest();
291 if($itemStackRequest !== null){
292 $result = $this->handleSingleItemStackRequest($itemStackRequest);
293 $this->session->sendDataPacket(ItemStackResponsePacket::create([$result]));
294 }
295
296 return $packetHandled;
297 }
298
299 public function handleLevelSoundEventPacketV1(LevelSoundEventPacketV1 $packet) : bool{
300 return true; //useless leftover from 1.8
301 }
302
303 public function handleActorEvent(ActorEventPacket $packet) : bool{
304 if($packet->actorRuntimeId !== $this->player->getId()){
305 //TODO HACK: EATING_ITEM is sent back to the server when the server sends it for other players (1.14 bug, maybe earlier)
306 return $packet->actorRuntimeId === ActorEvent::EATING_ITEM;
307 }
308
309 switch($packet->eventId){
310 case ActorEvent::EATING_ITEM: //TODO: ignore this and handle it server-side
311 $item = $this->player->getInventory()->getItemInHand();
312 if($item->isNull()){
313 return false;
314 }
315 $this->player->broadcastAnimation(new ConsumingItemAnimation($this->player, $this->player->getInventory()->getItemInHand()));
316 break;
317 default:
318 return false;
319 }
320
321 return true;
322 }
323
324 public function handleInventoryTransaction(InventoryTransactionPacket $packet) : bool{
325 $result = true;
326
327 if(count($packet->trData->getActions()) > 50){
328 throw new PacketHandlingException("Too many actions in inventory transaction");
329 }
330 if(count($packet->requestChangedSlots) > 10){
331 throw new PacketHandlingException("Too many slot sync requests in inventory transaction");
332 }
333
334 $this->inventoryManager->setCurrentItemStackRequestId($packet->requestId);
335 $this->inventoryManager->addRawPredictedSlotChanges($packet->trData->getActions());
336
337 if($packet->trData instanceof NormalTransactionData){
338 $result = $this->handleNormalTransaction($packet->trData, $packet->requestId);
339 }elseif($packet->trData instanceof MismatchTransactionData){
340 $this->session->getLogger()->debug("Mismatch transaction received");
341 $this->inventoryManager->requestSyncAll();
342 $result = true;
343 }elseif($packet->trData instanceof UseItemTransactionData){
344 $result = $this->handleUseItemTransaction($packet->trData);
345 }elseif($packet->trData instanceof UseItemOnEntityTransactionData){
346 $result = $this->handleUseItemOnEntityTransaction($packet->trData);
347 }elseif($packet->trData instanceof ReleaseItemTransactionData){
348 $result = $this->handleReleaseItemTransaction($packet->trData);
349 }
350
351 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
352
353 //requestChangedSlots asks the server to always send out the contents of the specified slots, even if they
354 //haven't changed. Handling these is necessary to ensure the client inventory stays in sync if the server
355 //rejects the transaction. The most common example of this is equipping armor by right-click, which doesn't send
356 //a legacy prediction action for the destination armor slot.
357 foreach($packet->requestChangedSlots as $containerInfo){
358 foreach($containerInfo->getChangedSlotIndexes() as $netSlot){
359 [$windowId, $slot] = ItemStackContainerIdTranslator::translate($containerInfo->getContainerId(), $this->inventoryManager->getCurrentWindowId(), $netSlot);
360 $inventoryAndSlot = $this->inventoryManager->locateWindowAndSlot($windowId, $slot);
361 if($inventoryAndSlot !== null){ //trigger the normal slot sync logic
362 $this->inventoryManager->onSlotChange($inventoryAndSlot[0], $inventoryAndSlot[1]);
363 }
364 }
365 }
366
367 $this->inventoryManager->setCurrentItemStackRequestId(null);
368 return $result;
369 }
370
371 private function executeInventoryTransaction(InventoryTransaction $transaction, int $requestId) : bool{
372 $this->player->setUsingItem(false);
373
374 $this->inventoryManager->setCurrentItemStackRequestId($requestId);
375 $this->inventoryManager->addTransactionPredictedSlotChanges($transaction);
376 try{
377 $transaction->execute();
379 $this->inventoryManager->requestSyncAll();
380 $logger = $this->session->getLogger();
381 $logger->debug("Invalid inventory transaction $requestId: " . $e->getMessage());
382
383 return false;
385 $this->session->getLogger()->debug("Inventory transaction $requestId cancelled by a plugin");
386
387 return false;
388 }finally{
389 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
390 $this->inventoryManager->setCurrentItemStackRequestId(null);
391 }
392
393 return true;
394 }
395
396 private function handleNormalTransaction(NormalTransactionData $data, int $itemStackRequestId) : bool{
397 //When the ItemStackRequest system is used, this transaction type is used for dropping items by pressing Q.
398 //I don't know why they don't just use ItemStackRequest for that too, which already supports dropping items by
399 //clicking them outside an open inventory menu, but for now it is what it is.
400 //Fortunately, this means we can be much stricter about the validation criteria.
401
402 $actionCount = count($data->getActions());
403 if($actionCount > 2){
404 if($actionCount > 5){
405 throw new PacketHandlingException("Too many actions ($actionCount) in normal inventory transaction");
406 }
407
408 //Due to a bug in the game, this transaction type is still sent when a player edits a book. We don't need
409 //these transactions for editing books, since we have BookEditPacket, so we can just ignore them.
410 $this->session->getLogger()->debug("Ignoring normal inventory transaction with $actionCount actions (drop-item should have exactly 2 actions)");
411 return false;
412 }
413
414 $sourceSlot = null;
415 $clientItemStack = null;
416 $droppedCount = null;
417
418 foreach($data->getActions() as $networkInventoryAction){
419 if($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_WORLD && $networkInventoryAction->inventorySlot == NetworkInventoryAction::ACTION_MAGIC_SLOT_DROP_ITEM){
420 $droppedCount = $networkInventoryAction->newItem->getItemStack()->getCount();
421 if($droppedCount <= 0){
422 throw new PacketHandlingException("Expected positive count for dropped item");
423 }
424 }elseif($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_CONTAINER && $networkInventoryAction->windowId === ContainerIds::INVENTORY){
425 //mobile players can drop an item from a non-selected hotbar slot
426 $sourceSlot = $networkInventoryAction->inventorySlot;
427 $clientItemStack = $networkInventoryAction->oldItem->getItemStack();
428 }else{
429 $this->session->getLogger()->debug("Unexpected inventory action type $networkInventoryAction->sourceType in drop item transaction");
430 return false;
431 }
432 }
433 if($sourceSlot === null || $clientItemStack === null || $droppedCount === null){
434 $this->session->getLogger()->debug("Missing information in drop item transaction, need source slot, client item stack and dropped count");
435 return false;
436 }
437
438 $inventory = $this->player->getInventory();
439
440 if(!$inventory->slotExists($sourceSlot)){
441 return false; //TODO: size desync??
442 }
443
444 $sourceSlotItem = $inventory->getItem($sourceSlot);
445 if($sourceSlotItem->getCount() < $droppedCount){
446 return false;
447 }
448 $serverItemStack = $this->session->getTypeConverter()->coreItemStackToNet($sourceSlotItem);
449 //Sadly we don't have itemstack IDs here, so we have to compare the basic item properties to ensure that we're
450 //dropping the item the client expects (inventory might be out of sync with the client).
451 if(
452 $serverItemStack->getId() !== $clientItemStack->getId() ||
453 $serverItemStack->getMeta() !== $clientItemStack->getMeta() ||
454 $serverItemStack->getCount() !== $clientItemStack->getCount() ||
455 $serverItemStack->getBlockRuntimeId() !== $clientItemStack->getBlockRuntimeId()
456 //Raw extraData may not match because of TAG_Compound key ordering differences, and decoding it to compare
457 //is costly. Assume that we're in sync if id+meta+count+runtimeId match.
458 //NB: Make sure $clientItemStack isn't used to create the dropped item, as that would allow the client
459 //to change the item NBT since we're not validating it.
460 ){
461 return false;
462 }
463
464 //this modifies $sourceSlotItem
465 $droppedItem = $sourceSlotItem->pop($droppedCount);
466
467 $builder = new TransactionBuilder();
468 $builder->getInventory($inventory)->setItem($sourceSlot, $sourceSlotItem);
469 $builder->addAction(new DropItemAction($droppedItem));
470
471 $transaction = new InventoryTransaction($this->player, $builder->generateActions());
472 return $this->executeInventoryTransaction($transaction, $itemStackRequestId);
473 }
474
475 private function handleUseItemTransaction(UseItemTransactionData $data) : bool{
476 $this->player->selectHotbarSlot($data->getHotbarSlot());
477
478 switch($data->getActionType()){
479 case UseItemTransactionData::ACTION_CLICK_BLOCK:
480 //TODO: start hack for client spam bug
481 $clickPos = $data->getClickPosition();
482 $spamBug = ($this->lastRightClickData !== null &&
483 microtime(true) - $this->lastRightClickTime < 0.1 && //100ms
484 $this->lastRightClickData->getPlayerPosition()->distanceSquared($data->getPlayerPosition()) < 0.00001 &&
485 $this->lastRightClickData->getBlockPosition()->equals($data->getBlockPosition()) &&
486 $this->lastRightClickData->getClickPosition()->distanceSquared($clickPos) < 0.00001 //signature spam bug has 0 distance, but allow some error
487 );
488 //get rid of continued spam if the player clicks and holds right-click
489 $this->lastRightClickData = $data;
490 $this->lastRightClickTime = microtime(true);
491 if($spamBug){
492 return true;
493 }
494 //TODO: end hack for client spam bug
495
496 self::validateFacing($data->getFace());
497
498 $blockPos = $data->getBlockPosition();
499 $vBlockPos = new Vector3($blockPos->getX(), $blockPos->getY(), $blockPos->getZ());
500 $this->player->interactBlock($vBlockPos, $data->getFace(), $clickPos);
501 //always sync this in case plugins caused a different result than the client expected
502 //we *could* try to enhance detection of plugin-altered behaviour, but this would require propagating
503 //more information up the stack. For now I think this is good enough.
504 //if only the client would tell us what blocks it thinks changed...
505 $this->syncBlocksNearby($vBlockPos, $data->getFace());
506 return true;
507 case UseItemTransactionData::ACTION_BREAK_BLOCK:
508 $blockPos = $data->getBlockPosition();
509 $vBlockPos = new Vector3($blockPos->getX(), $blockPos->getY(), $blockPos->getZ());
510 if(!$this->player->breakBlock($vBlockPos)){
511 $this->syncBlocksNearby($vBlockPos, null);
512 }
513 return true;
514 case UseItemTransactionData::ACTION_CLICK_AIR:
515 if($this->player->isUsingItem()){
516 if(!$this->player->consumeHeldItem()){
517 $hungerAttr = $this->player->getAttributeMap()->get(Attribute::HUNGER) ?? throw new AssumptionFailedError();
518 $hungerAttr->markSynchronized(false);
519 }
520 return true;
521 }
522 $this->player->useHeldItem();
523 return true;
524 }
525
526 return false;
527 }
528
532 private static function validateFacing(int $facing) : void{
533 if(!in_array($facing, Facing::ALL, true)){
534 throw new PacketHandlingException("Invalid facing value $facing");
535 }
536 }
537
541 private function syncBlocksNearby(Vector3 $blockPos, ?int $face) : void{
542 if($blockPos->distanceSquared($this->player->getLocation()) < 10000){
543 $blocks = $blockPos->sidesArray();
544 if($face !== null){
545 $sidePos = $blockPos->getSide($face);
546
548 array_push($blocks, ...$sidePos->sidesArray()); //getAllSides() on each of these will include $blockPos and $sidePos because they are next to each other
549 }else{
550 $blocks[] = $blockPos;
551 }
552 foreach($this->player->getWorld()->createBlockUpdatePackets($blocks) as $packet){
553 $this->session->sendDataPacket($packet);
554 }
555 }
556 }
557
558 private function handleUseItemOnEntityTransaction(UseItemOnEntityTransactionData $data) : bool{
559 $target = $this->player->getWorld()->getEntity($data->getActorRuntimeId());
560 if($target === null){
561 return false;
562 }
563
564 $this->player->selectHotbarSlot($data->getHotbarSlot());
565
566 switch($data->getActionType()){
567 case UseItemOnEntityTransactionData::ACTION_INTERACT:
568 $this->player->interactEntity($target, $data->getClickPosition());
569 return true;
570 case UseItemOnEntityTransactionData::ACTION_ATTACK:
571 $this->player->attackEntity($target);
572 return true;
573 }
574
575 return false;
576 }
577
578 private function handleReleaseItemTransaction(ReleaseItemTransactionData $data) : bool{
579 $this->player->selectHotbarSlot($data->getHotbarSlot());
580
581 if($data->getActionType() == ReleaseItemTransactionData::ACTION_RELEASE){
582 $this->player->releaseHeldItem();
583 return true;
584 }
585
586 return false;
587 }
588
589 private function handleSingleItemStackRequest(ItemStackRequest $request) : ItemStackResponse{
590 if(count($request->getActions()) > 60){
591 //recipe book auto crafting can affect all slots of the inventory when consuming inputs or producing outputs
592 //this means there could be as many as 50 CraftingConsumeInput actions or Place (taking the result) actions
593 //in a single request (there are certain ways items can be arranged which will result in the same stack
594 //being taken from multiple times, but this is behaviour with a calculable limit)
595 //this means there SHOULD be AT MOST 53 actions in a single request, but 60 is a nice round number.
596 //n64Stacks = ?
597 //n1Stacks = 45 - n64Stacks
598 //nItemsRequiredFor1Craft = 9
599 //nResults = floor((n1Stacks + (n64Stacks * 64)) / nItemsRequiredFor1Craft)
600 //nTakeActionsTotal = floor(64 / nResults) + max(1, 64 % nResults) + ((nResults * nItemsRequiredFor1Craft) - (n64Stacks * 64))
601 throw new PacketHandlingException("Too many actions in ItemStackRequest");
602 }
603 $executor = new ItemStackRequestExecutor($this->player, $this->inventoryManager, $request);
604 try{
605 $transaction = $executor->generateInventoryTransaction();
606 $result = $this->executeInventoryTransaction($transaction, $request->getRequestId());
608 $result = false;
609 $this->session->getLogger()->debug("ItemStackRequest #" . $request->getRequestId() . " failed: " . $e->getMessage());
610 $this->session->getLogger()->debug(implode("\n", Utils::printableExceptionInfo($e)));
611 $this->inventoryManager->requestSyncAll();
612 }
613
614 if(!$result){
615 return new ItemStackResponse(ItemStackResponse::RESULT_ERROR, $request->getRequestId());
616 }
617 return $executor->buildItemStackResponse();
618 }
619
620 public function handleItemStackRequest(ItemStackRequestPacket $packet) : bool{
621 $responses = [];
622 if(count($packet->getRequests()) > 80){
623 //TODO: we can probably lower this limit, but this will do for now
624 throw new PacketHandlingException("Too many requests in ItemStackRequestPacket");
625 }
626 foreach($packet->getRequests() as $request){
627 $responses[] = $this->handleSingleItemStackRequest($request);
628 }
629
630 $this->session->sendDataPacket(ItemStackResponsePacket::create($responses));
631
632 return true;
633 }
634
635 public function handleMobEquipment(MobEquipmentPacket $packet) : bool{
636 if($packet->windowId === ContainerIds::OFFHAND){
637 return true; //this happens when we put an item into the offhand
638 }
639 if($packet->windowId === ContainerIds::INVENTORY){
640 $this->inventoryManager->onClientSelectHotbarSlot($packet->hotbarSlot);
641 if(!$this->player->selectHotbarSlot($packet->hotbarSlot)){
642 $this->inventoryManager->syncSelectedHotbarSlot();
643 }
644 return true;
645 }
646 return false;
647 }
648
649 public function handleMobArmorEquipment(MobArmorEquipmentPacket $packet) : bool{
650 return true; //Not used
651 }
652
653 public function handleInteract(InteractPacket $packet) : bool{
654 if($packet->action === InteractPacket::ACTION_MOUSEOVER){
655 //TODO HACK: silence useless spam (MCPE 1.8)
656 //due to some messy Mojang hacks, it sends this when changing the held item now, which causes us to think
657 //the inventory was closed when it wasn't.
658 //this is also sent whenever entity metadata updates, which can get really spammy.
659 //TODO: implement handling for this where it matters
660 return true;
661 }
662 $target = $this->player->getWorld()->getEntity($packet->targetActorRuntimeId);
663 if($target === null){
664 return false;
665 }
666 if($packet->action === InteractPacket::ACTION_OPEN_INVENTORY && $target === $this->player){
667 $this->inventoryManager->onClientOpenMainInventory();
668 return true;
669 }
670 return false; //TODO
671 }
672
673 public function handleBlockPickRequest(BlockPickRequestPacket $packet) : bool{
674 return $this->player->pickBlock(new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ()), $packet->addUserData);
675 }
676
677 public function handleActorPickRequest(ActorPickRequestPacket $packet) : bool{
678 return $this->player->pickEntity($packet->actorUniqueId);
679 }
680
681 public function handlePlayerAction(PlayerActionPacket $packet) : bool{
682 return $this->handlePlayerActionFromData($packet->action, $packet->blockPosition, $packet->face);
683 }
684
685 private function handlePlayerActionFromData(int $action, BlockPosition $blockPosition, int $face) : bool{
686 $pos = new Vector3($blockPosition->getX(), $blockPosition->getY(), $blockPosition->getZ());
687
688 switch($action){
689 case PlayerAction::START_BREAK:
690 self::validateFacing($face);
691 if(!$this->player->attackBlock($pos, $face)){
692 $this->syncBlocksNearby($pos, $face);
693 }
694
695 break;
696
697 case PlayerAction::ABORT_BREAK:
698 case PlayerAction::STOP_BREAK:
699 $this->player->stopBreakBlock($pos);
700 break;
701 case PlayerAction::START_SLEEPING:
702 //unused
703 break;
704 case PlayerAction::STOP_SLEEPING:
705 $this->player->stopSleep();
706 break;
707 case PlayerAction::CRACK_BREAK:
708 self::validateFacing($face);
709 $this->player->continueBreakBlock($pos, $face);
710 break;
711 case PlayerAction::INTERACT_BLOCK: //TODO: ignored (for now)
712 break;
713 case PlayerAction::CREATIVE_PLAYER_DESTROY_BLOCK:
714 //TODO: do we need to handle this?
715 break;
716 case PlayerAction::START_ITEM_USE_ON:
717 case PlayerAction::STOP_ITEM_USE_ON:
718 //TODO: this has no obvious use and seems only used for analytics in vanilla - ignore it
719 break;
720 default:
721 $this->session->getLogger()->debug("Unhandled/unknown player action type " . $action);
722 return false;
723 }
724
725 $this->player->setUsingItem(false);
726
727 return true;
728 }
729
730 public function handleSetActorMotion(SetActorMotionPacket $packet) : bool{
731 return true; //Not used: This packet is (erroneously) sent to the server when the client is riding a vehicle.
732 }
733
734 public function handleAnimate(AnimatePacket $packet) : bool{
735 return true; //Not used
736 }
737
738 public function handleContainerClose(ContainerClosePacket $packet) : bool{
739 $this->inventoryManager->onClientRemoveWindow($packet->windowId);
740 return true;
741 }
742
743 public function handlePlayerHotbar(PlayerHotbarPacket $packet) : bool{
744 return true; //this packet is useless
745 }
746
747 public function handleBlockActorData(BlockActorDataPacket $packet) : bool{
748 $pos = new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ());
749 if($pos->distanceSquared($this->player->getLocation()) > 10000){
750 return false;
751 }
752
753 $block = $this->player->getLocation()->getWorld()->getBlock($pos);
754 $nbt = $packet->nbt->getRoot();
755 if(!($nbt instanceof CompoundTag)) throw new AssumptionFailedError("PHPStan should ensure this is a CompoundTag"); //for phpstorm's benefit
756
757 if($block instanceof BaseSign){
758 $frontTextTag = $nbt->getTag(Sign::TAG_FRONT_TEXT);
759 if(!$frontTextTag instanceof CompoundTag){
760 throw new PacketHandlingException("Invalid tag type " . get_debug_type($frontTextTag) . " for tag \"" . Sign::TAG_FRONT_TEXT . "\" in sign update data");
761 }
762 $textBlobTag = $frontTextTag->getTag(Sign::TAG_TEXT_BLOB);
763 if(!$textBlobTag instanceof StringTag){
764 throw new PacketHandlingException("Invalid tag type " . get_debug_type($textBlobTag) . " for tag \"" . Sign::TAG_TEXT_BLOB . "\" in sign update data");
765 }
766
767 try{
768 $text = SignText::fromBlob($textBlobTag->getValue());
769 }catch(\InvalidArgumentException $e){
770 throw PacketHandlingException::wrap($e, "Invalid sign text update");
771 }
772
773 try{
774 if(!$block->updateText($this->player, $text)){
775 foreach($this->player->getWorld()->createBlockUpdatePackets([$pos]) as $updatePacket){
776 $this->session->sendDataPacket($updatePacket);
777 }
778 }
779 }catch(\UnexpectedValueException $e){
780 throw PacketHandlingException::wrap($e);
781 }
782
783 return true;
784 }
785
786 return false;
787 }
788
789 public function handlePlayerInput(PlayerInputPacket $packet) : bool{
790 return false; //TODO
791 }
792
793 public function handleSetPlayerGameType(SetPlayerGameTypePacket $packet) : bool{
794 $gameMode = $this->session->getTypeConverter()->protocolGameModeToCore($packet->gamemode);
795 if($gameMode !== $this->player->getGamemode()){
796 //Set this back to default. TODO: handle this properly
797 $this->session->syncGameMode($this->player->getGamemode(), true);
798 }
799 return true;
800 }
801
802 public function handleSpawnExperienceOrb(SpawnExperienceOrbPacket $packet) : bool{
803 return false; //TODO
804 }
805
806 public function handleMapInfoRequest(MapInfoRequestPacket $packet) : bool{
807 return false; //TODO
808 }
809
810 public function handleRequestChunkRadius(RequestChunkRadiusPacket $packet) : bool{
811 $this->player->setViewDistance($packet->radius);
812
813 return true;
814 }
815
816 public function handleBossEvent(BossEventPacket $packet) : bool{
817 return false; //TODO
818 }
819
820 public function handleShowCredits(ShowCreditsPacket $packet) : bool{
821 return false; //TODO: handle resume
822 }
823
824 public function handleCommandRequest(CommandRequestPacket $packet) : bool{
825 if(str_starts_with($packet->command, '/')){
826 $this->player->chat($packet->command);
827 return true;
828 }
829 return false;
830 }
831
832 public function handleCommandBlockUpdate(CommandBlockUpdatePacket $packet) : bool{
833 return false; //TODO
834 }
835
836 public function handlePlayerSkin(PlayerSkinPacket $packet) : bool{
837 if($packet->skin->getFullSkinId() === $this->lastRequestedFullSkinId){
838 //TODO: HACK! In 1.19.60, the client sends its skin back to us if we sent it a skin different from the one
839 //it's using. We need to prevent this from causing a feedback loop.
840 $this->session->getLogger()->debug("Refused duplicate skin change request");
841 return true;
842 }
843 $this->lastRequestedFullSkinId = $packet->skin->getFullSkinId();
844
845 $this->session->getLogger()->debug("Processing skin change request");
846 try{
847 $skin = $this->session->getTypeConverter()->getSkinAdapter()->fromSkinData($packet->skin);
848 }catch(InvalidSkinException $e){
849 throw PacketHandlingException::wrap($e, "Invalid skin in PlayerSkinPacket");
850 }
851 return $this->player->changeSkin($skin, $packet->newSkinName, $packet->oldSkinName);
852 }
853
854 public function handleSubClientLogin(SubClientLoginPacket $packet) : bool{
855 return false; //TODO
856 }
857
861 private function checkBookText(string $string, string $fieldName, int $softLimit, int $hardLimit, bool &$cancel) : string{
862 if(strlen($string) > $hardLimit){
863 throw new PacketHandlingException(sprintf("Book %s must be at most %d bytes, but have %d bytes", $fieldName, $hardLimit, strlen($string)));
864 }
865
866 $result = TextFormat::clean($string, false);
867 //strlen() is O(1), mb_strlen() is O(n)
868 if(strlen($result) > $softLimit * 4 || mb_strlen($result, 'UTF-8') > $softLimit){
869 $cancel = true;
870 $this->session->getLogger()->debug("Cancelled book edit due to $fieldName exceeded soft limit of $softLimit chars");
871 }
872
873 return $result;
874 }
875
876 public function handleBookEdit(BookEditPacket $packet) : bool{
877 $inventory = $this->player->getInventory();
878 if(!$inventory->slotExists($packet->inventorySlot)){
879 return false;
880 }
881 //TODO: break this up into book API things
882 $oldBook = $inventory->getItem($packet->inventorySlot);
883 if(!($oldBook instanceof WritableBook)){
884 return false;
885 }
886
887 $newBook = clone $oldBook;
888 $modifiedPages = [];
889 $cancel = false;
890 switch($packet->type){
891 case BookEditPacket::TYPE_REPLACE_PAGE:
892 $text = self::checkBookText($packet->text, "page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
893 $newBook->setPageText($packet->pageNumber, $text);
894 $modifiedPages[] = $packet->pageNumber;
895 break;
896 case BookEditPacket::TYPE_ADD_PAGE:
897 if(!$newBook->pageExists($packet->pageNumber)){
898 //this may only come before a page which already exists
899 //TODO: the client can send insert-before actions on trailing client-side pages which cause odd behaviour on the server
900 return false;
901 }
902 $text = self::checkBookText($packet->text, "page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
903 $newBook->insertPage($packet->pageNumber, $text);
904 $modifiedPages[] = $packet->pageNumber;
905 break;
906 case BookEditPacket::TYPE_DELETE_PAGE:
907 if(!$newBook->pageExists($packet->pageNumber)){
908 return false;
909 }
910 $newBook->deletePage($packet->pageNumber);
911 $modifiedPages[] = $packet->pageNumber;
912 break;
913 case BookEditPacket::TYPE_SWAP_PAGES:
914 if(!$newBook->pageExists($packet->pageNumber) || !$newBook->pageExists($packet->secondaryPageNumber)){
915 //the client will create pages on its own without telling us until it tries to switch them
916 $newBook->addPage(max($packet->pageNumber, $packet->secondaryPageNumber));
917 }
918 $newBook->swapPages($packet->pageNumber, $packet->secondaryPageNumber);
919 $modifiedPages = [$packet->pageNumber, $packet->secondaryPageNumber];
920 break;
921 case BookEditPacket::TYPE_SIGN_BOOK:
922 $title = self::checkBookText($packet->title, "title", 16, Limits::INT16_MAX, $cancel);
923 //this one doesn't have a limit in vanilla, so we have to improvise
924 $author = self::checkBookText($packet->author, "author", 256, Limits::INT16_MAX, $cancel);
925
926 $newBook = VanillaItems::WRITTEN_BOOK()
927 ->setPages($oldBook->getPages())
928 ->setAuthor($author)
929 ->setTitle($title)
930 ->setGeneration(WrittenBook::GENERATION_ORIGINAL);
931 break;
932 default:
933 return false;
934 }
935
936 //for redundancy, in case of protocol changes, we don't want to pass these directly
937 $action = match($packet->type){
938 BookEditPacket::TYPE_REPLACE_PAGE => PlayerEditBookEvent::ACTION_REPLACE_PAGE,
939 BookEditPacket::TYPE_ADD_PAGE => PlayerEditBookEvent::ACTION_ADD_PAGE,
940 BookEditPacket::TYPE_DELETE_PAGE => PlayerEditBookEvent::ACTION_DELETE_PAGE,
941 BookEditPacket::TYPE_SWAP_PAGES => PlayerEditBookEvent::ACTION_SWAP_PAGES,
942 BookEditPacket::TYPE_SIGN_BOOK => PlayerEditBookEvent::ACTION_SIGN_BOOK,
943 default => throw new AssumptionFailedError("We already filtered unknown types in the switch above")
944 };
945
946 /*
947 * Plugins may have created books with more than 50 pages; we allow plugins to do this, but not players.
948 * Don't allow the page count to grow past 50, but allow deleting, swapping or altering text of existing pages.
949 */
950 $oldPageCount = count($oldBook->getPages());
951 $newPageCount = count($newBook->getPages());
952 if(($newPageCount > $oldPageCount && $newPageCount > 50)){
953 $this->session->getLogger()->debug("Cancelled book edit due to adding too many pages (new page count would be $newPageCount)");
954 $cancel = true;
955 }
956
957 $event = new PlayerEditBookEvent($this->player, $oldBook, $newBook, $action, $modifiedPages);
958 if($cancel){
959 $event->cancel();
960 }
961
962 $event->call();
963 if($event->isCancelled()){
964 return true;
965 }
966
967 $this->player->getInventory()->setItem($packet->inventorySlot, $event->getNewBook());
968
969 return true;
970 }
971
972 public function handleModalFormResponse(ModalFormResponsePacket $packet) : bool{
973 if($packet->cancelReason !== null){
974 //TODO: make APIs for this to allow plugins to use this information
975 return $this->player->onFormSubmit($packet->formId, null);
976 }elseif($packet->formData !== null){
977 try{
978 $responseData = json_decode($packet->formData, true, self::MAX_FORM_RESPONSE_DEPTH, JSON_THROW_ON_ERROR);
979 }catch(\JsonException $e){
980 throw PacketHandlingException::wrap($e, "Failed to decode form response data");
981 }
982 return $this->player->onFormSubmit($packet->formId, $responseData);
983 }else{
984 throw new PacketHandlingException("Expected either formData or cancelReason to be set in ModalFormResponsePacket");
985 }
986 }
987
988 public function handleServerSettingsRequest(ServerSettingsRequestPacket $packet) : bool{
989 return false; //TODO: GUI stuff
990 }
991
992 public function handleLabTable(LabTablePacket $packet) : bool{
993 return false; //TODO
994 }
995
996 public function handleLecternUpdate(LecternUpdatePacket $packet) : bool{
997 $pos = $packet->blockPosition;
998 $chunkX = $pos->getX() >> Chunk::COORD_BIT_SIZE;
999 $chunkZ = $pos->getZ() >> Chunk::COORD_BIT_SIZE;
1000 $world = $this->player->getWorld();
1001 if(!$world->isChunkLoaded($chunkX, $chunkZ) || $world->isChunkLocked($chunkX, $chunkZ)){
1002 return false;
1003 }
1004
1005 $lectern = $world->getBlockAt($pos->getX(), $pos->getY(), $pos->getZ());
1006 if($lectern instanceof Lectern && $this->player->canInteract($lectern->getPosition(), 15)){
1007 if(!$lectern->onPageTurn($packet->page)){
1008 $this->syncBlocksNearby($lectern->getPosition(), null);
1009 }
1010 return true;
1011 }
1012
1013 return false;
1014 }
1015
1016 public function handleNetworkStackLatency(NetworkStackLatencyPacket $packet) : bool{
1017 return true; //TODO: implement this properly - this is here to silence debug spam from MCPE dev builds
1018 }
1019
1020 public function handleLevelSoundEvent(LevelSoundEventPacket $packet) : bool{
1021 /*
1022 * We don't handle this - all sounds are handled by the server now.
1023 * However, some plugins find this useful to detect events like left-click-air, which doesn't have any other
1024 * action bound to it.
1025 * In addition, we use this handler to silence debug noise, since this packet is frequently sent by the client.
1026 */
1027 return true;
1028 }
1029
1030 public function handleEmote(EmotePacket $packet) : bool{
1031 $this->player->emote($packet->getEmoteId());
1032 return true;
1033 }
1034}
sidesArray(bool $keys=false, int $step=1)
Definition Vector3.php:187
getSide(int $side, int $step=1)
Definition Vector3.php:120
static translate(int $containerInterfaceId, int $currentWindowId, int $slotId)