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