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