PocketMine-MP 5.33.2 git-1133d49c924b4358c79d44eeb97dcbf56cb4d1eb
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
108use function array_push;
109use function count;
110use function fmod;
111use function get_debug_type;
112use function implode;
113use function is_infinite;
114use function is_nan;
115use function json_decode;
116use function max;
117use function mb_strlen;
118use function microtime;
119use function sprintf;
120use function str_starts_with;
121use function strlen;
122use const JSON_THROW_ON_ERROR;
123
128 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
129
130 protected float $lastRightClickTime = 0.0;
131 protected ?UseItemTransactionData $lastRightClickData = null;
132
133 protected ?Vector3 $lastPlayerAuthInputPosition = null;
134 protected ?float $lastPlayerAuthInputYaw = null;
135 protected ?float $lastPlayerAuthInputPitch = null;
136 protected ?BitSet $lastPlayerAuthInputFlags = null;
137
138 protected ?BlockPosition $lastBlockAttacked = 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(BitSet $inputFlags, int $startFlag, int $stopFlag) : ?bool{
165 $enabled = $inputFlags->get($startFlag);
166 $disabled = $inputFlags->get($stopFlag);
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($this->lastPlayerAuthInputFlags === null || !$inputFlags->equals($this->lastPlayerAuthInputFlags)){
216 $this->lastPlayerAuthInputFlags = $inputFlags;
217
218 $sneaking = $inputFlags->get(PlayerAuthInputFlags::SNEAKING);
219 if($this->player->isSneaking() === $sneaking){
220 $sneaking = null;
221 }
222 $sprinting = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SPRINTING, PlayerAuthInputFlags::STOP_SPRINTING);
223 $swimming = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SWIMMING, PlayerAuthInputFlags::STOP_SWIMMING);
224 $gliding = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_GLIDING, PlayerAuthInputFlags::STOP_GLIDING);
225 $flying = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_FLYING, PlayerAuthInputFlags::STOP_FLYING);
226 $mismatch =
227 ($sneaking !== null && !$this->player->toggleSneak($sneaking)) |
228 ($sprinting !== null && !$this->player->toggleSprint($sprinting)) |
229 ($swimming !== null && !$this->player->toggleSwim($swimming)) |
230 ($gliding !== null && !$this->player->toggleGlide($gliding)) |
231 ($flying !== null && !$this->player->toggleFlight($flying));
232 if((bool) $mismatch){
233 $this->player->sendData([$this->player]);
234 }
235
236 if($inputFlags->get(PlayerAuthInputFlags::START_JUMPING)){
237 $this->player->jump();
238 }
239 if($inputFlags->get(PlayerAuthInputFlags::MISSED_SWING)){
240 $this->player->missSwing();
241 }
242 }
243
244 if(!$this->forceMoveSync && $hasMoved){
245 $this->lastPlayerAuthInputPosition = $rawPos;
246 //TODO: this packet has WAYYYYY more useful information that we're not using
247 $this->player->handleMovement($newPos);
248 }
249
250 $packetHandled = true;
251
252 $useItemTransaction = $packet->getItemInteractionData();
253 if($useItemTransaction !== null){
254 if(count($useItemTransaction->getTransactionData()->getActions()) > 100){
255 throw new PacketHandlingException("Too many actions in item use transaction");
256 }
257
258 $this->inventoryManager->setCurrentItemStackRequestId($useItemTransaction->getRequestId());
259 $this->inventoryManager->addRawPredictedSlotChanges($useItemTransaction->getTransactionData()->getActions());
260 if(!$this->handleUseItemTransaction($useItemTransaction->getTransactionData())){
261 $packetHandled = false;
262 $this->session->getLogger()->debug("Unhandled transaction in PlayerAuthInputPacket (type " . $useItemTransaction->getTransactionData()->getActionType() . ")");
263 }else{
264 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
265 }
266 $this->inventoryManager->setCurrentItemStackRequestId(null);
267 }
268
269 $itemStackRequest = $packet->getItemStackRequest();
270 $itemStackResponseBuilder = $itemStackRequest !== null ? $this->handleSingleItemStackRequest($itemStackRequest) : null;
271
272 //itemstack request or transaction may set predictions for the outcome of these actions, so these need to be
273 //processed last
274 $blockActions = $packet->getBlockActions();
275 if($blockActions !== null){
276 if(count($blockActions) > 100){
277 throw new PacketHandlingException("Too many block actions in PlayerAuthInputPacket");
278 }
279 foreach(Utils::promoteKeys($blockActions) as $k => $blockAction){
280 $actionHandled = false;
281 if($blockAction instanceof PlayerBlockActionStopBreak){
282 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), new BlockPosition(0, 0, 0), 0);
283 }elseif($blockAction instanceof PlayerBlockActionWithBlockInfo){
284 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), $blockAction->getBlockPosition(), $blockAction->getFace());
285 }
286
287 if(!$actionHandled){
288 $packetHandled = false;
289 $this->session->getLogger()->debug("Unhandled player block action at offset $k in PlayerAuthInputPacket");
290 }
291 }
292 }
293
294 if($itemStackRequest !== null){
295 $itemStackResponse = $itemStackResponseBuilder?->build() ?? new ItemStackResponse(ItemStackResponse::RESULT_ERROR, $itemStackRequest->getRequestId());
296 $this->session->sendDataPacket(ItemStackResponsePacket::create([$itemStackResponse]));
297 }
298
299 return $packetHandled;
300 }
301
302 public function handleActorEvent(ActorEventPacket $packet) : bool{
303 if($packet->actorRuntimeId !== $this->player->getId()){
304 //TODO HACK: EATING_ITEM is sent back to the server when the server sends it for other players (1.14 bug, maybe earlier)
305 return $packet->actorRuntimeId === ActorEvent::EATING_ITEM;
306 }
307
308 switch($packet->eventId){
309 case ActorEvent::EATING_ITEM: //TODO: ignore this and handle it server-side
310 $item = $this->player->getMainHandItem();
311 if($item->isNull()){
312 return false;
313 }
314 $this->player->broadcastAnimation(new ConsumingItemAnimation($this->player, $item));
315 break;
316 default:
317 return false;
318 }
319
320 return true;
321 }
322
323 public function handleInventoryTransaction(InventoryTransactionPacket $packet) : bool{
324 $result = true;
325
326 if(count($packet->trData->getActions()) > 50){
327 throw new PacketHandlingException("Too many actions in inventory transaction");
328 }
329 if(count($packet->requestChangedSlots) > 10){
330 throw new PacketHandlingException("Too many slot sync requests in inventory transaction");
331 }
332
333 $this->inventoryManager->setCurrentItemStackRequestId($packet->requestId);
334 $this->inventoryManager->addRawPredictedSlotChanges($packet->trData->getActions());
335
336 if($packet->trData instanceof NormalTransactionData){
337 $result = $this->handleNormalTransaction($packet->trData, $packet->requestId);
338 }elseif($packet->trData instanceof MismatchTransactionData){
339 $this->session->getLogger()->debug("Mismatch transaction received");
340 $this->inventoryManager->requestSyncAll();
341 $result = true;
342 }elseif($packet->trData instanceof UseItemTransactionData){
343 $result = $this->handleUseItemTransaction($packet->trData);
344 }elseif($packet->trData instanceof UseItemOnEntityTransactionData){
345 $result = $this->handleUseItemOnEntityTransaction($packet->trData);
346 }elseif($packet->trData instanceof ReleaseItemTransactionData){
347 $result = $this->handleReleaseItemTransaction($packet->trData);
348 }
349
350 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
351
352 //requestChangedSlots asks the server to always send out the contents of the specified slots, even if they
353 //haven't changed. Handling these is necessary to ensure the client inventory stays in sync if the server
354 //rejects the transaction. The most common example of this is equipping armor by right-click, which doesn't send
355 //a legacy prediction action for the destination armor slot.
356 foreach($packet->requestChangedSlots as $containerInfo){
357 foreach($containerInfo->getChangedSlotIndexes() as $netSlot){
358 [$windowId, $slot] = ItemStackContainerIdTranslator::translate($containerInfo->getContainerId(), $this->inventoryManager->getCurrentWindowId(), $netSlot);
359 $inventoryAndSlot = $this->inventoryManager->locateWindowAndSlot($windowId, $slot);
360 if($inventoryAndSlot !== null){ //trigger the normal slot sync logic
361 $this->inventoryManager->requestSyncSlot($inventoryAndSlot[0], $inventoryAndSlot[1]);
362 }
363 }
364 }
365
366 $this->inventoryManager->setCurrentItemStackRequestId(null);
367 return $result;
368 }
369
370 private function executeInventoryTransaction(InventoryTransaction $transaction, int $requestId) : bool{
371 $this->player->setUsingItem(false);
372
373 $this->inventoryManager->setCurrentItemStackRequestId($requestId);
374 $this->inventoryManager->addTransactionPredictedSlotChanges($transaction);
375 try{
376 $transaction->execute();
378 $this->inventoryManager->requestSyncAll();
379 $logger = $this->session->getLogger();
380 $logger->debug("Invalid inventory transaction $requestId: " . $e->getMessage());
381
382 return false;
384 $this->session->getLogger()->debug("Inventory transaction $requestId cancelled by a plugin");
385
386 return false;
387 }finally{
388 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
389 $this->inventoryManager->setCurrentItemStackRequestId(null);
390 }
391
392 return true;
393 }
394
395 private function handleNormalTransaction(NormalTransactionData $data, int $itemStackRequestId) : bool{
396 //When the ItemStackRequest system is used, this transaction type is used for dropping items by pressing Q.
397 //I don't know why they don't just use ItemStackRequest for that too, which already supports dropping items by
398 //clicking them outside an open inventory menu, but for now it is what it is.
399 //Fortunately, this means we can be much stricter about the validation criteria.
400
401 $actionCount = count($data->getActions());
402 if($actionCount > 2){
403 if($actionCount > 5){
404 throw new PacketHandlingException("Too many actions ($actionCount) in normal inventory transaction");
405 }
406
407 //Due to a bug in the game, this transaction type is still sent when a player edits a book. We don't need
408 //these transactions for editing books, since we have BookEditPacket, so we can just ignore them.
409 $this->session->getLogger()->debug("Ignoring normal inventory transaction with $actionCount actions (drop-item should have exactly 2 actions)");
410 return false;
411 }
412
413 $sourceSlot = null;
414 $clientItemStack = null;
415 $droppedCount = null;
416
417 foreach($data->getActions() as $networkInventoryAction){
418 if($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_WORLD && $networkInventoryAction->inventorySlot === NetworkInventoryAction::ACTION_MAGIC_SLOT_DROP_ITEM){
419 $droppedCount = $networkInventoryAction->newItem->getItemStack()->getCount();
420 if($droppedCount <= 0){
421 throw new PacketHandlingException("Expected positive count for dropped item");
422 }
423 }elseif($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_CONTAINER && $networkInventoryAction->windowId === ContainerIds::INVENTORY){
424 //mobile players can drop an item from a non-selected hotbar slot
425 $sourceSlot = $networkInventoryAction->inventorySlot;
426 $clientItemStack = $networkInventoryAction->oldItem->getItemStack();
427 }else{
428 $this->session->getLogger()->debug("Unexpected inventory action type $networkInventoryAction->sourceType in drop item transaction");
429 return false;
430 }
431 }
432 if($sourceSlot === null || $clientItemStack === null || $droppedCount === null){
433 $this->session->getLogger()->debug("Missing information in drop item transaction, need source slot, client item stack and dropped count");
434 return false;
435 }
436
437 $inventory = $this->player->getInventory();
438
439 if(!$inventory->slotExists($sourceSlot)){
440 return false; //TODO: size desync??
441 }
442
443 $sourceSlotItem = $inventory->getItem($sourceSlot);
444 if($sourceSlotItem->getCount() < $droppedCount){
445 return false;
446 }
447 $serverItemStack = $this->session->getTypeConverter()->coreItemStackToNet($sourceSlotItem);
448 //Sadly we don't have itemstack IDs here, so we have to compare the basic item properties to ensure that we're
449 //dropping the item the client expects (inventory might be out of sync with the client).
450 if(
451 $serverItemStack->getId() !== $clientItemStack->getId() ||
452 $serverItemStack->getMeta() !== $clientItemStack->getMeta() ||
453 $serverItemStack->getCount() !== $clientItemStack->getCount() ||
454 $serverItemStack->getBlockRuntimeId() !== $clientItemStack->getBlockRuntimeId()
455 //Raw extraData may not match because of TAG_Compound key ordering differences, and decoding it to compare
456 //is costly. Assume that we're in sync if id+meta+count+runtimeId match.
457 //NB: Make sure $clientItemStack isn't used to create the dropped item, as that would allow the client
458 //to change the item NBT since we're not validating it.
459 ){
460 return false;
461 }
462
463 //this modifies $sourceSlotItem
464 $droppedItem = $sourceSlotItem->pop($droppedCount);
465
466 $builder = new TransactionBuilder();
467 $window = $this->inventoryManager->getInventoryWindow($inventory) ?? throw new AssumptionFailedError("This should never happen");
468 $builder->getActionBuilder($window)->setItem($sourceSlot, $sourceSlotItem);
469 $builder->addAction(new DropItemAction($droppedItem));
470
471 $transaction = new InventoryTransaction($this->player, $builder->generateActions());
472 return $this->executeInventoryTransaction($transaction, $itemStackRequestId);
473 }
474
475 private function handleUseItemTransaction(UseItemTransactionData $data) : bool{
476 $this->player->selectHotbarSlot($data->getHotbarSlot());
477
478 switch($data->getActionType()){
479 case UseItemTransactionData::ACTION_CLICK_BLOCK:
480 //TODO: start hack for client spam bug
481 $clickPos = $data->getClickPosition();
482 $spamBug = ($this->lastRightClickData !== null &&
483 microtime(true) - $this->lastRightClickTime < 0.1 && //100ms
484 $this->lastRightClickData->getPlayerPosition()->distanceSquared($data->getPlayerPosition()) < 0.00001 &&
485 $this->lastRightClickData->getBlockPosition()->equals($data->getBlockPosition()) &&
486 $this->lastRightClickData->getClickPosition()->distanceSquared($clickPos) < 0.00001 //signature spam bug has 0 distance, but allow some error
487 );
488 //get rid of continued spam if the player clicks and holds right-click
489 $this->lastRightClickData = $data;
490 $this->lastRightClickTime = microtime(true);
491 if($spamBug){
492 return true;
493 }
494 //TODO: end hack for client spam bug
495
496 $face = self::deserializeFacing($data->getFace());
497
498 $blockPos = $data->getBlockPosition();
499 $vBlockPos = new Vector3($blockPos->getX(), $blockPos->getY(), $blockPos->getZ());
500 $this->player->interactBlock($vBlockPos, $face, $clickPos);
501 //always sync this in case plugins caused a different result than the client expected
502 //we *could* try to enhance detection of plugin-altered behaviour, but this would require propagating
503 //more information up the stack. For now I think this is good enough.
504 //if only the client would tell us what blocks it thinks changed...
505 $this->syncBlocksNearby($vBlockPos, $face);
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 deserializeFacing(int $facing) : Facing{
526 //TODO: dodgy use of network facing values as internal values here - they may not be the same in the future
527 $case = Facing::tryFrom($facing);
528 if($case === null){
529 throw new PacketHandlingException("Invalid facing value $facing");
530 }
531 return $case;
532 }
533
537 private function syncBlocksNearby(Vector3 $blockPos, ?Facing $face) : void{
538 if($blockPos->distanceSquared($this->player->getLocation()) < 10000){
539 $blocks = $blockPos->sidesArray();
540 if($face !== null){
541 $sidePos = $blockPos->getSide($face);
542
544 array_push($blocks, ...$sidePos->sidesArray()); //getAllSides() on each of these will include $blockPos and $sidePos because they are next to each other
545 }else{
546 $blocks[] = $blockPos;
547 }
548 foreach($this->player->getWorld()->createBlockUpdatePackets($blocks) as $packet){
549 $this->session->sendDataPacket($packet);
550 }
551 }
552 }
553
554 private function handleUseItemOnEntityTransaction(UseItemOnEntityTransactionData $data) : bool{
555 $target = $this->player->getWorld()->getEntity($data->getActorRuntimeId());
556 if($target === null){
557 return false;
558 }
559
560 $this->player->selectHotbarSlot($data->getHotbarSlot());
561
562 switch($data->getActionType()){
563 case UseItemOnEntityTransactionData::ACTION_INTERACT:
564 $this->player->interactEntity($target, $data->getClickPosition());
565 return true;
566 case UseItemOnEntityTransactionData::ACTION_ATTACK:
567 $this->player->attackEntity($target);
568 return true;
569 }
570
571 return false;
572 }
573
574 private function handleReleaseItemTransaction(ReleaseItemTransactionData $data) : bool{
575 $this->player->selectHotbarSlot($data->getHotbarSlot());
576
577 if($data->getActionType() === ReleaseItemTransactionData::ACTION_RELEASE){
578 $this->player->releaseHeldItem();
579 return true;
580 }
581
582 return false;
583 }
584
585 private function handleSingleItemStackRequest(ItemStackRequest $request) : ?ItemStackResponseBuilder{
586 if(count($request->getActions()) > 60){
587 //recipe book auto crafting can affect all slots of the inventory when consuming inputs or producing outputs
588 //this means there could be as many as 50 CraftingConsumeInput actions or Place (taking the result) actions
589 //in a single request (there are certain ways items can be arranged which will result in the same stack
590 //being taken from multiple times, but this is behaviour with a calculable limit)
591 //this means there SHOULD be AT MOST 53 actions in a single request, but 60 is a nice round number.
592 //n64Stacks = ?
593 //n1Stacks = 45 - n64Stacks
594 //nItemsRequiredFor1Craft = 9
595 //nResults = floor((n1Stacks + (n64Stacks * 64)) / nItemsRequiredFor1Craft)
596 //nTakeActionsTotal = floor(64 / nResults) + max(1, 64 % nResults) + ((nResults * nItemsRequiredFor1Craft) - (n64Stacks * 64))
597 throw new PacketHandlingException("Too many actions in ItemStackRequest");
598 }
599 $executor = new ItemStackRequestExecutor($this->player, $this->inventoryManager, $request);
600 try{
601 $transaction = $executor->generateInventoryTransaction();
602 if($transaction !== null){
603 $result = $this->executeInventoryTransaction($transaction, $request->getRequestId());
604 }else{
605 $result = true; //predictions only, just send responses
606 }
608 $result = false;
609 $this->session->getLogger()->debug("ItemStackRequest #" . $request->getRequestId() . " failed: " . $e->getMessage());
610 $this->session->getLogger()->debug(implode("\n", Utils::printableExceptionInfo($e)));
611 $this->inventoryManager->requestSyncAll();
612 }
613
614 return $result ? $executor->getItemStackResponseBuilder() : null;
615 }
616
617 public function handleItemStackRequest(ItemStackRequestPacket $packet) : bool{
618 $responses = [];
619 if(count($packet->getRequests()) > 80){
620 //TODO: we can probably lower this limit, but this will do for now
621 throw new PacketHandlingException("Too many requests in ItemStackRequestPacket");
622 }
623 foreach($packet->getRequests() as $request){
624 $responses[] = $this->handleSingleItemStackRequest($request)?->build() ?? new ItemStackResponse(ItemStackResponse::RESULT_ERROR, $request->getRequestId());
625 }
626
627 $this->session->sendDataPacket(ItemStackResponsePacket::create($responses));
628
629 return true;
630 }
631
632 public function handleMobEquipment(MobEquipmentPacket $packet) : bool{
633 if($packet->windowId === ContainerIds::OFFHAND){
634 return true; //this happens when we put an item into the offhand
635 }
636 if($packet->windowId === ContainerIds::INVENTORY){
637 $this->inventoryManager->onClientSelectHotbarSlot($packet->hotbarSlot);
638 if(!$this->player->selectHotbarSlot($packet->hotbarSlot)){
639 $this->inventoryManager->syncSelectedHotbarSlot();
640 }
641 return true;
642 }
643 return false;
644 }
645
646 public function handleMobArmorEquipment(MobArmorEquipmentPacket $packet) : bool{
647 return true; //Not used
648 }
649
650 public function handleInteract(InteractPacket $packet) : bool{
651 if($packet->action === InteractPacket::ACTION_MOUSEOVER){
652 //TODO HACK: silence useless spam (MCPE 1.8)
653 //due to some messy Mojang hacks, it sends this when changing the held item now, which causes us to think
654 //the inventory was closed when it wasn't.
655 //this is also sent whenever entity metadata updates, which can get really spammy.
656 //TODO: implement handling for this where it matters
657 return true;
658 }
659 $target = $this->player->getWorld()->getEntity($packet->targetActorRuntimeId);
660 if($target === null){
661 return false;
662 }
663 if($packet->action === InteractPacket::ACTION_OPEN_INVENTORY && $target === $this->player){
664 $this->inventoryManager->onClientOpenMainInventory();
665 return true;
666 }
667 return false; //TODO
668 }
669
670 public function handleBlockPickRequest(BlockPickRequestPacket $packet) : bool{
671 return $this->player->pickBlock(new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ()), $packet->addUserData);
672 }
673
674 public function handleActorPickRequest(ActorPickRequestPacket $packet) : bool{
675 return $this->player->pickEntity($packet->actorUniqueId);
676 }
677
678 public function handlePlayerAction(PlayerActionPacket $packet) : bool{
679 return $this->handlePlayerActionFromData($packet->action, $packet->blockPosition, $packet->face);
680 }
681
682 private function handlePlayerActionFromData(int $action, BlockPosition $blockPosition, int $extraData) : bool{
683 $pos = new Vector3($blockPosition->getX(), $blockPosition->getY(), $blockPosition->getZ());
684
685 switch($action){
686 case PlayerAction::START_BREAK:
687 case PlayerAction::CONTINUE_DESTROY_BLOCK: //destroy the next block while holding down left click
688 $face = self::deserializeFacing($extraData);
689 if($this->lastBlockAttacked !== null && $blockPosition->equals($this->lastBlockAttacked)){
690 //the client will send CONTINUE_DESTROY_BLOCK for the currently targeted block directly before it
691 //sends PREDICT_DESTROY_BLOCK, but also when it starts to break the block
692 //this seems like a bug in the client and would cause spurious left-click events if we allowed it to
693 //be delivered to the player
694 $this->session->getLogger()->debug("Ignoring PlayerAction $action on $pos because we were already destroying this block");
695 break;
696 }
697 if(!$this->player->attackBlock($pos, $face)){
698 $this->syncBlocksNearby($pos, $face);
699 }
700 $this->lastBlockAttacked = $blockPosition;
701
702 break;
703
704 case PlayerAction::ABORT_BREAK:
705 case PlayerAction::STOP_BREAK:
706 $this->player->stopBreakBlock($pos);
707 $this->lastBlockAttacked = null;
708 break;
709 case PlayerAction::START_SLEEPING:
710 //unused
711 break;
712 case PlayerAction::STOP_SLEEPING:
713 $this->player->stopSleep();
714 break;
715 case PlayerAction::CRACK_BREAK:
716 $face = self::deserializeFacing($extraData);
717 $this->player->continueBreakBlock($pos, $face);
718 $this->lastBlockAttacked = $blockPosition;
719 break;
720 case PlayerAction::INTERACT_BLOCK: //TODO: ignored (for now)
721 break;
722 case PlayerAction::CREATIVE_PLAYER_DESTROY_BLOCK:
723 //TODO: do we need to handle this?
724 case PlayerAction::PREDICT_DESTROY_BLOCK:
725 if(!$this->player->breakBlock($pos)){
726 $face = self::deserializeFacing($extraData);
727 $this->syncBlocksNearby($pos, $face);
728 }
729 $this->lastBlockAttacked = null;
730 break;
731 case PlayerAction::START_ITEM_USE_ON:
732 case PlayerAction::STOP_ITEM_USE_ON:
733 //TODO: this has no obvious use and seems only used for analytics in vanilla - ignore it
734 break;
735 default:
736 $this->session->getLogger()->debug("Unhandled/unknown player action type " . $action);
737 return false;
738 }
739
740 $this->player->setUsingItem(false);
741
742 return true;
743 }
744
745 public function handleSetActorMotion(SetActorMotionPacket $packet) : bool{
746 return true; //Not used: This packet is (erroneously) sent to the server when the client is riding a vehicle.
747 }
748
749 public function handleAnimate(AnimatePacket $packet) : bool{
750 return true; //Not used
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 try{
1006 $responseData = json_decode($packet->formData, true, self::MAX_FORM_RESPONSE_DEPTH, JSON_THROW_ON_ERROR);
1007 }catch(\JsonException $e){
1008 throw PacketHandlingException::wrap($e, "Failed to decode form response data");
1009 }
1010 return $this->player->onFormSubmit($packet->formId, $responseData);
1011 }else{
1012 throw new PacketHandlingException("Expected either formData or cancelReason to be set in ModalFormResponsePacket");
1013 }
1014 }
1015
1016 public function handleServerSettingsRequest(ServerSettingsRequestPacket $packet) : bool{
1017 return false; //TODO: GUI stuff
1018 }
1019
1020 public function handleLabTable(LabTablePacket $packet) : bool{
1021 return false; //TODO
1022 }
1023
1024 public function handleLecternUpdate(LecternUpdatePacket $packet) : bool{
1025 $pos = $packet->blockPosition;
1026 $chunkX = $pos->getX() >> Chunk::COORD_BIT_SIZE;
1027 $chunkZ = $pos->getZ() >> Chunk::COORD_BIT_SIZE;
1028 $world = $this->player->getWorld();
1029 if(!$world->isChunkLoaded($chunkX, $chunkZ) || $world->isChunkLocked($chunkX, $chunkZ)){
1030 return false;
1031 }
1032
1033 $lectern = $world->getBlockAt($pos->getX(), $pos->getY(), $pos->getZ());
1034 if($lectern instanceof Lectern && $this->player->canInteract($lectern->getPosition(), 15)){
1035 if(!$lectern->onPageTurn($packet->page)){
1036 $this->syncBlocksNearby($lectern->getPosition(), null);
1037 }
1038 return true;
1039 }
1040
1041 return false;
1042 }
1043
1044 public function handleNetworkStackLatency(NetworkStackLatencyPacket $packet) : bool{
1045 return true; //TODO: implement this properly - this is here to silence debug spam from MCPE dev builds
1046 }
1047
1048 public function handleLevelSoundEvent(LevelSoundEventPacket $packet) : bool{
1049 /*
1050 * We don't handle this - all sounds are handled by the server now.
1051 * However, some plugins find this useful to detect events like left-click-air, which doesn't have any other
1052 * action bound to it.
1053 * In addition, we use this handler to silence debug noise, since this packet is frequently sent by the client.
1054 */
1055 return true;
1056 }
1057
1058 public function handleEmote(EmotePacket $packet) : bool{
1059 $this->player->emote($packet->getEmoteId());
1060 return true;
1061 }
1062}
updateFaceText(Player $author, bool $frontFace, SignText $text)
Definition BaseSign.php:305
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)