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