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