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