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