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