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