mirror of
https://github.com/pmmp/PocketMine-MP.git
synced 2025-09-06 17:59:48 +00:00
Merge branch 'minor-next' into item-stack-request
This commit is contained in:
@ -33,6 +33,7 @@ use pocketmine\network\mcpe\protocol\serializer\PacketSerializerContext;
|
||||
use pocketmine\network\mcpe\protocol\types\ChunkPosition;
|
||||
use pocketmine\network\mcpe\serializer\ChunkSerializer;
|
||||
use pocketmine\scheduler\AsyncTask;
|
||||
use pocketmine\utils\BinaryStream;
|
||||
use pocketmine\world\format\Chunk;
|
||||
use pocketmine\world\format\io\FastChunkSerializer;
|
||||
|
||||
@ -72,7 +73,10 @@ class ChunkRequestTask extends AsyncTask{
|
||||
$subCount = ChunkSerializer::getSubChunkCount($chunk) + ChunkSerializer::LOWER_PADDING_SIZE;
|
||||
$encoderContext = new PacketSerializerContext(GlobalItemTypeDictionary::getInstance()->getDictionary());
|
||||
$payload = ChunkSerializer::serializeFullChunk($chunk, RuntimeBlockMapping::getInstance(), $encoderContext, $this->tiles);
|
||||
$this->setResult($this->compressor->compress(PacketBatch::fromPackets($encoderContext, LevelChunkPacket::create(new ChunkPosition($this->chunkX, $this->chunkZ), $subCount, false, null, $payload))->getBuffer()));
|
||||
|
||||
$stream = new BinaryStream();
|
||||
PacketBatch::encodePackets($stream, $encoderContext, [LevelChunkPacket::create(new ChunkPosition($this->chunkX, $this->chunkZ), $subCount, false, null, $payload)]);
|
||||
$this->setResult($this->compressor->compress($stream->getBuffer()));
|
||||
}
|
||||
|
||||
public function onError() : void{
|
||||
|
@ -43,7 +43,6 @@ use pocketmine\network\mcpe\cache\ChunkCache;
|
||||
use pocketmine\network\mcpe\compression\CompressBatchPromise;
|
||||
use pocketmine\network\mcpe\compression\Compressor;
|
||||
use pocketmine\network\mcpe\compression\DecompressionException;
|
||||
use pocketmine\network\mcpe\convert\GlobalItemTypeDictionary;
|
||||
use pocketmine\network\mcpe\convert\SkinAdapterSingleton;
|
||||
use pocketmine\network\mcpe\convert\TypeConverter;
|
||||
use pocketmine\network\mcpe\encryption\DecryptionException;
|
||||
@ -90,6 +89,8 @@ use pocketmine\network\mcpe\protocol\TakeItemActorPacket;
|
||||
use pocketmine\network\mcpe\protocol\TextPacket;
|
||||
use pocketmine\network\mcpe\protocol\ToastRequestPacket;
|
||||
use pocketmine\network\mcpe\protocol\TransferPacket;
|
||||
use pocketmine\network\mcpe\protocol\types\AbilitiesData;
|
||||
use pocketmine\network\mcpe\protocol\types\AbilitiesLayer;
|
||||
use pocketmine\network\mcpe\protocol\types\BlockPosition;
|
||||
use pocketmine\network\mcpe\protocol\types\command\CommandData;
|
||||
use pocketmine\network\mcpe\protocol\types\command\CommandEnum;
|
||||
@ -103,7 +104,6 @@ use pocketmine\network\mcpe\protocol\types\inventory\ContainerIds;
|
||||
use pocketmine\network\mcpe\protocol\types\inventory\ItemStackWrapper;
|
||||
use pocketmine\network\mcpe\protocol\types\PlayerListEntry;
|
||||
use pocketmine\network\mcpe\protocol\types\PlayerPermissions;
|
||||
use pocketmine\network\mcpe\protocol\types\UpdateAbilitiesPacketLayer;
|
||||
use pocketmine\network\mcpe\protocol\UpdateAbilitiesPacket;
|
||||
use pocketmine\network\mcpe\protocol\UpdateAdventureSettingsPacket;
|
||||
use pocketmine\network\mcpe\protocol\UpdateAttributesPacket;
|
||||
@ -119,6 +119,7 @@ use pocketmine\player\XboxLivePlayerInfo;
|
||||
use pocketmine\Server;
|
||||
use pocketmine\timings\Timings;
|
||||
use pocketmine\utils\AssumptionFailedError;
|
||||
use pocketmine\utils\BinaryStream;
|
||||
use pocketmine\utils\ObjectSet;
|
||||
use pocketmine\utils\TextFormat;
|
||||
use pocketmine\utils\Utils;
|
||||
@ -129,9 +130,12 @@ use function base64_encode;
|
||||
use function bin2hex;
|
||||
use function count;
|
||||
use function get_class;
|
||||
use function hrtime;
|
||||
use function in_array;
|
||||
use function intdiv;
|
||||
use function json_encode;
|
||||
use function ksort;
|
||||
use function min;
|
||||
use function strcasecmp;
|
||||
use function strlen;
|
||||
use function strtolower;
|
||||
@ -142,6 +146,20 @@ use const JSON_THROW_ON_ERROR;
|
||||
use const SORT_NUMERIC;
|
||||
|
||||
class NetworkSession{
|
||||
private const INCOMING_PACKET_BATCH_PER_TICK = 2; //usually max 1 per tick, but transactions may arrive separately
|
||||
private const INCOMING_PACKET_BATCH_MAX_BUDGET = 100 * self::INCOMING_PACKET_BATCH_PER_TICK; //enough to account for a 5-second lag spike
|
||||
|
||||
/**
|
||||
* At most this many more packets can be received. If this reaches zero, any additional packets received will cause
|
||||
* the player to be kicked from the server.
|
||||
* This number is increased every tick up to a maximum limit.
|
||||
*
|
||||
* @see self::INCOMING_PACKET_BATCH_PER_TICK
|
||||
* @see self::INCOMING_PACKET_BATCH_MAX_BUDGET
|
||||
*/
|
||||
private int $incomingPacketBatchBudget = self::INCOMING_PACKET_BATCH_MAX_BUDGET;
|
||||
private int $lastPacketBudgetUpdateTimeNs;
|
||||
|
||||
private \PrefixedLogger $logger;
|
||||
private ?Player $player = null;
|
||||
private ?PlayerInfo $info = null;
|
||||
@ -158,7 +176,7 @@ class NetworkSession{
|
||||
|
||||
private ?EncryptionContext $cipher = null;
|
||||
|
||||
/** @var Packet[] */
|
||||
/** @var string[] */
|
||||
private array $sendBuffer = [];
|
||||
|
||||
/**
|
||||
@ -169,8 +187,6 @@ class NetworkSession{
|
||||
private bool $forceAsyncCompression = true;
|
||||
private bool $enableCompression = false; //disabled until handshake completed
|
||||
|
||||
private PacketSerializerContext $packetSerializerContext;
|
||||
|
||||
private ?InventoryManager $invManager = null;
|
||||
|
||||
/**
|
||||
@ -183,6 +199,7 @@ class NetworkSession{
|
||||
private Server $server,
|
||||
private NetworkSessionManager $manager,
|
||||
private PacketPool $packetPool,
|
||||
private PacketSerializerContext $packetSerializerContext,
|
||||
private PacketSender $sender,
|
||||
private PacketBroadcaster $broadcaster,
|
||||
private Compressor $compressor,
|
||||
@ -193,12 +210,10 @@ class NetworkSession{
|
||||
|
||||
$this->compressedQueue = new \SplQueue();
|
||||
|
||||
//TODO: allow this to be injected
|
||||
$this->packetSerializerContext = new PacketSerializerContext(GlobalItemTypeDictionary::getInstance()->getDictionary());
|
||||
|
||||
$this->disposeHooks = new ObjectSet();
|
||||
|
||||
$this->connectTime = time();
|
||||
$this->lastPacketBudgetUpdateTimeNs = hrtime(true);
|
||||
|
||||
$this->setHandler(new SessionStartPacketHandler(
|
||||
$this->server,
|
||||
@ -339,48 +354,67 @@ class NetworkSession{
|
||||
return;
|
||||
}
|
||||
|
||||
if($this->cipher !== null){
|
||||
Timings::$playerNetworkReceiveDecrypt->startTiming();
|
||||
try{
|
||||
$payload = $this->cipher->decrypt($payload);
|
||||
}catch(DecryptionException $e){
|
||||
$this->logger->debug("Encrypted packet: " . base64_encode($payload));
|
||||
throw PacketHandlingException::wrap($e, "Packet decryption error");
|
||||
}finally{
|
||||
Timings::$playerNetworkReceiveDecrypt->stopTiming();
|
||||
}
|
||||
}
|
||||
|
||||
if($this->enableCompression){
|
||||
Timings::$playerNetworkReceiveDecompress->startTiming();
|
||||
try{
|
||||
$decompressed = $this->compressor->decompress($payload);
|
||||
}catch(DecompressionException $e){
|
||||
$this->logger->debug("Failed to decompress packet: " . base64_encode($payload));
|
||||
throw PacketHandlingException::wrap($e, "Compressed packet batch decode error");
|
||||
}finally{
|
||||
Timings::$playerNetworkReceiveDecompress->stopTiming();
|
||||
}
|
||||
}else{
|
||||
$decompressed = $payload;
|
||||
}
|
||||
|
||||
Timings::$playerNetworkReceive->startTiming();
|
||||
try{
|
||||
foreach((new PacketBatch($decompressed))->getPackets($this->packetPool, $this->packetSerializerContext, 1300) as [$packet, $buffer]){
|
||||
if($packet === null){
|
||||
$this->logger->debug("Unknown packet: " . base64_encode($buffer));
|
||||
throw new PacketHandlingException("Unknown packet received");
|
||||
}
|
||||
try{
|
||||
$this->handleDataPacket($packet, $buffer);
|
||||
}catch(PacketHandlingException $e){
|
||||
$this->logger->debug($packet->getName() . ": " . base64_encode($buffer));
|
||||
throw PacketHandlingException::wrap($e, "Error processing " . $packet->getName());
|
||||
if($this->incomingPacketBatchBudget <= 0){
|
||||
$this->updatePacketBudget();
|
||||
if($this->incomingPacketBatchBudget <= 0){
|
||||
throw new PacketHandlingException("Receiving packets too fast");
|
||||
}
|
||||
}
|
||||
}catch(PacketDecodeException $e){
|
||||
$this->logger->logException($e);
|
||||
throw PacketHandlingException::wrap($e, "Packet batch decode error");
|
||||
$this->incomingPacketBatchBudget--;
|
||||
|
||||
if($this->cipher !== null){
|
||||
Timings::$playerNetworkReceiveDecrypt->startTiming();
|
||||
try{
|
||||
$payload = $this->cipher->decrypt($payload);
|
||||
}catch(DecryptionException $e){
|
||||
$this->logger->debug("Encrypted packet: " . base64_encode($payload));
|
||||
throw PacketHandlingException::wrap($e, "Packet decryption error");
|
||||
}finally{
|
||||
Timings::$playerNetworkReceiveDecrypt->stopTiming();
|
||||
}
|
||||
}
|
||||
|
||||
if($this->enableCompression){
|
||||
Timings::$playerNetworkReceiveDecompress->startTiming();
|
||||
try{
|
||||
$decompressed = $this->compressor->decompress($payload);
|
||||
}catch(DecompressionException $e){
|
||||
$this->logger->debug("Failed to decompress packet: " . base64_encode($payload));
|
||||
throw PacketHandlingException::wrap($e, "Compressed packet batch decode error");
|
||||
}finally{
|
||||
Timings::$playerNetworkReceiveDecompress->stopTiming();
|
||||
}
|
||||
}else{
|
||||
$decompressed = $payload;
|
||||
}
|
||||
|
||||
try{
|
||||
$stream = new BinaryStream($decompressed);
|
||||
$count = 0;
|
||||
foreach(PacketBatch::decodeRaw($stream) as $buffer){
|
||||
if(++$count > 1300){
|
||||
throw new PacketHandlingException("Too many packets in batch");
|
||||
}
|
||||
$packet = $this->packetPool->getPacket($buffer);
|
||||
if($packet === null){
|
||||
$this->logger->debug("Unknown packet: " . base64_encode($buffer));
|
||||
throw new PacketHandlingException("Unknown packet received");
|
||||
}
|
||||
try{
|
||||
$this->handleDataPacket($packet, $buffer);
|
||||
}catch(PacketHandlingException $e){
|
||||
$this->logger->debug($packet->getName() . ": " . base64_encode($buffer));
|
||||
throw PacketHandlingException::wrap($e, "Error processing " . $packet->getName());
|
||||
}
|
||||
}
|
||||
}catch(PacketDecodeException $e){
|
||||
$this->logger->logException($e);
|
||||
throw PacketHandlingException::wrap($e, "Packet batch decode error");
|
||||
}
|
||||
}finally{
|
||||
Timings::$playerNetworkReceive->stopTiming();
|
||||
}
|
||||
}
|
||||
|
||||
@ -392,32 +426,39 @@ class NetworkSession{
|
||||
throw new PacketHandlingException("Unexpected non-serverbound packet");
|
||||
}
|
||||
|
||||
$timings = Timings::getDecodeDataPacketTimings($packet);
|
||||
$timings = Timings::getReceiveDataPacketTimings($packet);
|
||||
$timings->startTiming();
|
||||
try{
|
||||
$stream = PacketSerializer::decoder($buffer, 0, $this->packetSerializerContext);
|
||||
try{
|
||||
$packet->decode($stream);
|
||||
}catch(PacketDecodeException $e){
|
||||
throw PacketHandlingException::wrap($e);
|
||||
}
|
||||
if(!$stream->feof()){
|
||||
$remains = substr($stream->getBuffer(), $stream->getOffset());
|
||||
$this->logger->debug("Still " . strlen($remains) . " bytes unread in " . $packet->getName() . ": " . bin2hex($remains));
|
||||
}
|
||||
}finally{
|
||||
$timings->stopTiming();
|
||||
}
|
||||
|
||||
$timings = Timings::getHandleDataPacketTimings($packet);
|
||||
$timings->startTiming();
|
||||
try{
|
||||
//TODO: I'm not sure DataPacketReceiveEvent should be included in the handler timings, but it needs to be
|
||||
//included for now to ensure the receivePacket timings are counted the way they were before
|
||||
$decodeTimings = Timings::getDecodeDataPacketTimings($packet);
|
||||
$decodeTimings->startTiming();
|
||||
try{
|
||||
$stream = PacketSerializer::decoder($buffer, 0, $this->packetSerializerContext);
|
||||
try{
|
||||
$packet->decode($stream);
|
||||
}catch(PacketDecodeException $e){
|
||||
throw PacketHandlingException::wrap($e);
|
||||
}
|
||||
if(!$stream->feof()){
|
||||
$remains = substr($stream->getBuffer(), $stream->getOffset());
|
||||
$this->logger->debug("Still " . strlen($remains) . " bytes unread in " . $packet->getName() . ": " . bin2hex($remains));
|
||||
}
|
||||
}finally{
|
||||
$decodeTimings->stopTiming();
|
||||
}
|
||||
|
||||
$ev = new DataPacketReceiveEvent($this, $packet);
|
||||
$ev->call();
|
||||
if(!$ev->isCancelled() && ($this->handler === null || !$packet->handle($this->handler))){
|
||||
$this->logger->debug("Unhandled " . $packet->getName() . ": " . base64_encode($stream->getBuffer()));
|
||||
if(!$ev->isCancelled()){
|
||||
$handlerTimings = Timings::getHandleDataPacketTimings($packet);
|
||||
$handlerTimings->startTiming();
|
||||
try{
|
||||
if($this->handler === null || !$packet->handle($this->handler)){
|
||||
$this->logger->debug("Unhandled " . $packet->getName() . ": " . base64_encode($stream->getBuffer()));
|
||||
}
|
||||
}finally{
|
||||
$handlerTimings->stopTiming();
|
||||
}
|
||||
}
|
||||
}finally{
|
||||
$timings->stopTiming();
|
||||
@ -425,6 +466,9 @@ class NetworkSession{
|
||||
}
|
||||
|
||||
public function sendDataPacket(ClientboundPacket $packet, bool $immediate = false) : bool{
|
||||
if(!$this->connected){
|
||||
return false;
|
||||
}
|
||||
//Basic safety restriction. TODO: improve this
|
||||
if(!$this->loggedIn && !$packet->canBeSentBeforeLogin()){
|
||||
throw new \InvalidArgumentException("Attempted to send " . get_class($packet) . " to " . $this->getDisplayName() . " too early");
|
||||
@ -439,7 +483,7 @@ class NetworkSession{
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->addToSendBuffer($packet);
|
||||
$this->addToSendBuffer(self::encodePacketTimed(PacketSerializer::encoder($this->packetSerializerContext), $packet));
|
||||
if($immediate){
|
||||
$this->flushSendBuffer(true);
|
||||
}
|
||||
@ -453,34 +497,49 @@ class NetworkSession{
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public function addToSendBuffer(ClientboundPacket $packet) : void{
|
||||
$timings = Timings::getSendDataPacketTimings($packet);
|
||||
public static function encodePacketTimed(PacketSerializer $serializer, ClientboundPacket $packet) : string{
|
||||
$timings = Timings::getEncodeDataPacketTimings($packet);
|
||||
$timings->startTiming();
|
||||
try{
|
||||
$this->sendBuffer[] = $packet;
|
||||
$packet->encode($serializer);
|
||||
return $serializer->getBuffer();
|
||||
}finally{
|
||||
$timings->stopTiming();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public function addToSendBuffer(string $buffer) : void{
|
||||
$this->sendBuffer[] = $buffer;
|
||||
}
|
||||
|
||||
private function flushSendBuffer(bool $immediate = false) : void{
|
||||
if(count($this->sendBuffer) > 0){
|
||||
$syncMode = null; //automatic
|
||||
if($immediate){
|
||||
$syncMode = true;
|
||||
}elseif($this->forceAsyncCompression){
|
||||
$syncMode = false;
|
||||
}
|
||||
Timings::$playerNetworkSend->startTiming();
|
||||
try{
|
||||
$syncMode = null; //automatic
|
||||
if($immediate){
|
||||
$syncMode = true;
|
||||
}elseif($this->forceAsyncCompression){
|
||||
$syncMode = false;
|
||||
}
|
||||
|
||||
$batch = PacketBatch::fromPackets($this->packetSerializerContext, ...$this->sendBuffer);
|
||||
if($this->enableCompression){
|
||||
$promise = $this->server->prepareBatch($batch, $this->compressor, $syncMode);
|
||||
}else{
|
||||
$promise = new CompressBatchPromise();
|
||||
$promise->resolve($batch->getBuffer());
|
||||
$stream = new BinaryStream();
|
||||
PacketBatch::encodeRaw($stream, $this->sendBuffer);
|
||||
|
||||
if($this->enableCompression){
|
||||
$promise = $this->server->prepareBatch(new PacketBatch($stream->getBuffer()), $this->compressor, $syncMode, Timings::$playerNetworkSendCompressSessionBuffer);
|
||||
}else{
|
||||
$promise = new CompressBatchPromise();
|
||||
$promise->resolve($stream->getBuffer());
|
||||
}
|
||||
$this->sendBuffer = [];
|
||||
$this->queueCompressedNoBufferFlush($promise, $immediate);
|
||||
}finally{
|
||||
Timings::$playerNetworkSend->stopTiming();
|
||||
}
|
||||
$this->sendBuffer = [];
|
||||
$this->queueCompressedNoBufferFlush($promise, $immediate);
|
||||
}
|
||||
}
|
||||
|
||||
@ -493,35 +552,45 @@ class NetworkSession{
|
||||
}
|
||||
|
||||
public function queueCompressed(CompressBatchPromise $payload, bool $immediate = false) : void{
|
||||
$this->flushSendBuffer($immediate); //Maintain ordering if possible
|
||||
$this->queueCompressedNoBufferFlush($payload, $immediate);
|
||||
Timings::$playerNetworkSend->startTiming();
|
||||
try{
|
||||
$this->flushSendBuffer($immediate); //Maintain ordering if possible
|
||||
$this->queueCompressedNoBufferFlush($payload, $immediate);
|
||||
}finally{
|
||||
Timings::$playerNetworkSend->stopTiming();
|
||||
}
|
||||
}
|
||||
|
||||
private function queueCompressedNoBufferFlush(CompressBatchPromise $payload, bool $immediate = false) : void{
|
||||
if($immediate){
|
||||
//Skips all queues
|
||||
$this->sendEncoded($payload->getResult(), true);
|
||||
}else{
|
||||
$this->compressedQueue->enqueue($payload);
|
||||
$payload->onResolve(function(CompressBatchPromise $payload) : void{
|
||||
if($this->connected && $this->compressedQueue->bottom() === $payload){
|
||||
$this->compressedQueue->dequeue(); //result unused
|
||||
$this->sendEncoded($payload->getResult());
|
||||
Timings::$playerNetworkSend->startTiming();
|
||||
try{
|
||||
if($immediate){
|
||||
//Skips all queues
|
||||
$this->sendEncoded($payload->getResult(), true);
|
||||
}else{
|
||||
$this->compressedQueue->enqueue($payload);
|
||||
$payload->onResolve(function(CompressBatchPromise $payload) : void{
|
||||
if($this->connected && $this->compressedQueue->bottom() === $payload){
|
||||
$this->compressedQueue->dequeue(); //result unused
|
||||
$this->sendEncoded($payload->getResult());
|
||||
|
||||
while(!$this->compressedQueue->isEmpty()){
|
||||
/** @var CompressBatchPromise $current */
|
||||
$current = $this->compressedQueue->bottom();
|
||||
if($current->hasResult()){
|
||||
$this->compressedQueue->dequeue();
|
||||
while(!$this->compressedQueue->isEmpty()){
|
||||
/** @var CompressBatchPromise $current */
|
||||
$current = $this->compressedQueue->bottom();
|
||||
if($current->hasResult()){
|
||||
$this->compressedQueue->dequeue();
|
||||
|
||||
$this->sendEncoded($current->getResult());
|
||||
}else{
|
||||
//can't send any more queued until this one is ready
|
||||
break;
|
||||
$this->sendEncoded($current->getResult());
|
||||
}else{
|
||||
//can't send any more queued until this one is ready
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}finally{
|
||||
Timings::$playerNetworkSend->stopTiming();
|
||||
}
|
||||
}
|
||||
|
||||
@ -542,28 +611,37 @@ class NetworkSession{
|
||||
$this->disconnectGuard = true;
|
||||
$func();
|
||||
$this->disconnectGuard = false;
|
||||
$this->flushSendBuffer(true);
|
||||
$this->sender->close("");
|
||||
foreach($this->disposeHooks as $callback){
|
||||
$callback();
|
||||
}
|
||||
$this->disposeHooks->clear();
|
||||
$this->setHandler(null);
|
||||
$this->connected = false;
|
||||
$this->manager->remove($this);
|
||||
$this->logger->info("Session closed due to $reason");
|
||||
|
||||
$this->invManager = null; //break cycles - TODO: this really ought to be deferred until it's safe
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs actions after the session has been disconnected. By this point, nothing should be interacting with the
|
||||
* session, so it's safe to destroy any cycles and perform destructive cleanup.
|
||||
*/
|
||||
private function dispose() : void{
|
||||
$this->invManager = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects the session, destroying the associated player (if it exists).
|
||||
*/
|
||||
public function disconnect(string $reason, bool $notify = true) : void{
|
||||
$this->tryDisconnect(function() use ($reason, $notify) : void{
|
||||
if($notify){
|
||||
$this->sendDataPacket(DisconnectPacket::create($reason));
|
||||
}
|
||||
if($this->player !== null){
|
||||
$this->player->onPostDisconnect($reason, null);
|
||||
}
|
||||
$this->doServerDisconnect($reason, $notify);
|
||||
}, $reason);
|
||||
}
|
||||
|
||||
@ -576,7 +654,6 @@ class NetworkSession{
|
||||
if($this->player !== null){
|
||||
$this->player->onPostDisconnect($reason, null);
|
||||
}
|
||||
$this->doServerDisconnect($reason, false);
|
||||
}, $reason);
|
||||
}
|
||||
|
||||
@ -585,21 +662,10 @@ class NetworkSession{
|
||||
*/
|
||||
public function onPlayerDestroyed(string $reason) : void{
|
||||
$this->tryDisconnect(function() use ($reason) : void{
|
||||
$this->doServerDisconnect($reason, true);
|
||||
$this->sendDataPacket(DisconnectPacket::create($reason));
|
||||
}, $reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal helper function used to handle server disconnections.
|
||||
*/
|
||||
private function doServerDisconnect(string $reason, bool $notify = true) : void{
|
||||
if($notify){
|
||||
$this->sendDataPacket(DisconnectPacket::create($reason !== "" ? $reason : null), true);
|
||||
}
|
||||
|
||||
$this->sender->close($notify ? $reason : "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by the network interface to close the session when the client disconnects without server input, for
|
||||
* example in a timeout condition or voluntary client disconnect.
|
||||
@ -683,7 +749,7 @@ class NetworkSession{
|
||||
//TODO: we shouldn't be loading player data here at all, but right now we don't have any choice :(
|
||||
$this->cachedOfflinePlayerData = $this->server->getOfflinePlayerData($this->info->getUsername());
|
||||
if($checkXUID){
|
||||
$recordedXUID = $this->cachedOfflinePlayerData !== null ? $this->cachedOfflinePlayerData->getTag("LastKnownXUID") : null;
|
||||
$recordedXUID = $this->cachedOfflinePlayerData !== null ? $this->cachedOfflinePlayerData->getTag(Player::TAG_LAST_KNOWN_XUID) : null;
|
||||
if(!($recordedXUID instanceof StringTag)){
|
||||
$this->logger->debug("No previous XUID recorded, no choice but to trust this player");
|
||||
}elseif(!$kickForXUIDMismatch($recordedXUID->getValue())){
|
||||
@ -744,9 +810,9 @@ class NetworkSession{
|
||||
$this->setHandler(new InGamePacketHandler($this->player, $this, $this->invManager));
|
||||
}
|
||||
|
||||
public function onServerDeath() : void{
|
||||
public function onServerDeath(Translatable|string $deathMessage) : void{
|
||||
if($this->handler instanceof InGamePacketHandler){ //TODO: this is a bad fix for pre-spawn death, this shouldn't be reachable at all at this stage :(
|
||||
$this->setHandler(new DeathPacketHandler($this->player, $this, $this->invManager ?? throw new AssumptionFailedError()));
|
||||
$this->setHandler(new DeathPacketHandler($this->player, $this, $this->invManager ?? throw new AssumptionFailedError(), $deathMessage));
|
||||
}
|
||||
}
|
||||
|
||||
@ -817,33 +883,33 @@ class NetworkSession{
|
||||
|
||||
//ALL of these need to be set for the base layer, otherwise the client will cry
|
||||
$boolAbilities = [
|
||||
UpdateAbilitiesPacketLayer::ABILITY_ALLOW_FLIGHT => $for->getAllowFlight(),
|
||||
UpdateAbilitiesPacketLayer::ABILITY_FLYING => $for->isFlying(),
|
||||
UpdateAbilitiesPacketLayer::ABILITY_NO_CLIP => !$for->hasBlockCollision(),
|
||||
UpdateAbilitiesPacketLayer::ABILITY_OPERATOR => $isOp,
|
||||
UpdateAbilitiesPacketLayer::ABILITY_TELEPORT => $for->hasPermission(DefaultPermissionNames::COMMAND_TELEPORT),
|
||||
UpdateAbilitiesPacketLayer::ABILITY_INVULNERABLE => $for->isCreative(),
|
||||
UpdateAbilitiesPacketLayer::ABILITY_MUTED => false,
|
||||
UpdateAbilitiesPacketLayer::ABILITY_WORLD_BUILDER => false,
|
||||
UpdateAbilitiesPacketLayer::ABILITY_INFINITE_RESOURCES => !$for->hasFiniteResources(),
|
||||
UpdateAbilitiesPacketLayer::ABILITY_LIGHTNING => false,
|
||||
UpdateAbilitiesPacketLayer::ABILITY_BUILD => !$for->isSpectator(),
|
||||
UpdateAbilitiesPacketLayer::ABILITY_MINE => !$for->isSpectator(),
|
||||
UpdateAbilitiesPacketLayer::ABILITY_DOORS_AND_SWITCHES => !$for->isSpectator(),
|
||||
UpdateAbilitiesPacketLayer::ABILITY_OPEN_CONTAINERS => !$for->isSpectator(),
|
||||
UpdateAbilitiesPacketLayer::ABILITY_ATTACK_PLAYERS => !$for->isSpectator(),
|
||||
UpdateAbilitiesPacketLayer::ABILITY_ATTACK_MOBS => !$for->isSpectator(),
|
||||
AbilitiesLayer::ABILITY_ALLOW_FLIGHT => $for->getAllowFlight(),
|
||||
AbilitiesLayer::ABILITY_FLYING => $for->isFlying(),
|
||||
AbilitiesLayer::ABILITY_NO_CLIP => !$for->hasBlockCollision(),
|
||||
AbilitiesLayer::ABILITY_OPERATOR => $isOp,
|
||||
AbilitiesLayer::ABILITY_TELEPORT => $for->hasPermission(DefaultPermissionNames::COMMAND_TELEPORT_SELF),
|
||||
AbilitiesLayer::ABILITY_INVULNERABLE => $for->isCreative(),
|
||||
AbilitiesLayer::ABILITY_MUTED => false,
|
||||
AbilitiesLayer::ABILITY_WORLD_BUILDER => false,
|
||||
AbilitiesLayer::ABILITY_INFINITE_RESOURCES => !$for->hasFiniteResources(),
|
||||
AbilitiesLayer::ABILITY_LIGHTNING => false,
|
||||
AbilitiesLayer::ABILITY_BUILD => !$for->isSpectator(),
|
||||
AbilitiesLayer::ABILITY_MINE => !$for->isSpectator(),
|
||||
AbilitiesLayer::ABILITY_DOORS_AND_SWITCHES => !$for->isSpectator(),
|
||||
AbilitiesLayer::ABILITY_OPEN_CONTAINERS => !$for->isSpectator(),
|
||||
AbilitiesLayer::ABILITY_ATTACK_PLAYERS => !$for->isSpectator(),
|
||||
AbilitiesLayer::ABILITY_ATTACK_MOBS => !$for->isSpectator(),
|
||||
];
|
||||
|
||||
$this->sendDataPacket(UpdateAbilitiesPacket::create(
|
||||
$this->sendDataPacket(UpdateAbilitiesPacket::create(new AbilitiesData(
|
||||
$isOp ? CommandPermissions::OPERATOR : CommandPermissions::NORMAL,
|
||||
$isOp ? PlayerPermissions::OPERATOR : PlayerPermissions::MEMBER,
|
||||
$for->getId(),
|
||||
[
|
||||
//TODO: dynamic flying speed! FINALLY!!!!!!!!!!!!!!!!!
|
||||
new UpdateAbilitiesPacketLayer(UpdateAbilitiesPacketLayer::LAYER_BASE, $boolAbilities, 0.05, 0.1),
|
||||
new AbilitiesLayer(AbilitiesLayer::LAYER_BASE, $boolAbilities, 0.05, 0.1),
|
||||
]
|
||||
));
|
||||
)));
|
||||
}
|
||||
|
||||
public function syncAdventureSettings() : void{
|
||||
@ -931,15 +997,19 @@ class NetworkSession{
|
||||
$this->sendDataPacket(AvailableCommandsPacket::create($commandData, [], [], []));
|
||||
}
|
||||
|
||||
public function onRawChatMessage(string $message) : void{
|
||||
$this->sendDataPacket(TextPacket::raw($message));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string[] $parameters
|
||||
*/
|
||||
public function onTranslatedChatMessage(string $key, array $parameters) : void{
|
||||
$this->sendDataPacket(TextPacket::translation($key, $parameters));
|
||||
public function onChatMessage(Translatable|string $message) : void{
|
||||
if($message instanceof Translatable){
|
||||
$language = $this->player->getLanguage();
|
||||
if(!$this->server->isLanguageForced()){
|
||||
//we can't send nested translations to the client, so make sure they are always pre-translated by the server
|
||||
$parameters = array_map(fn(string|Translatable $p) => $p instanceof Translatable ? $language->translate($p) : $p, $message->getParameters());
|
||||
$this->sendDataPacket(TextPacket::translation($language->translateString($message->getText(), $parameters, "pocketmine."), $parameters));
|
||||
}else{
|
||||
$this->sendDataPacket(TextPacket::raw($language->translate($message)));
|
||||
}
|
||||
}else{
|
||||
$this->sendDataPacket(TextPacket::raw($message));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1107,7 +1177,29 @@ class NetworkSession{
|
||||
$this->sendDataPacket(ToastRequestPacket::create($title, $body));
|
||||
}
|
||||
|
||||
private function updatePacketBudget() : void{
|
||||
$nowNs = hrtime(true);
|
||||
$timeSinceLastUpdateNs = $nowNs - $this->lastPacketBudgetUpdateTimeNs;
|
||||
if($timeSinceLastUpdateNs > 50_000_000){
|
||||
$ticksSinceLastUpdate = intdiv($timeSinceLastUpdateNs, 50_000_000);
|
||||
/*
|
||||
* If the server takes an abnormally long time to process a tick, add the budget for time difference to
|
||||
* compensate. This extra budget may be very large, but it will disappear the next time a normal update
|
||||
* occurs. This ensures that backlogs during a large lag spike don't cause everyone to get kicked.
|
||||
* As long as all the backlogged packets are processed before the next tick, everything should be OK for
|
||||
* clients behaving normally.
|
||||
*/
|
||||
$this->incomingPacketBatchBudget = min($this->incomingPacketBatchBudget, self::INCOMING_PACKET_BATCH_MAX_BUDGET) + (self::INCOMING_PACKET_BATCH_PER_TICK * 2 * $ticksSinceLastUpdate);
|
||||
$this->lastPacketBudgetUpdateTimeNs = $nowNs;
|
||||
}
|
||||
}
|
||||
|
||||
public function tick() : void{
|
||||
if(!$this->isConnected()){
|
||||
$this->dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
if($this->info === null){
|
||||
if(time() >= $this->connectTime + 10){
|
||||
$this->disconnect("Login timeout");
|
||||
|
@ -24,44 +24,64 @@ declare(strict_types=1);
|
||||
namespace pocketmine\network\mcpe;
|
||||
|
||||
use pocketmine\network\mcpe\protocol\serializer\PacketBatch;
|
||||
use pocketmine\network\mcpe\protocol\serializer\PacketSerializer;
|
||||
use pocketmine\network\mcpe\protocol\serializer\PacketSerializerContext;
|
||||
use pocketmine\Server;
|
||||
use pocketmine\timings\Timings;
|
||||
use pocketmine\utils\BinaryStream;
|
||||
use function count;
|
||||
use function spl_object_id;
|
||||
use function strlen;
|
||||
|
||||
final class StandardPacketBroadcaster implements PacketBroadcaster{
|
||||
public function __construct(private Server $server){}
|
||||
public function __construct(
|
||||
private Server $server,
|
||||
private PacketSerializerContext $protocolContext
|
||||
){}
|
||||
|
||||
public function broadcastPackets(array $recipients, array $packets) : void{
|
||||
$buffers = [];
|
||||
$compressors = [];
|
||||
$targetMap = [];
|
||||
|
||||
/** @var NetworkSession[][] $targetsByCompressor */
|
||||
$targetsByCompressor = [];
|
||||
foreach($recipients as $recipient){
|
||||
$serializerContext = $recipient->getPacketSerializerContext();
|
||||
$bufferId = spl_object_id($serializerContext);
|
||||
if(!isset($buffers[$bufferId])){
|
||||
$buffers[$bufferId] = PacketBatch::fromPackets($serializerContext, ...$packets);
|
||||
if($recipient->getPacketSerializerContext() !== $this->protocolContext){
|
||||
throw new \InvalidArgumentException("Only recipients with the same protocol context as the broadcaster can be broadcast to by this broadcaster");
|
||||
}
|
||||
|
||||
//TODO: different compressors might be compatible, it might not be necessary to split them up by object
|
||||
$compressor = $recipient->getCompressor();
|
||||
$compressors[spl_object_id($compressor)] = $compressor;
|
||||
|
||||
$targetMap[$bufferId][spl_object_id($compressor)][] = $recipient;
|
||||
$targetsByCompressor[spl_object_id($compressor)][] = $recipient;
|
||||
}
|
||||
|
||||
foreach($targetMap as $bufferId => $compressorMap){
|
||||
$buffer = $buffers[$bufferId];
|
||||
foreach($compressorMap as $compressorId => $compressorTargets){
|
||||
$compressor = $compressors[$compressorId];
|
||||
if(!$compressor->willCompress($buffer->getBuffer())){
|
||||
foreach($compressorTargets as $target){
|
||||
foreach($packets as $pk){
|
||||
$target->addToSendBuffer($pk);
|
||||
}
|
||||
}
|
||||
}else{
|
||||
$promise = $this->server->prepareBatch($buffer, $compressor);
|
||||
foreach($compressorTargets as $target){
|
||||
$target->queueCompressed($promise);
|
||||
$totalLength = 0;
|
||||
$packetBuffers = [];
|
||||
foreach($packets as $packet){
|
||||
$buffer = NetworkSession::encodePacketTimed(PacketSerializer::encoder($this->protocolContext), $packet);
|
||||
$totalLength += strlen($buffer);
|
||||
$packetBuffers[] = $buffer;
|
||||
}
|
||||
|
||||
foreach($targetsByCompressor as $compressorId => $compressorTargets){
|
||||
$compressor = $compressors[$compressorId];
|
||||
|
||||
$threshold = $compressor->getCompressionThreshold();
|
||||
if(count($compressorTargets) > 1 && $threshold !== null && $totalLength >= $threshold){
|
||||
//do not prepare shared batch unless we're sure it will be compressed
|
||||
$stream = new BinaryStream();
|
||||
PacketBatch::encodeRaw($stream, $packetBuffers);
|
||||
$batchBuffer = $stream->getBuffer();
|
||||
|
||||
$promise = $this->server->prepareBatch(new PacketBatch($batchBuffer), $compressor, timings: Timings::$playerNetworkSendCompressBroadcast);
|
||||
foreach($compressorTargets as $target){
|
||||
$target->queueCompressed($promise);
|
||||
}
|
||||
}else{
|
||||
foreach($compressorTargets as $target){
|
||||
foreach($packetBuffers as $packetBuffer){
|
||||
$target->addToSendBuffer($packetBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
12
src/network/mcpe/cache/StaticPacketCache.php
vendored
12
src/network/mcpe/cache/StaticPacketCache.php
vendored
@ -23,13 +23,13 @@ declare(strict_types=1);
|
||||
|
||||
namespace pocketmine\network\mcpe\cache;
|
||||
|
||||
use pocketmine\data\bedrock\BedrockDataFiles;
|
||||
use pocketmine\network\mcpe\protocol\AvailableActorIdentifiersPacket;
|
||||
use pocketmine\network\mcpe\protocol\BiomeDefinitionListPacket;
|
||||
use pocketmine\network\mcpe\protocol\serializer\NetworkNbtSerializer;
|
||||
use pocketmine\network\mcpe\protocol\types\CacheableNbt;
|
||||
use pocketmine\utils\Filesystem;
|
||||
use pocketmine\utils\SingletonTrait;
|
||||
use Symfony\Component\Filesystem\Path;
|
||||
use function file_get_contents;
|
||||
|
||||
class StaticPacketCache{
|
||||
use SingletonTrait;
|
||||
@ -38,15 +38,13 @@ class StaticPacketCache{
|
||||
* @phpstan-return CacheableNbt<\pocketmine\nbt\tag\CompoundTag>
|
||||
*/
|
||||
private static function loadCompoundFromFile(string $filePath) : CacheableNbt{
|
||||
$rawNbt = @file_get_contents($filePath);
|
||||
if($rawNbt === false) throw new \RuntimeException("Failed to read file");
|
||||
return new CacheableNbt((new NetworkNbtSerializer())->read($rawNbt)->mustGetCompoundTag());
|
||||
return new CacheableNbt((new NetworkNbtSerializer())->read(Filesystem::fileGetContents($filePath))->mustGetCompoundTag());
|
||||
}
|
||||
|
||||
private static function make() : self{
|
||||
return new self(
|
||||
BiomeDefinitionListPacket::create(self::loadCompoundFromFile(Path::join(\pocketmine\BEDROCK_DATA_PATH, 'biome_definitions.nbt'))),
|
||||
AvailableActorIdentifiersPacket::create(self::loadCompoundFromFile(Path::join(\pocketmine\BEDROCK_DATA_PATH, 'entity_identifiers.nbt')))
|
||||
BiomeDefinitionListPacket::create(self::loadCompoundFromFile(BedrockDataFiles::BIOME_DEFINITIONS_NBT)),
|
||||
AvailableActorIdentifiersPacket::create(self::loadCompoundFromFile(BedrockDataFiles::ENTITY_IDENTIFIERS_NBT))
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -24,13 +24,20 @@ declare(strict_types=1);
|
||||
namespace pocketmine\network\mcpe\compression;
|
||||
|
||||
interface Compressor{
|
||||
|
||||
public function willCompress(string $data) : bool;
|
||||
|
||||
/**
|
||||
* @throws DecompressionException
|
||||
*/
|
||||
public function decompress(string $payload) : string;
|
||||
|
||||
public function compress(string $payload) : string;
|
||||
|
||||
/**
|
||||
* Returns the minimum size of packet batch that the compressor will attempt to compress.
|
||||
*
|
||||
* The compressor's output **MUST** still be valid input for the decompressor even if the compressor input is
|
||||
* below this threshold.
|
||||
* However, it may choose to use a cheaper compression option (e.g. zlib level 0, which simply wraps the data and
|
||||
* doesn't attempt to compress it) to avoid wasting CPU time.
|
||||
*/
|
||||
public function getCompressionThreshold() : ?int;
|
||||
}
|
||||
|
@ -48,12 +48,12 @@ final class ZlibCompressor implements Compressor{
|
||||
|
||||
public function __construct(
|
||||
private int $level,
|
||||
private int $minCompressionSize,
|
||||
private ?int $minCompressionSize,
|
||||
private int $maxDecompressionSize
|
||||
){}
|
||||
|
||||
public function willCompress(string $data) : bool{
|
||||
return $this->minCompressionSize > -1 && strlen($data) >= $this->minCompressionSize;
|
||||
public function getCompressionThreshold() : ?int{
|
||||
return $this->minCompressionSize;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -72,11 +72,12 @@ final class ZlibCompressor implements Compressor{
|
||||
}
|
||||
|
||||
public function compress(string $payload) : string{
|
||||
$compressible = $this->minCompressionSize !== null && strlen($payload) >= $this->minCompressionSize;
|
||||
if(function_exists('libdeflate_deflate_compress')){
|
||||
return $this->willCompress($payload) ?
|
||||
return $compressible ?
|
||||
libdeflate_deflate_compress($payload, $this->level) :
|
||||
self::zlib_encode($payload, 0);
|
||||
}
|
||||
return self::zlib_encode($payload, $this->willCompress($payload) ? $this->level : 0);
|
||||
return self::zlib_encode($payload, $compressible ? $this->level : 0);
|
||||
}
|
||||
}
|
||||
|
@ -23,13 +23,12 @@ declare(strict_types=1);
|
||||
|
||||
namespace pocketmine\network\mcpe\convert;
|
||||
|
||||
use pocketmine\data\bedrock\BedrockDataFiles;
|
||||
use pocketmine\network\mcpe\protocol\serializer\ItemTypeDictionary;
|
||||
use pocketmine\network\mcpe\protocol\types\ItemTypeEntry;
|
||||
use pocketmine\utils\AssumptionFailedError;
|
||||
use pocketmine\utils\Filesystem;
|
||||
use pocketmine\utils\SingletonTrait;
|
||||
use pocketmine\utils\Utils;
|
||||
use Symfony\Component\Filesystem\Path;
|
||||
use function file_get_contents;
|
||||
use function is_array;
|
||||
use function is_bool;
|
||||
use function is_int;
|
||||
@ -40,7 +39,7 @@ final class GlobalItemTypeDictionary{
|
||||
use SingletonTrait;
|
||||
|
||||
private static function make() : self{
|
||||
$data = Utils::assumeNotFalse(file_get_contents(Path::join(\pocketmine\BEDROCK_DATA_PATH, 'required_item_list.json')), "Missing required resource file");
|
||||
$data = Filesystem::fileGetContents(BedrockDataFiles::REQUIRED_ITEM_LIST_JSON);
|
||||
$table = json_decode($data, true);
|
||||
if(!is_array($table)){
|
||||
throw new AssumptionFailedError("Invalid item list format");
|
||||
|
@ -23,14 +23,14 @@ declare(strict_types=1);
|
||||
|
||||
namespace pocketmine\network\mcpe\convert;
|
||||
|
||||
use pocketmine\data\bedrock\BedrockDataFiles;
|
||||
use pocketmine\data\bedrock\LegacyItemIdToStringIdMap;
|
||||
use pocketmine\network\mcpe\protocol\serializer\ItemTypeDictionary;
|
||||
use pocketmine\utils\AssumptionFailedError;
|
||||
use pocketmine\utils\Filesystem;
|
||||
use pocketmine\utils\SingletonTrait;
|
||||
use pocketmine\utils\Utils;
|
||||
use Symfony\Component\Filesystem\Path;
|
||||
use function array_key_exists;
|
||||
use function file_get_contents;
|
||||
use function is_array;
|
||||
use function is_numeric;
|
||||
use function is_string;
|
||||
@ -67,7 +67,7 @@ final class ItemTranslator{
|
||||
private array $complexNetToCoreMapping = [];
|
||||
|
||||
private static function make() : self{
|
||||
$data = Utils::assumeNotFalse(file_get_contents(Path::join(\pocketmine\BEDROCK_DATA_PATH, 'r16_to_current_item_map.json')), "Missing required resource file");
|
||||
$data = Filesystem::fileGetContents(BedrockDataFiles::R16_TO_CURRENT_ITEM_MAP_JSON);
|
||||
$json = json_decode($data, true);
|
||||
if(!is_array($json) || !isset($json["simple"], $json["complex"]) || !is_array($json["simple"]) || !is_array($json["complex"])){
|
||||
throw new AssumptionFailedError("Invalid item table format");
|
||||
|
@ -25,15 +25,13 @@ namespace pocketmine\network\mcpe\convert;
|
||||
|
||||
use pocketmine\block\Block;
|
||||
use pocketmine\block\BlockLegacyIds;
|
||||
use pocketmine\data\bedrock\BedrockDataFiles;
|
||||
use pocketmine\data\bedrock\LegacyBlockIdToStringIdMap;
|
||||
use pocketmine\nbt\tag\CompoundTag;
|
||||
use pocketmine\network\mcpe\protocol\serializer\NetworkNbtSerializer;
|
||||
use pocketmine\network\mcpe\protocol\serializer\PacketSerializer;
|
||||
use pocketmine\network\mcpe\protocol\serializer\PacketSerializerContext;
|
||||
use pocketmine\utils\BinaryStream;
|
||||
use pocketmine\utils\Filesystem;
|
||||
use pocketmine\utils\SingletonTrait;
|
||||
use pocketmine\utils\Utils;
|
||||
use Symfony\Component\Filesystem\Path;
|
||||
use function file_get_contents;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
@ -50,20 +48,20 @@ final class RuntimeBlockMapping{
|
||||
|
||||
private static function make() : self{
|
||||
return new self(
|
||||
Path::join(\pocketmine\BEDROCK_DATA_PATH, "canonical_block_states.nbt"),
|
||||
Path::join(\pocketmine\BEDROCK_DATA_PATH, "r12_to_current_block_map.bin")
|
||||
BedrockDataFiles::CANONICAL_BLOCK_STATES_NBT,
|
||||
BedrockDataFiles::R12_TO_CURRENT_BLOCK_MAP_BIN
|
||||
);
|
||||
}
|
||||
|
||||
public function __construct(string $canonicalBlockStatesFile, string $r12ToCurrentBlockMapFile){
|
||||
$stream = PacketSerializer::decoder(
|
||||
Utils::assumeNotFalse(file_get_contents($canonicalBlockStatesFile), "Missing required resource file"),
|
||||
0,
|
||||
new PacketSerializerContext(GlobalItemTypeDictionary::getInstance()->getDictionary())
|
||||
);
|
||||
$stream = new BinaryStream(Filesystem::fileGetContents($canonicalBlockStatesFile));
|
||||
$list = [];
|
||||
$nbtReader = new NetworkNbtSerializer();
|
||||
while(!$stream->feof()){
|
||||
$list[] = $stream->getNbtCompoundRoot();
|
||||
$offset = $stream->getOffset();
|
||||
$blockState = $nbtReader->read($stream->getBuffer(), $offset)->mustGetCompoundTag();
|
||||
$stream->setOffset($offset);
|
||||
$list[] = $blockState;
|
||||
}
|
||||
$this->bedrockKnownStates = $list;
|
||||
|
||||
@ -74,14 +72,10 @@ final class RuntimeBlockMapping{
|
||||
$legacyIdMap = LegacyBlockIdToStringIdMap::getInstance();
|
||||
/** @var R12ToCurrentBlockMapEntry[] $legacyStateMap */
|
||||
$legacyStateMap = [];
|
||||
$legacyStateMapReader = PacketSerializer::decoder(
|
||||
Utils::assumeNotFalse(file_get_contents($r12ToCurrentBlockMapFile), "Missing required resource file"),
|
||||
0,
|
||||
new PacketSerializerContext(GlobalItemTypeDictionary::getInstance()->getDictionary())
|
||||
);
|
||||
$legacyStateMapReader = new BinaryStream(Filesystem::fileGetContents($r12ToCurrentBlockMapFile));
|
||||
$nbtReader = new NetworkNbtSerializer();
|
||||
while(!$legacyStateMapReader->feof()){
|
||||
$id = $legacyStateMapReader->getString();
|
||||
$id = $legacyStateMapReader->get($legacyStateMapReader->getUnsignedVarInt());
|
||||
$meta = $legacyStateMapReader->getLShort();
|
||||
|
||||
$offset = $legacyStateMapReader->getOffset();
|
||||
|
@ -23,19 +23,23 @@ declare(strict_types=1);
|
||||
|
||||
namespace pocketmine\network\mcpe\handler;
|
||||
|
||||
use pocketmine\lang\Translatable;
|
||||
use pocketmine\network\mcpe\InventoryManager;
|
||||
use pocketmine\network\mcpe\NetworkSession;
|
||||
use pocketmine\network\mcpe\protocol\ContainerClosePacket;
|
||||
use pocketmine\network\mcpe\protocol\DeathInfoPacket;
|
||||
use pocketmine\network\mcpe\protocol\PlayerActionPacket;
|
||||
use pocketmine\network\mcpe\protocol\RespawnPacket;
|
||||
use pocketmine\network\mcpe\protocol\types\PlayerAction;
|
||||
use pocketmine\player\Player;
|
||||
use function array_map;
|
||||
|
||||
class DeathPacketHandler extends PacketHandler{
|
||||
public function __construct(
|
||||
private Player $player,
|
||||
private NetworkSession $session,
|
||||
private InventoryManager $inventoryManager
|
||||
private InventoryManager $inventoryManager,
|
||||
private Translatable|string $deathMessage
|
||||
){}
|
||||
|
||||
public function setUp() : void{
|
||||
@ -44,6 +48,22 @@ class DeathPacketHandler extends PacketHandler{
|
||||
RespawnPacket::SEARCHING_FOR_SPAWN,
|
||||
$this->player->getId()
|
||||
));
|
||||
|
||||
/** @var string[] $parameters */
|
||||
$parameters = [];
|
||||
if($this->deathMessage instanceof Translatable){
|
||||
$language = $this->player->getLanguage();
|
||||
if(!$this->player->getServer()->isLanguageForced()){
|
||||
//we can't send nested translations to the client, so make sure they are always pre-translated by the server
|
||||
$parameters = array_map(fn(string|Translatable $p) => $p instanceof Translatable ? $language->translate($p) : $p, $this->deathMessage->getParameters());
|
||||
$message = $language->translateString($this->deathMessage->getText(), $parameters, "pocketmine.");
|
||||
}else{
|
||||
$message = $language->translate($this->deathMessage);
|
||||
}
|
||||
}else{
|
||||
$message = $this->deathMessage;
|
||||
}
|
||||
$this->session->sendDataPacket(DeathInfoPacket::create($message, $parameters));
|
||||
}
|
||||
|
||||
public function handlePlayerAction(PlayerActionPacket $packet) : bool{
|
||||
|
@ -26,6 +26,7 @@ namespace pocketmine\network\mcpe\handler;
|
||||
use pocketmine\block\BaseSign;
|
||||
use pocketmine\block\ItemFrame;
|
||||
use pocketmine\block\Lectern;
|
||||
use pocketmine\block\tile\Sign;
|
||||
use pocketmine\block\utils\SignText;
|
||||
use pocketmine\entity\animation\ConsumingItemAnimation;
|
||||
use pocketmine\entity\Attribute;
|
||||
@ -124,8 +125,8 @@ use function max;
|
||||
use function mb_strlen;
|
||||
use function microtime;
|
||||
use function sprintf;
|
||||
use function str_starts_with;
|
||||
use function strlen;
|
||||
use function strpos;
|
||||
use const JSON_THROW_ON_ERROR;
|
||||
|
||||
/**
|
||||
@ -150,6 +151,8 @@ class InGamePacketHandler extends PacketHandler{
|
||||
/** @var bool */
|
||||
public $forceMoveSync = false;
|
||||
|
||||
protected ?string $lastRequestedFullSkinId = null;
|
||||
|
||||
public function __construct(
|
||||
private Player $player,
|
||||
private NetworkSession $session,
|
||||
@ -250,6 +253,26 @@ class InGamePacketHandler extends PacketHandler{
|
||||
|
||||
$packetHandled = true;
|
||||
|
||||
$blockActions = $packet->getBlockActions();
|
||||
if($blockActions !== null){
|
||||
if(count($blockActions) > 100){
|
||||
throw new PacketHandlingException("Too many block actions in PlayerAuthInputPacket");
|
||||
}
|
||||
foreach($blockActions as $k => $blockAction){
|
||||
$actionHandled = false;
|
||||
if($blockAction instanceof PlayerBlockActionStopBreak){
|
||||
$actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), new BlockPosition(0, 0, 0), Facing::DOWN);
|
||||
}elseif($blockAction instanceof PlayerBlockActionWithBlockInfo){
|
||||
$actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), $blockAction->getBlockPosition(), $blockAction->getFace());
|
||||
}
|
||||
|
||||
if(!$actionHandled){
|
||||
$packetHandled = false;
|
||||
$this->session->getLogger()->debug("Unhandled player block action at offset $k in PlayerAuthInputPacket");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$useItemTransaction = $packet->getItemInteractionData();
|
||||
if($useItemTransaction !== null){
|
||||
if(count($useItemTransaction->getTransactionData()->getActions()) > 100){
|
||||
@ -273,26 +296,6 @@ class InGamePacketHandler extends PacketHandler{
|
||||
$this->session->sendDataPacket(ItemStackResponsePacket::create([$result]));
|
||||
}
|
||||
|
||||
$blockActions = $packet->getBlockActions();
|
||||
if($blockActions !== null){
|
||||
if(count($blockActions) > 100){
|
||||
throw new PacketHandlingException("Too many block actions in PlayerAuthInputPacket");
|
||||
}
|
||||
foreach($blockActions as $k => $blockAction){
|
||||
$actionHandled = false;
|
||||
if($blockAction instanceof PlayerBlockActionStopBreak){
|
||||
$actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), new BlockPosition(0, 0, 0), Facing::DOWN);
|
||||
}elseif($blockAction instanceof PlayerBlockActionWithBlockInfo){
|
||||
$actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), $blockAction->getBlockPosition(), $blockAction->getFace());
|
||||
}
|
||||
|
||||
if(!$actionHandled){
|
||||
$packetHandled = false;
|
||||
$this->session->getLogger()->debug("Unhandled player block action at offset $k in PlayerAuthInputPacket");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $packetHandled;
|
||||
}
|
||||
|
||||
@ -676,7 +679,7 @@ class InGamePacketHandler extends PacketHandler{
|
||||
if(!($nbt instanceof CompoundTag)) throw new AssumptionFailedError("PHPStan should ensure this is a CompoundTag"); //for phpstorm's benefit
|
||||
|
||||
if($block instanceof BaseSign){
|
||||
if(($textBlobTag = $nbt->getTag("Text")) instanceof StringTag){
|
||||
if(($textBlobTag = $nbt->getTag(Sign::TAG_TEXT_BLOB)) instanceof StringTag){
|
||||
try{
|
||||
$text = SignText::fromBlob($textBlobTag->getValue());
|
||||
}catch(\InvalidArgumentException $e){
|
||||
@ -747,7 +750,7 @@ class InGamePacketHandler extends PacketHandler{
|
||||
}
|
||||
|
||||
public function handleCommandRequest(CommandRequestPacket $packet) : bool{
|
||||
if(strpos($packet->command, '/') === 0){
|
||||
if(str_starts_with($packet->command, '/')){
|
||||
$this->player->chat($packet->command);
|
||||
return true;
|
||||
}
|
||||
@ -759,6 +762,15 @@ class InGamePacketHandler extends PacketHandler{
|
||||
}
|
||||
|
||||
public function handlePlayerSkin(PlayerSkinPacket $packet) : bool{
|
||||
if($packet->skin->getFullSkinId() === $this->lastRequestedFullSkinId){
|
||||
//TODO: HACK! In 1.19.60, the client sends its skin back to us if we sent it a skin different from the one
|
||||
//it's using. We need to prevent this from causing a feedback loop.
|
||||
$this->session->getLogger()->debug("Refused duplicate skin change request");
|
||||
return true;
|
||||
}
|
||||
$this->lastRequestedFullSkinId = $packet->skin->getFullSkinId();
|
||||
|
||||
$this->session->getLogger()->debug("Processing skin change request");
|
||||
try{
|
||||
$skin = SkinAdapterSingleton::get()->fromSkinData($packet->skin);
|
||||
}catch(InvalidSkinException $e){
|
||||
|
@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\handler;
|
||||
|
||||
use pocketmine\entity\InvalidSkinException;
|
||||
use pocketmine\event\player\PlayerPreLoginEvent;
|
||||
use pocketmine\lang\KnownTranslationFactory;
|
||||
use pocketmine\lang\KnownTranslationKeys;
|
||||
use pocketmine\network\mcpe\auth\ProcessLoginTask;
|
||||
use pocketmine\network\mcpe\convert\SkinAdapterSingleton;
|
||||
@ -33,8 +32,6 @@ use pocketmine\network\mcpe\JwtException;
|
||||
use pocketmine\network\mcpe\JwtUtils;
|
||||
use pocketmine\network\mcpe\NetworkSession;
|
||||
use pocketmine\network\mcpe\protocol\LoginPacket;
|
||||
use pocketmine\network\mcpe\protocol\PlayStatusPacket;
|
||||
use pocketmine\network\mcpe\protocol\ProtocolInfo;
|
||||
use pocketmine\network\mcpe\protocol\types\login\AuthenticationData;
|
||||
use pocketmine\network\mcpe\protocol\types\login\ClientData;
|
||||
use pocketmine\network\mcpe\protocol\types\login\ClientDataToSkinDataHelper;
|
||||
@ -63,18 +60,6 @@ class LoginPacketHandler extends PacketHandler{
|
||||
){}
|
||||
|
||||
public function handleLogin(LoginPacket $packet) : bool{
|
||||
if(!$this->isCompatibleProtocol($packet->protocol)){
|
||||
$this->session->sendDataPacket(PlayStatusPacket::create($packet->protocol < ProtocolInfo::CURRENT_PROTOCOL ? PlayStatusPacket::LOGIN_FAILED_CLIENT : PlayStatusPacket::LOGIN_FAILED_SERVER), true);
|
||||
|
||||
//This pocketmine disconnect message will only be seen by the console (PlayStatusPacket causes the messages to be shown for the client)
|
||||
$this->session->disconnect(
|
||||
$this->server->getLanguage()->translate(KnownTranslationFactory::pocketmine_disconnect_incompatibleProtocol((string) $packet->protocol)),
|
||||
false
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$extraData = $this->fetchAuthData($packet->chainDataJwt);
|
||||
|
||||
if(!Player::isValidUserName($extraData->displayName)){
|
||||
@ -84,6 +69,7 @@ class LoginPacketHandler extends PacketHandler{
|
||||
}
|
||||
|
||||
$clientData = $this->parseClientData($packet->clientDataJwt);
|
||||
|
||||
try{
|
||||
$skin = SkinAdapterSingleton::get()->fromSkinData(ClientDataToSkinDataHelper::fromClientData($clientData));
|
||||
}catch(\InvalidArgumentException | InvalidSkinException $e){
|
||||
@ -215,8 +201,4 @@ class LoginPacketHandler extends PacketHandler{
|
||||
$this->server->getAsyncPool()->submitTask(new ProcessLoginTask($packet->chainDataJwt->chain, $packet->clientDataJwt, $authRequired, $this->authCallback));
|
||||
$this->session->setHandler(null); //drop packets received during login verification
|
||||
}
|
||||
|
||||
protected function isCompatibleProtocol(int $protocolVersion) : bool{
|
||||
return $protocolVersion === ProtocolInfo::CURRENT_PROTOCOL;
|
||||
}
|
||||
}
|
||||
|
@ -24,6 +24,7 @@ declare(strict_types=1);
|
||||
namespace pocketmine\network\mcpe\handler;
|
||||
|
||||
use pocketmine\network\mcpe\protocol\PlayerAuthInputPacket;
|
||||
use pocketmine\network\mcpe\protocol\PlayerSkinPacket;
|
||||
use pocketmine\network\mcpe\protocol\SetLocalPlayerAsInitializedPacket;
|
||||
|
||||
final class SpawnResponsePacketHandler extends PacketHandler{
|
||||
@ -37,6 +38,13 @@ final class SpawnResponsePacketHandler extends PacketHandler{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function handlePlayerSkin(PlayerSkinPacket $packet) : bool{
|
||||
//TODO: REMOVE THIS
|
||||
//As of 1.19.60, we receive this packet during pre-spawn for no obvious reason. The skin is still sent in the
|
||||
//login packet, so we can ignore this one. If unhandled, this packet makes a huge debug spam in the log.
|
||||
return true;
|
||||
}
|
||||
|
||||
public function handlePlayerAuthInput(PlayerAuthInputPacket $packet) : bool{
|
||||
//the client will send this every tick once we start sending chunks, but we don't handle it in this stage
|
||||
//this is very spammy so we filter it out
|
||||
|
@ -25,17 +25,20 @@ namespace pocketmine\network\mcpe\raklib;
|
||||
|
||||
use pocketmine\network\AdvancedNetworkInterface;
|
||||
use pocketmine\network\mcpe\compression\ZlibCompressor;
|
||||
use pocketmine\network\mcpe\convert\GlobalItemTypeDictionary;
|
||||
use pocketmine\network\mcpe\convert\TypeConverter;
|
||||
use pocketmine\network\mcpe\NetworkSession;
|
||||
use pocketmine\network\mcpe\PacketBroadcaster;
|
||||
use pocketmine\network\mcpe\protocol\PacketPool;
|
||||
use pocketmine\network\mcpe\protocol\ProtocolInfo;
|
||||
use pocketmine\network\mcpe\protocol\serializer\PacketSerializerContext;
|
||||
use pocketmine\network\mcpe\StandardPacketBroadcaster;
|
||||
use pocketmine\network\Network;
|
||||
use pocketmine\network\NetworkInterfaceStartException;
|
||||
use pocketmine\network\PacketHandlingException;
|
||||
use pocketmine\Server;
|
||||
use pocketmine\snooze\SleeperNotifier;
|
||||
use pocketmine\timings\Timings;
|
||||
use pocketmine\utils\Utils;
|
||||
use raklib\generic\SocketException;
|
||||
use raklib\protocol\EncapsulatedPacket;
|
||||
@ -78,6 +81,7 @@ class RakLibInterface implements ServerEventListener, AdvancedNetworkInterface{
|
||||
private SleeperNotifier $sleeper;
|
||||
|
||||
private PacketBroadcaster $broadcaster;
|
||||
private PacketSerializerContext $packetSerializerContext;
|
||||
|
||||
public function __construct(Server $server, string $ip, int $port, bool $ipV6){
|
||||
$this->server = $server;
|
||||
@ -105,12 +109,18 @@ class RakLibInterface implements ServerEventListener, AdvancedNetworkInterface{
|
||||
new PthreadsChannelWriter($mainToThreadBuffer)
|
||||
);
|
||||
|
||||
$this->broadcaster = new StandardPacketBroadcaster($this->server);
|
||||
$this->packetSerializerContext = new PacketSerializerContext(GlobalItemTypeDictionary::getInstance()->getDictionary());
|
||||
$this->broadcaster = new StandardPacketBroadcaster($this->server, $this->packetSerializerContext);
|
||||
}
|
||||
|
||||
public function start() : void{
|
||||
$this->server->getTickSleeper()->addNotifier($this->sleeper, function() : void{
|
||||
while($this->eventReceiver->handle($this));
|
||||
Timings::$connection->startTiming();
|
||||
try{
|
||||
while($this->eventReceiver->handle($this));
|
||||
}finally{
|
||||
Timings::$connection->stopTiming();
|
||||
}
|
||||
});
|
||||
$this->server->getLogger()->debug("Waiting for RakLib to start...");
|
||||
try{
|
||||
@ -160,6 +170,7 @@ class RakLibInterface implements ServerEventListener, AdvancedNetworkInterface{
|
||||
$this->server,
|
||||
$this->network->getSessionManager(),
|
||||
PacketPool::getInstance(),
|
||||
$this->packetSerializerContext,
|
||||
new RakLibPacketSender($sessionId, $this),
|
||||
$this->broadcaster,
|
||||
ZlibCompressor::getInstance(), //TODO: this shouldn't be hardcoded, but we might need the RakNet protocol version to select it
|
||||
|
Reference in New Issue
Block a user