PocketMine-MP 5.35.1 git-e32e836dad793a3a3c8ddd8927c00e112b1e576a
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
92use pocketmine\network\mcpe\protocol\types\inventory\PredictedResult;
109use function array_push;
110use function count;
111use function fmod;
112use function get_debug_type;
113use function implode;
114use function is_infinite;
115use function is_nan;
116use function json_decode;
117use function max;
118use function mb_strlen;
119use function microtime;
120use function sprintf;
121use function str_starts_with;
122use function strlen;
123use const JSON_THROW_ON_ERROR;
124
129 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
130
131 protected float $lastRightClickTime = 0.0;
132 protected ?UseItemTransactionData $lastRightClickData = null;
133
134 protected ?Vector3 $lastPlayerAuthInputPosition = null;
135 protected ?float $lastPlayerAuthInputYaw = null;
136 protected ?float $lastPlayerAuthInputPitch = null;
137 protected ?BitSet $lastPlayerAuthInputFlags = null;
138
139 protected ?BlockPosition $lastBlockAttacked = 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($this->lastPlayerAuthInputFlags === null || !$inputFlags->equals($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 $useItemTransaction = $packet->getItemInteractionData();
254 if($useItemTransaction !== null){
255 if(count($useItemTransaction->getTransactionData()->getActions()) > 100){
256 throw new PacketHandlingException("Too many actions in item use transaction");
257 }
258
259 $this->inventoryManager->setCurrentItemStackRequestId($useItemTransaction->getRequestId());
260 $this->inventoryManager->addRawPredictedSlotChanges($useItemTransaction->getTransactionData()->getActions());
261 if(!$this->handleUseItemTransaction($useItemTransaction->getTransactionData())){
262 $packetHandled = false;
263 $this->session->getLogger()->debug("Unhandled transaction in PlayerAuthInputPacket (type " . $useItemTransaction->getTransactionData()->getActionType() . ")");
264 }else{
265 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
266 }
267 $this->inventoryManager->setCurrentItemStackRequestId(null);
268 }
269
270 $itemStackRequest = $packet->getItemStackRequest();
271 $itemStackResponseBuilder = $itemStackRequest !== null ? $this->handleSingleItemStackRequest($itemStackRequest) : null;
272
273 //itemstack request or transaction may set predictions for the outcome of these actions, so these need to be
274 //processed last
275 $blockActions = $packet->getBlockActions();
276 if($blockActions !== null){
277 if(count($blockActions) > 100){
278 throw new PacketHandlingException("Too many block actions in PlayerAuthInputPacket");
279 }
280 foreach(Utils::promoteKeys($blockActions) as $k => $blockAction){
281 $actionHandled = false;
282 if($blockAction instanceof PlayerBlockActionStopBreak){
283 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), new BlockPosition(0, 0, 0), 0);
284 }elseif($blockAction instanceof PlayerBlockActionWithBlockInfo){
285 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), $blockAction->getBlockPosition(), $blockAction->getFace());
286 }
287
288 if(!$actionHandled){
289 $packetHandled = false;
290 $this->session->getLogger()->debug("Unhandled player block action at offset $k in PlayerAuthInputPacket");
291 }
292 }
293 }
294
295 if($itemStackRequest !== null){
296 $itemStackResponse = $itemStackResponseBuilder?->build() ?? new ItemStackResponse(ItemStackResponse::RESULT_ERROR, $itemStackRequest->getRequestId());
297 $this->session->sendDataPacket(ItemStackResponsePacket::create([$itemStackResponse]));
298 }
299
300 return $packetHandled;
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->getMainHandItem();
312 if($item->isNull()){
313 return false;
314 }
315 $this->player->broadcastAnimation(new ConsumingItemAnimation($this->player, $item));
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->requestSyncSlot($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 $window = $this->inventoryManager->getInventoryWindow($inventory) ?? throw new AssumptionFailedError("This should never happen");
469 $builder->getActionBuilder($window)->setItem($sourceSlot, $sourceSlotItem);
470 $builder->addAction(new DropItemAction($droppedItem));
471
472 $transaction = new InventoryTransaction($this->player, $builder->generateActions());
473 return $this->executeInventoryTransaction($transaction, $itemStackRequestId);
474 }
475
476 private function handleUseItemTransaction(UseItemTransactionData $data) : bool{
477 $this->player->selectHotbarSlot($data->getHotbarSlot());
478
479 switch($data->getActionType()){
480 case UseItemTransactionData::ACTION_CLICK_BLOCK:
481 //TODO: start hack for client spam bug
482 $clickPos = $data->getClickPosition();
483 $spamBug = ($this->lastRightClickData !== null &&
484 microtime(true) - $this->lastRightClickTime < 0.1 && //100ms
485 $this->lastRightClickData->getPlayerPosition()->distanceSquared($data->getPlayerPosition()) < 0.00001 &&
486 $this->lastRightClickData->getBlockPosition()->equals($data->getBlockPosition()) &&
487 $this->lastRightClickData->getClickPosition()->distanceSquared($clickPos) < 0.00001 //signature spam bug has 0 distance, but allow some error
488 );
489 //get rid of continued spam if the player clicks and holds right-click
490 $this->lastRightClickData = $data;
491 $this->lastRightClickTime = microtime(true);
492 if($spamBug){
493 return true;
494 }
495 //TODO: end hack for client spam bug
496
497 $face = self::deserializeFacing($data->getFace());
498
499 $blockPos = $data->getBlockPosition();
500 $vBlockPos = new Vector3($blockPos->getX(), $blockPos->getY(), $blockPos->getZ());
501 $this->player->interactBlock($vBlockPos, $face, $clickPos);
502 if($data->getClientInteractPrediction() === PredictedResult::SUCCESS){
503 //always sync this in case plugins caused a different result than the client expected
504 //we *could* try to enhance detection of plugin-altered behaviour, but this would require propagating
505 //more information up the stack. For now I think this is good enough.
506 //if only the client would tell us what blocks it thinks changed...
507 $this->syncBlocksNearby($vBlockPos, $face);
508 }
509 return true;
510 case UseItemTransactionData::ACTION_CLICK_AIR:
511 if($this->player->isUsingItem()){
512 if(!$this->player->consumeHeldItem()){
513 $hungerAttr = $this->player->getAttributeMap()->get(Attribute::HUNGER) ?? throw new AssumptionFailedError();
514 $hungerAttr->markSynchronized(false);
515 }
516 return true;
517 }
518 $this->player->useHeldItem();
519 return true;
520 }
521
522 return false;
523 }
524
528 private static function deserializeFacing(int $facing) : Facing{
529 //TODO: dodgy use of network facing values as internal values here - they may not be the same in the future
530 $case = Facing::tryFrom($facing);
531 if($case === null){
532 throw new PacketHandlingException("Invalid facing value $facing");
533 }
534 return $case;
535 }
536
540 private function syncBlocksNearby(Vector3 $blockPos, ?Facing $face) : void{
541 if($blockPos->distanceSquared($this->player->getLocation()) < 10000){
542 $blocks = $blockPos->sidesArray();
543 if($face !== null){
544 $sidePos = $blockPos->getSide($face);
545
547 array_push($blocks, ...$sidePos->sidesArray()); //getAllSides() on each of these will include $blockPos and $sidePos because they are next to each other
548 }else{
549 $blocks[] = $blockPos;
550 }
551 foreach($this->player->getWorld()->createBlockUpdatePackets($blocks) as $packet){
552 $this->session->sendDataPacket($packet);
553 }
554 }
555 }
556
557 private function handleUseItemOnEntityTransaction(UseItemOnEntityTransactionData $data) : bool{
558 $target = $this->player->getWorld()->getEntity($data->getActorRuntimeId());
559 if($target === null){
560 return false;
561 }
562
563 $this->player->selectHotbarSlot($data->getHotbarSlot());
564
565 switch($data->getActionType()){
566 case UseItemOnEntityTransactionData::ACTION_INTERACT:
567 $this->player->interactEntity($target, $data->getClickPosition());
568 return true;
569 case UseItemOnEntityTransactionData::ACTION_ATTACK:
570 $this->player->attackEntity($target);
571 return true;
572 }
573
574 return false;
575 }
576
577 private function handleReleaseItemTransaction(ReleaseItemTransactionData $data) : bool{
578 $this->player->selectHotbarSlot($data->getHotbarSlot());
579
580 if($data->getActionType() === ReleaseItemTransactionData::ACTION_RELEASE){
581 $this->player->releaseHeldItem();
582 return true;
583 }
584
585 return false;
586 }
587
588 private function handleSingleItemStackRequest(ItemStackRequest $request) : ?ItemStackResponseBuilder{
589 if(count($request->getActions()) > 60){
590 //recipe book auto crafting can affect all slots of the inventory when consuming inputs or producing outputs
591 //this means there could be as many as 50 CraftingConsumeInput actions or Place (taking the result) actions
592 //in a single request (there are certain ways items can be arranged which will result in the same stack
593 //being taken from multiple times, but this is behaviour with a calculable limit)
594 //this means there SHOULD be AT MOST 53 actions in a single request, but 60 is a nice round number.
595 //n64Stacks = ?
596 //n1Stacks = 45 - n64Stacks
597 //nItemsRequiredFor1Craft = 9
598 //nResults = floor((n1Stacks + (n64Stacks * 64)) / nItemsRequiredFor1Craft)
599 //nTakeActionsTotal = floor(64 / nResults) + max(1, 64 % nResults) + ((nResults * nItemsRequiredFor1Craft) - (n64Stacks * 64))
600 throw new PacketHandlingException("Too many actions in ItemStackRequest");
601 }
602 $executor = new ItemStackRequestExecutor($this->player, $this->inventoryManager, $request);
603 try{
604 $transaction = $executor->generateInventoryTransaction();
605 if($transaction !== null){
606 $result = $this->executeInventoryTransaction($transaction, $request->getRequestId());
607 }else{
608 $result = true; //predictions only, just send responses
609 }
611 $result = false;
612 $this->session->getLogger()->debug("ItemStackRequest #" . $request->getRequestId() . " failed: " . $e->getMessage());
613 $this->session->getLogger()->debug(implode("\n", Utils::printableExceptionInfo($e)));
614 $this->inventoryManager->requestSyncAll();
615 }
616
617 return $result ? $executor->getItemStackResponseBuilder() : null;
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)?->build() ?? new ItemStackResponse(ItemStackResponse::RESULT_ERROR, $request->getRequestId());
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 $extraData) : bool{
686 $pos = new Vector3($blockPosition->getX(), $blockPosition->getY(), $blockPosition->getZ());
687
688 switch($action){
689 case PlayerAction::START_BREAK:
690 case PlayerAction::CONTINUE_DESTROY_BLOCK: //destroy the next block while holding down left click
691 $face = self::deserializeFacing($extraData);
692 if($this->lastBlockAttacked !== null && $blockPosition->equals($this->lastBlockAttacked)){
693 //the client will send CONTINUE_DESTROY_BLOCK for the currently targeted block directly before it
694 //sends PREDICT_DESTROY_BLOCK, but also when it starts to break the block
695 //this seems like a bug in the client and would cause spurious left-click events if we allowed it to
696 //be delivered to the player
697 $this->session->getLogger()->debug("Ignoring PlayerAction $action on $pos because we were already destroying this block");
698 break;
699 }
700 if(!$this->player->attackBlock($pos, $face)){
701 $this->syncBlocksNearby($pos, $face);
702 }
703 $this->lastBlockAttacked = $blockPosition;
704
705 break;
706
707 case PlayerAction::ABORT_BREAK:
708 case PlayerAction::STOP_BREAK:
709 $this->player->stopBreakBlock($pos);
710 $this->lastBlockAttacked = null;
711 break;
712 case PlayerAction::START_SLEEPING:
713 //unused
714 break;
715 case PlayerAction::STOP_SLEEPING:
716 $this->player->stopSleep();
717 break;
718 case PlayerAction::CRACK_BREAK:
719 $face = self::deserializeFacing($extraData);
720 $this->player->continueBreakBlock($pos, $face);
721 $this->lastBlockAttacked = $blockPosition;
722 break;
723 case PlayerAction::INTERACT_BLOCK: //TODO: ignored (for now)
724 break;
725 case PlayerAction::CREATIVE_PLAYER_DESTROY_BLOCK:
726 //in server auth block breaking, we get PREDICT_DESTROY_BLOCK anyway, so this action is redundant
727 break;
728 case PlayerAction::PREDICT_DESTROY_BLOCK:
729 if(!$this->player->breakBlock($pos)){
730 $face = self::deserializeFacing($extraData);
731 $this->syncBlocksNearby($pos, $face);
732 }
733 $this->lastBlockAttacked = null;
734 break;
735 case PlayerAction::START_ITEM_USE_ON:
736 case PlayerAction::STOP_ITEM_USE_ON:
737 //TODO: this has no obvious use and seems only used for analytics in vanilla - ignore it
738 break;
739 default:
740 $this->session->getLogger()->debug("Unhandled/unknown player action type " . $action);
741 return false;
742 }
743
744 $this->player->setUsingItem(false);
745
746 return true;
747 }
748
749 public function handleSetActorMotion(SetActorMotionPacket $packet) : bool{
750 return true; //Not used: This packet is (erroneously) sent to the server when the client is riding a vehicle.
751 }
752
753 public function handleAnimate(AnimatePacket $packet) : bool{
754 return true; //Not used
755 }
756
757 public function handleContainerClose(ContainerClosePacket $packet) : bool{
758 $this->inventoryManager->onClientRemoveWindow($packet->windowId);
759 return true;
760 }
761
762 public function handlePlayerHotbar(PlayerHotbarPacket $packet) : bool{
763 return true; //this packet is useless
764 }
765
769 private function updateSignText(CompoundTag $nbt, string $tagName, bool $frontFace, BaseSign $block, Vector3 $pos) : bool{
770 $textTag = $nbt->getTag($tagName);
771 if(!$textTag instanceof CompoundTag){
772 throw new PacketHandlingException("Invalid tag type " . get_debug_type($textTag) . " for tag \"$tagName\" in sign update data");
773 }
774 $textBlobTag = $textTag->getTag(Sign::TAG_TEXT_BLOB);
775 if(!$textBlobTag instanceof StringTag){
776 throw new PacketHandlingException("Invalid tag type " . get_debug_type($textBlobTag) . " for tag \"" . Sign::TAG_TEXT_BLOB . "\" in sign update data");
777 }
778
779 try{
780 $text = SignText::fromBlob($textBlobTag->getValue());
781 }catch(\InvalidArgumentException $e){
782 throw PacketHandlingException::wrap($e, "Invalid sign text update");
783 }
784
785 $oldText = $block->getFaceText($frontFace);
786 if($text->getLines() === $oldText->getLines()){
787 return false;
788 }
789
790 try{
791 if(!$block->updateFaceText($this->player, $frontFace, $text)){
792 foreach($this->player->getWorld()->createBlockUpdatePackets([$pos]) as $updatePacket){
793 $this->session->sendDataPacket($updatePacket);
794 }
795 return false;
796 }
797 return true;
798 }catch(\UnexpectedValueException $e){
799 throw PacketHandlingException::wrap($e);
800 }
801 }
802
803 public function handleBlockActorData(BlockActorDataPacket $packet) : bool{
804 $pos = new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ());
805 if($pos->distanceSquared($this->player->getLocation()) > 10000){
806 return false;
807 }
808
809 $block = $this->player->getLocation()->getWorld()->getBlock($pos);
810 $nbt = $packet->nbt->getRoot();
811 if(!($nbt instanceof CompoundTag)) throw new AssumptionFailedError("PHPStan should ensure this is a CompoundTag"); //for phpstorm's benefit
812
813 if($block instanceof BaseSign){
814 if(!$this->updateSignText($nbt, Sign::TAG_FRONT_TEXT, true, $block, $pos)){
815 //only one side can be updated at a time
816 $this->updateSignText($nbt, Sign::TAG_BACK_TEXT, false, $block, $pos);
817 }
818
819 return true;
820 }
821
822 return false;
823 }
824
825 public function handleSetPlayerGameType(SetPlayerGameTypePacket $packet) : bool{
826 $gameMode = $this->session->getTypeConverter()->protocolGameModeToCore($packet->gamemode);
827 if($gameMode !== $this->player->getGamemode()){
828 //Set this back to default. TODO: handle this properly
829 $this->session->syncGameMode($this->player->getGamemode(), true);
830 }
831 return true;
832 }
833
834 public function handleSpawnExperienceOrb(SpawnExperienceOrbPacket $packet) : bool{
835 return false; //TODO
836 }
837
838 public function handleMapInfoRequest(MapInfoRequestPacket $packet) : bool{
839 return false; //TODO
840 }
841
842 public function handleRequestChunkRadius(RequestChunkRadiusPacket $packet) : bool{
843 $this->player->setViewDistance($packet->radius);
844
845 return true;
846 }
847
848 public function handleBossEvent(BossEventPacket $packet) : bool{
849 return false; //TODO
850 }
851
852 public function handleShowCredits(ShowCreditsPacket $packet) : bool{
853 return false; //TODO: handle resume
854 }
855
856 public function handleCommandRequest(CommandRequestPacket $packet) : bool{
857 if(str_starts_with($packet->command, '/')){
858 $this->player->chat($packet->command);
859 return true;
860 }
861 return false;
862 }
863
864 public function handleCommandBlockUpdate(CommandBlockUpdatePacket $packet) : bool{
865 return false; //TODO
866 }
867
868 public function handlePlayerSkin(PlayerSkinPacket $packet) : bool{
869 if($packet->skin->getFullSkinId() === $this->lastRequestedFullSkinId){
870 //TODO: HACK! In 1.19.60, the client sends its skin back to us if we sent it a skin different from the one
871 //it's using. We need to prevent this from causing a feedback loop.
872 $this->session->getLogger()->debug("Refused duplicate skin change request");
873 return true;
874 }
875 $this->lastRequestedFullSkinId = $packet->skin->getFullSkinId();
876
877 $this->session->getLogger()->debug("Processing skin change request");
878 try{
879 $skin = $this->session->getTypeConverter()->getSkinAdapter()->fromSkinData($packet->skin);
880 }catch(InvalidSkinException $e){
881 throw PacketHandlingException::wrap($e, "Invalid skin in PlayerSkinPacket");
882 }
883 return $this->player->changeSkin($skin, $packet->newSkinName, $packet->oldSkinName);
884 }
885
886 public function handleSubClientLogin(SubClientLoginPacket $packet) : bool{
887 return false; //TODO
888 }
889
893 private function checkBookText(string $string, string $fieldName, int $softLimit, int $hardLimit, bool &$cancel) : string{
894 if(strlen($string) > $hardLimit){
895 throw new PacketHandlingException(sprintf("Book %s must be at most %d bytes, but have %d bytes", $fieldName, $hardLimit, strlen($string)));
896 }
897
898 $result = TextFormat::clean($string, false);
899 //strlen() is O(1), mb_strlen() is O(n)
900 if(strlen($result) > $softLimit * 4 || mb_strlen($result, 'UTF-8') > $softLimit){
901 $cancel = true;
902 $this->session->getLogger()->debug("Cancelled book edit due to $fieldName exceeded soft limit of $softLimit chars");
903 }
904
905 return $result;
906 }
907
908 public function handleBookEdit(BookEditPacket $packet) : bool{
909 $inventory = $this->player->getInventory();
910 if(!$inventory->slotExists($packet->inventorySlot)){
911 return false;
912 }
913 //TODO: break this up into book API things
914 $oldBook = $inventory->getItem($packet->inventorySlot);
915 if(!($oldBook instanceof WritableBook)){
916 return false;
917 }
918
919 $newBook = clone $oldBook;
920 $modifiedPages = [];
921 $cancel = false;
922 switch($packet->type){
923 case BookEditPacket::TYPE_REPLACE_PAGE:
924 $text = self::checkBookText($packet->text, "page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
925 $newBook->setPageText($packet->pageNumber, $text);
926 $modifiedPages[] = $packet->pageNumber;
927 break;
928 case BookEditPacket::TYPE_ADD_PAGE:
929 if(!$newBook->pageExists($packet->pageNumber)){
930 //this may only come before a page which already exists
931 //TODO: the client can send insert-before actions on trailing client-side pages which cause odd behaviour on the server
932 return false;
933 }
934 $text = self::checkBookText($packet->text, "page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
935 $newBook->insertPage($packet->pageNumber, $text);
936 $modifiedPages[] = $packet->pageNumber;
937 break;
938 case BookEditPacket::TYPE_DELETE_PAGE:
939 if(!$newBook->pageExists($packet->pageNumber)){
940 return false;
941 }
942 $newBook->deletePage($packet->pageNumber);
943 $modifiedPages[] = $packet->pageNumber;
944 break;
945 case BookEditPacket::TYPE_SWAP_PAGES:
946 if(!$newBook->pageExists($packet->pageNumber) || !$newBook->pageExists($packet->secondaryPageNumber)){
947 //the client will create pages on its own without telling us until it tries to switch them
948 $newBook->addPage(max($packet->pageNumber, $packet->secondaryPageNumber));
949 }
950 $newBook->swapPages($packet->pageNumber, $packet->secondaryPageNumber);
951 $modifiedPages = [$packet->pageNumber, $packet->secondaryPageNumber];
952 break;
953 case BookEditPacket::TYPE_SIGN_BOOK:
954 $title = self::checkBookText($packet->title, "title", 16, Limits::INT16_MAX, $cancel);
955 //this one doesn't have a limit in vanilla, so we have to improvise
956 $author = self::checkBookText($packet->author, "author", 256, Limits::INT16_MAX, $cancel);
957
958 $newBook = VanillaItems::WRITTEN_BOOK()
959 ->setPages($oldBook->getPages())
960 ->setAuthor($author)
961 ->setTitle($title)
962 ->setGeneration(WrittenBook::GENERATION_ORIGINAL);
963 break;
964 default:
965 return false;
966 }
967
968 //for redundancy, in case of protocol changes, we don't want to pass these directly
969 $action = match($packet->type){
970 BookEditPacket::TYPE_REPLACE_PAGE => PlayerEditBookEvent::ACTION_REPLACE_PAGE,
971 BookEditPacket::TYPE_ADD_PAGE => PlayerEditBookEvent::ACTION_ADD_PAGE,
972 BookEditPacket::TYPE_DELETE_PAGE => PlayerEditBookEvent::ACTION_DELETE_PAGE,
973 BookEditPacket::TYPE_SWAP_PAGES => PlayerEditBookEvent::ACTION_SWAP_PAGES,
974 BookEditPacket::TYPE_SIGN_BOOK => PlayerEditBookEvent::ACTION_SIGN_BOOK,
975 default => throw new AssumptionFailedError("We already filtered unknown types in the switch above")
976 };
977
978 /*
979 * Plugins may have created books with more than 50 pages; we allow plugins to do this, but not players.
980 * Don't allow the page count to grow past 50, but allow deleting, swapping or altering text of existing pages.
981 */
982 $oldPageCount = count($oldBook->getPages());
983 $newPageCount = count($newBook->getPages());
984 if(($newPageCount > $oldPageCount && $newPageCount > 50)){
985 $this->session->getLogger()->debug("Cancelled book edit due to adding too many pages (new page count would be $newPageCount)");
986 $cancel = true;
987 }
988
989 $event = new PlayerEditBookEvent($this->player, $oldBook, $newBook, $action, $modifiedPages);
990 if($cancel){
991 $event->cancel();
992 }
993
994 $event->call();
995 if($event->isCancelled()){
996 return true;
997 }
998
999 $this->player->getInventory()->setItem($packet->inventorySlot, $event->getNewBook());
1000
1001 return true;
1002 }
1003
1004 public function handleModalFormResponse(ModalFormResponsePacket $packet) : bool{
1005 if($packet->cancelReason !== null){
1006 //TODO: make APIs for this to allow plugins to use this information
1007 return $this->player->onFormSubmit($packet->formId, null);
1008 }elseif($packet->formData !== null){
1009 try{
1010 $responseData = json_decode($packet->formData, true, self::MAX_FORM_RESPONSE_DEPTH, JSON_THROW_ON_ERROR);
1011 }catch(\JsonException $e){
1012 throw PacketHandlingException::wrap($e, "Failed to decode form response data");
1013 }
1014 return $this->player->onFormSubmit($packet->formId, $responseData);
1015 }else{
1016 throw new PacketHandlingException("Expected either formData or cancelReason to be set in ModalFormResponsePacket");
1017 }
1018 }
1019
1020 public function handleServerSettingsRequest(ServerSettingsRequestPacket $packet) : bool{
1021 return false; //TODO: GUI stuff
1022 }
1023
1024 public function handleLabTable(LabTablePacket $packet) : bool{
1025 return false; //TODO
1026 }
1027
1028 public function handleLecternUpdate(LecternUpdatePacket $packet) : bool{
1029 $pos = $packet->blockPosition;
1030 $chunkX = $pos->getX() >> Chunk::COORD_BIT_SIZE;
1031 $chunkZ = $pos->getZ() >> Chunk::COORD_BIT_SIZE;
1032 $world = $this->player->getWorld();
1033 if(!$world->isChunkLoaded($chunkX, $chunkZ) || $world->isChunkLocked($chunkX, $chunkZ)){
1034 return false;
1035 }
1036
1037 $lectern = $world->getBlockAt($pos->getX(), $pos->getY(), $pos->getZ());
1038 if($lectern instanceof Lectern && $this->player->canInteract($lectern->getPosition(), 15)){
1039 if(!$lectern->onPageTurn($packet->page)){
1040 $this->syncBlocksNearby($lectern->getPosition(), null);
1041 }
1042 return true;
1043 }
1044
1045 return false;
1046 }
1047
1048 public function handleNetworkStackLatency(NetworkStackLatencyPacket $packet) : bool{
1049 return true; //TODO: implement this properly - this is here to silence debug spam from MCPE dev builds
1050 }
1051
1052 public function handleLevelSoundEvent(LevelSoundEventPacket $packet) : bool{
1053 /*
1054 * We don't handle this - all sounds are handled by the server now.
1055 * However, some plugins find this useful to detect events like left-click-air, which doesn't have any other
1056 * action bound to it.
1057 * In addition, we use this handler to silence debug noise, since this packet is frequently sent by the client.
1058 */
1059 return true;
1060 }
1061
1062 public function handleEmote(EmotePacket $packet) : bool{
1063 $this->player->emote($packet->getEmoteId());
1064 return true;
1065 }
1066}
updateFaceText(Player $author, bool $frontFace, SignText $text)
Definition BaseSign.php:273
getSide(Facing $side, int $step=1)
Definition Vector3.php:121
sidesArray(bool $keys=false, int $step=1)
Definition Vector3.php:188
static translate(int $containerInterfaceId, int $currentWindowId, int $slotId)