Replace disallowed operators in src/network/

This commit is contained in:
Dylan K. Taylor 2022-01-20 19:11:32 +00:00
parent 2bcb629d78
commit be1996752a
No known key found for this signature in database
GPG Key ID: 8927471A91CAFD3D
15 changed files with 35 additions and 35 deletions

View File

@ -191,7 +191,7 @@ class Network{
} }
public function processRawPacket(AdvancedNetworkInterface $interface, string $address, int $port, string $packet) : void{ public function processRawPacket(AdvancedNetworkInterface $interface, string $address, int $port, string $packet) : void{
if(isset($this->bannedIps[$address]) and time() < $this->bannedIps[$address]){ if(isset($this->bannedIps[$address]) && time() < $this->bannedIps[$address]){
$this->logger->debug("Dropped raw packet from banned address $address $port"); $this->logger->debug("Dropped raw packet from banned address $address $port");
return; return;
} }

View File

@ -138,7 +138,7 @@ class InventoryManager{
public function onTransactionStart(InventoryTransaction $tx) : void{ public function onTransactionStart(InventoryTransaction $tx) : void{
foreach($tx->getActions() as $action){ foreach($tx->getActions() as $action){
if($action instanceof SlotChangeAction and ($windowId = $this->getWindowId($action->getInventory())) !== null){ if($action instanceof SlotChangeAction && ($windowId = $this->getWindowId($action->getInventory())) !== null){
//in some cases the inventory might not have a window ID, but still be referenced by a transaction (e.g. crafting grid changes), so we can't unconditionally record the change here or we might leak things //in some cases the inventory might not have a window ID, but still be referenced by a transaction (e.g. crafting grid changes), so we can't unconditionally record the change here or we might leak things
$this->initiatedSlotChanges[$windowId][$action->getSlot()] = $action->getTargetItem(); $this->initiatedSlotChanges[$windowId][$action->getSlot()] = $action->getTargetItem();
} }
@ -236,7 +236,7 @@ class InventoryManager{
if($windowId !== null){ if($windowId !== null){
$currentItem = $inventory->getItem($slot); $currentItem = $inventory->getItem($slot);
$clientSideItem = $this->initiatedSlotChanges[$windowId][$slot] ?? null; $clientSideItem = $this->initiatedSlotChanges[$windowId][$slot] ?? null;
if($clientSideItem === null or !$clientSideItem->equalsExact($currentItem)){ if($clientSideItem === null || !$clientSideItem->equalsExact($currentItem)){
$itemStackWrapper = ItemStackWrapper::legacy(TypeConverter::getInstance()->coreItemStackToNet($currentItem)); $itemStackWrapper = ItemStackWrapper::legacy(TypeConverter::getInstance()->coreItemStackToNet($currentItem));
if($windowId === ContainerIds::OFFHAND){ if($windowId === ContainerIds::OFFHAND){
//TODO: HACK! //TODO: HACK!

View File

@ -392,7 +392,7 @@ class NetworkSession{
$ev = new DataPacketReceiveEvent($this, $packet); $ev = new DataPacketReceiveEvent($this, $packet);
$ev->call(); $ev->call();
if(!$ev->isCancelled() and ($this->handler === null or !$packet->handle($this->handler))){ if(!$ev->isCancelled() && ($this->handler === null || !$packet->handle($this->handler))){
$this->logger->debug("Unhandled " . $packet->getName() . ": " . base64_encode($stream->getBuffer())); $this->logger->debug("Unhandled " . $packet->getName() . ": " . base64_encode($stream->getBuffer()));
} }
}finally{ }finally{
@ -402,7 +402,7 @@ class NetworkSession{
public function sendDataPacket(ClientboundPacket $packet, bool $immediate = false) : bool{ public function sendDataPacket(ClientboundPacket $packet, bool $immediate = false) : bool{
//Basic safety restriction. TODO: improve this //Basic safety restriction. TODO: improve this
if(!$this->loggedIn and !$packet->canBeSentBeforeLogin()){ if(!$this->loggedIn && !$packet->canBeSentBeforeLogin()){
throw new \InvalidArgumentException("Attempted to send " . get_class($packet) . " to " . $this->getDisplayName() . " too early"); throw new \InvalidArgumentException("Attempted to send " . get_class($packet) . " to " . $this->getDisplayName() . " too early");
} }
@ -473,7 +473,7 @@ class NetworkSession{
}else{ }else{
$this->compressedQueue->enqueue($payload); $this->compressedQueue->enqueue($payload);
$payload->onResolve(function(CompressBatchPromise $payload) : void{ $payload->onResolve(function(CompressBatchPromise $payload) : void{
if($this->connected and $this->compressedQueue->bottom() === $payload){ if($this->connected && $this->compressedQueue->bottom() === $payload){
$this->compressedQueue->dequeue(); //result unused $this->compressedQueue->dequeue(); //result unused
$this->sendEncoded($payload->getResult()); $this->sendEncoded($payload->getResult());
@ -507,7 +507,7 @@ class NetworkSession{
* @phpstan-param \Closure() : void $func * @phpstan-param \Closure() : void $func
*/ */
private function tryDisconnect(\Closure $func, string $reason) : void{ private function tryDisconnect(\Closure $func, string $reason) : void{
if($this->connected and !$this->disconnectGuard){ if($this->connected && !$this->disconnectGuard){
$this->disconnectGuard = true; $this->disconnectGuard = true;
$func(); $func();
$this->disconnectGuard = false; $this->disconnectGuard = false;
@ -586,7 +586,7 @@ class NetworkSession{
return; return;
} }
if($error === null){ if($error === null){
if($authenticated and !($this->info instanceof XboxLivePlayerInfo)){ if($authenticated && !($this->info instanceof XboxLivePlayerInfo)){
$error = "Expected XUID but none found"; $error = "Expected XUID but none found";
}elseif($clientPubKey === null){ }elseif($clientPubKey === null){
$error = "Missing client public key"; //failsafe $error = "Missing client public key"; //failsafe
@ -633,7 +633,7 @@ class NetworkSession{
continue; continue;
} }
$info = $existingSession->getPlayerInfo(); $info = $existingSession->getPlayerInfo();
if($info !== null and ($info->getUsername() === $this->info->getUsername() or $info->getUuid()->equals($this->info->getUuid()))){ if($info !== null && ($info->getUsername() === $this->info->getUsername() || $info->getUuid()->equals($this->info->getUuid()))){
if($kickForXUIDMismatch($info instanceof XboxLivePlayerInfo ? $info->getXuid() : "")){ if($kickForXUIDMismatch($info instanceof XboxLivePlayerInfo ? $info->getXuid() : "")){
return; return;
} }
@ -840,7 +840,7 @@ class NetworkSession{
public function syncAvailableCommands() : void{ public function syncAvailableCommands() : void{
$commandData = []; $commandData = [];
foreach($this->server->getCommandMap()->getCommands() as $name => $command){ foreach($this->server->getCommandMap()->getCommands() as $name => $command){
if(isset($commandData[$command->getName()]) or $command->getName() === "help" or !$command->testPermissionSilent($this->player)){ if(isset($commandData[$command->getName()]) || $command->getName() === "help" || !$command->testPermissionSilent($this->player)){
continue; continue;
} }
@ -920,7 +920,7 @@ class NetworkSession{
return; return;
} }
$currentWorld = $this->player->getLocation()->getWorld(); $currentWorld = $this->player->getLocation()->getWorld();
if($world !== $currentWorld or ($status = $this->player->getUsedChunkStatus($chunkX, $chunkZ)) === null){ if($world !== $currentWorld || ($status = $this->player->getUsedChunkStatus($chunkX, $chunkZ)) === null){
$this->logger->debug("Tried to send no-longer-active chunk $chunkX $chunkZ in world " . $world->getFolderName()); $this->logger->debug("Tried to send no-longer-active chunk $chunkX $chunkZ in world " . $world->getFolderName());
return; return;
} }

View File

@ -174,11 +174,11 @@ class ProcessLoginTask extends AsyncTask{
} }
$time = time(); $time = time();
if(isset($claims->nbf) and $claims->nbf > $time + self::CLOCK_DRIFT_MAX){ if(isset($claims->nbf) && $claims->nbf > $time + self::CLOCK_DRIFT_MAX){
throw new VerifyLoginException(KnownTranslationKeys::POCKETMINE_DISCONNECT_INVALIDSESSION_TOOEARLY); throw new VerifyLoginException(KnownTranslationKeys::POCKETMINE_DISCONNECT_INVALIDSESSION_TOOEARLY);
} }
if(isset($claims->exp) and $claims->exp < $time - self::CLOCK_DRIFT_MAX){ if(isset($claims->exp) && $claims->exp < $time - self::CLOCK_DRIFT_MAX){
throw new VerifyLoginException(KnownTranslationKeys::POCKETMINE_DISCONNECT_INVALIDSESSION_TOOLATE); throw new VerifyLoginException(KnownTranslationKeys::POCKETMINE_DISCONNECT_INVALIDSESSION_TOOLATE);
} }

View File

@ -160,7 +160,7 @@ class ChunkCache implements ChunkListener{
private function restartPendingRequest(int $chunkX, int $chunkZ) : void{ private function restartPendingRequest(int $chunkX, int $chunkZ) : void{
$chunkHash = World::chunkHash($chunkX, $chunkZ); $chunkHash = World::chunkHash($chunkX, $chunkZ);
$existing = $this->caches[$chunkHash] ?? null; $existing = $this->caches[$chunkHash] ?? null;
if($existing === null or $existing->hasResult()){ if($existing === null || $existing->hasResult()){
throw new \InvalidArgumentException("Restart can only be applied to unresolved promises"); throw new \InvalidArgumentException("Restart can only be applied to unresolved promises");
} }
$existing->cancel(); $existing->cancel();

View File

@ -60,7 +60,7 @@ final class ZlibCompressor implements Compressor{
} }
public function willCompress(string $data) : bool{ public function willCompress(string $data) : bool{
return $this->threshold > -1 and strlen($data) >= $this->threshold; return $this->threshold > -1 && strlen($data) >= $this->threshold;
} }
/** /**

View File

@ -69,7 +69,7 @@ final class ItemTranslator{
private static function make() : self{ 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 = Utils::assumeNotFalse(file_get_contents(Path::join(\pocketmine\BEDROCK_DATA_PATH, 'r16_to_current_item_map.json')), "Missing required resource file");
$json = json_decode($data, true); $json = json_decode($data, true);
if(!is_array($json) or !isset($json["simple"], $json["complex"]) || !is_array($json["simple"]) || !is_array($json["complex"])){ if(!is_array($json) || !isset($json["simple"], $json["complex"]) || !is_array($json["simple"]) || !is_array($json["complex"])){
throw new AssumptionFailedError("Invalid item table format"); throw new AssumptionFailedError("Invalid item table format");
} }

View File

@ -156,7 +156,7 @@ class TypeConverter{
}else{ }else{
[$id, $meta] = $idMeta; [$id, $meta] = $idMeta;
if($itemStack instanceof Durable and $itemStack->getDamage() > 0){ if($itemStack instanceof Durable && $itemStack->getDamage() > 0){
if($nbt !== null){ if($nbt !== null){
if(($existing = $nbt->getTag(self::DAMAGE_TAG)) !== null){ if(($existing = $nbt->getTag(self::DAMAGE_TAG)) !== null){
$nbt->removeTag(self::DAMAGE_TAG); $nbt->removeTag(self::DAMAGE_TAG);
@ -266,7 +266,7 @@ class TypeConverter{
switch($action->sourceType){ switch($action->sourceType){
case NetworkInventoryAction::SOURCE_CONTAINER: case NetworkInventoryAction::SOURCE_CONTAINER:
$window = null; $window = null;
if($action->windowId === ContainerIds::UI and $action->inventorySlot > 0){ if($action->windowId === ContainerIds::UI && $action->inventorySlot > 0){
if($action->inventorySlot === UIInventorySlotOffset::CREATED_ITEM_OUTPUT){ if($action->inventorySlot === UIInventorySlotOffset::CREATED_ITEM_OUTPUT){
return null; //useless noise return null; //useless noise
} }

View File

@ -201,7 +201,7 @@ class InGamePacketHandler extends PacketHandler{
$curPos = $this->player->getLocation(); $curPos = $this->player->getLocation();
$newPos = $rawPos->round(4)->subtract(0, 1.62, 0); $newPos = $rawPos->round(4)->subtract(0, 1.62, 0);
if($this->forceMoveSync and $newPos->distanceSquared($curPos) > 1){ //Tolerate up to 1 block to avoid problems with client-sided physics when spawning in blocks if($this->forceMoveSync && $newPos->distanceSquared($curPos) > 1){ //Tolerate up to 1 block to avoid problems with client-sided physics when spawning in blocks
$this->session->getLogger()->debug("Got outdated pre-teleport movement, received " . $newPos . ", expected " . $curPos); $this->session->getLogger()->debug("Got outdated pre-teleport movement, received " . $newPos . ", expected " . $curPos);
//Still getting movements from before teleport, ignore them //Still getting movements from before teleport, ignore them
return false; return false;
@ -316,11 +316,11 @@ class InGamePacketHandler extends PacketHandler{
foreach($data->getActions() as $networkInventoryAction){ foreach($data->getActions() as $networkInventoryAction){
if( if(
( (
$networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_TODO and ( $networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_TODO && (
$networkInventoryAction->windowId === NetworkInventoryAction::SOURCE_TYPE_CRAFTING_RESULT or $networkInventoryAction->windowId === NetworkInventoryAction::SOURCE_TYPE_CRAFTING_RESULT ||
$networkInventoryAction->windowId === NetworkInventoryAction::SOURCE_TYPE_CRAFTING_USE_INGREDIENT $networkInventoryAction->windowId === NetworkInventoryAction::SOURCE_TYPE_CRAFTING_USE_INGREDIENT
) )
) or ( ) || (
$this->craftingTransaction !== null && $this->craftingTransaction !== null &&
!$networkInventoryAction->oldItem->getItemStack()->equals($networkInventoryAction->newItem->getItemStack()) && !$networkInventoryAction->oldItem->getItemStack()->equals($networkInventoryAction->newItem->getItemStack()) &&
$networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_CONTAINER && $networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_CONTAINER &&
@ -415,10 +415,10 @@ class InGamePacketHandler extends PacketHandler{
case UseItemTransactionData::ACTION_CLICK_BLOCK: case UseItemTransactionData::ACTION_CLICK_BLOCK:
//TODO: start hack for client spam bug //TODO: start hack for client spam bug
$clickPos = $data->getClickPosition(); $clickPos = $data->getClickPosition();
$spamBug = ($this->lastRightClickData !== null and $spamBug = ($this->lastRightClickData !== null &&
microtime(true) - $this->lastRightClickTime < 0.1 and //100ms microtime(true) - $this->lastRightClickTime < 0.1 && //100ms
$this->lastRightClickData->getPlayerPosition()->distanceSquared($data->getPlayerPosition()) < 0.00001 and $this->lastRightClickData->getPlayerPosition()->distanceSquared($data->getPlayerPosition()) < 0.00001 &&
$this->lastRightClickData->getBlockPosition()->equals($data->getBlockPosition()) and $this->lastRightClickData->getBlockPosition()->equals($data->getBlockPosition()) &&
$this->lastRightClickData->getClickPosition()->distanceSquared($clickPos) < 0.00001 //signature spam bug has 0 distance, but allow some error $this->lastRightClickData->getClickPosition()->distanceSquared($clickPos) < 0.00001 //signature spam bug has 0 distance, but allow some error
); );
//get rid of continued spam if the player clicks and holds right-click //get rid of continued spam if the player clicks and holds right-click
@ -731,7 +731,7 @@ class InGamePacketHandler extends PacketHandler{
public function handleItemFrameDropItem(ItemFrameDropItemPacket $packet) : bool{ public function handleItemFrameDropItem(ItemFrameDropItemPacket $packet) : bool{
$blockPosition = $packet->blockPosition; $blockPosition = $packet->blockPosition;
$block = $this->player->getWorld()->getBlockAt($blockPosition->getX(), $blockPosition->getY(), $blockPosition->getZ()); $block = $this->player->getWorld()->getBlockAt($blockPosition->getX(), $blockPosition->getY(), $blockPosition->getZ());
if($block instanceof ItemFrame and $block->getFramedItem() !== null){ if($block instanceof ItemFrame && $block->getFramedItem() !== null){
return $this->player->attackBlock(new Vector3($blockPosition->getX(), $blockPosition->getY(), $blockPosition->getZ()), $block->getFacing()); return $this->player->attackBlock(new Vector3($blockPosition->getX(), $blockPosition->getY(), $blockPosition->getZ()), $block->getFacing());
} }
return false; return false;
@ -822,7 +822,7 @@ class InGamePacketHandler extends PacketHandler{
$modifiedPages[] = $packet->pageNumber; $modifiedPages[] = $packet->pageNumber;
break; break;
case BookEditPacket::TYPE_SWAP_PAGES: case BookEditPacket::TYPE_SWAP_PAGES:
if(!$newBook->pageExists($packet->pageNumber) or !$newBook->pageExists($packet->secondaryPageNumber)){ if(!$newBook->pageExists($packet->pageNumber) || !$newBook->pageExists($packet->secondaryPageNumber)){
//the client will create pages on its own without telling us until it tries to switch them //the client will create pages on its own without telling us until it tries to switch them
$newBook->addPage(max($packet->pageNumber, $packet->secondaryPageNumber)); $newBook->addPage(max($packet->pageNumber, $packet->secondaryPageNumber));
} }
@ -897,7 +897,7 @@ class InGamePacketHandler extends PacketHandler{
$newParts = []; $newParts = [];
$inQuotes = false; $inQuotes = false;
for($i = 0, $len = strlen($raw); $i <= $len; ++$i){ for($i = 0, $len = strlen($raw); $i <= $len; ++$i){
if($i === $len or ($raw[$i] === "," and !$inQuotes)){ if($i === $len || ($raw[$i] === "," && !$inQuotes)){
$part = substr($raw, $lastComma + 1, $i - ($lastComma + 1)); $part = substr($raw, $lastComma + 1, $i - ($lastComma + 1));
if(trim($part) === ""){ //regular parts will have quotes or something else that makes them non-empty if(trim($part) === ""){ //regular parts will have quotes or something else that makes them non-empty
$part = '""'; $part = '""';

View File

@ -145,7 +145,7 @@ class LoginPacketHandler extends PacketHandler{
if(!$this->server->isWhitelisted($playerInfo->getUsername())){ if(!$this->server->isWhitelisted($playerInfo->getUsername())){
$ev->setKickReason(PlayerPreLoginEvent::KICK_REASON_SERVER_WHITELISTED, "Server is whitelisted"); $ev->setKickReason(PlayerPreLoginEvent::KICK_REASON_SERVER_WHITELISTED, "Server is whitelisted");
} }
if($this->server->getNameBans()->isBanned($playerInfo->getUsername()) or $this->server->getIPBans()->isBanned($this->session->getIp())){ if($this->server->getNameBans()->isBanned($playerInfo->getUsername()) || $this->server->getIPBans()->isBanned($this->session->getIp())){
$ev->setKickReason(PlayerPreLoginEvent::KICK_REASON_BANNED, "You are banned"); $ev->setKickReason(PlayerPreLoginEvent::KICK_REASON_BANNED, "You are banned");
} }

View File

@ -163,7 +163,7 @@ class ResourcePacksPacketHandler extends PacketHandler{
} }
$offset = $packet->chunkIndex * self::PACK_CHUNK_SIZE; $offset = $packet->chunkIndex * self::PACK_CHUNK_SIZE;
if($offset < 0 or $offset >= $pack->getPackSize()){ if($offset < 0 || $offset >= $pack->getPackSize()){
$this->disconnectWithError("Invalid out-of-bounds request for chunk $packet->chunkIndex of $packet->packId: offset $offset, file size " . $pack->getPackSize()); $this->disconnectWithError("Invalid out-of-bounds request for chunk $packet->chunkIndex of $packet->packId: offset $offset, file size " . $pack->getPackSize());
return false; return false;
} }

View File

@ -180,7 +180,7 @@ class RakLibInterface implements ServerEventListener, AdvancedNetworkInterface{
public function onPacketReceive(int $sessionId, string $packet) : void{ public function onPacketReceive(int $sessionId, string $packet) : void{
if(isset($this->sessions[$sessionId])){ if(isset($this->sessions[$sessionId])){
if($packet === "" or $packet[0] !== self::MCPE_RAKNET_PACKET_ID){ if($packet === "" || $packet[0] !== self::MCPE_RAKNET_PACKET_ID){
$this->sessions[$sessionId]->getLogger()->debug("Non-FE packet received: " . base64_encode($packet)); $this->sessions[$sessionId]->getLogger()->debug("Non-FE packet received: " . base64_encode($packet));
return; return;
} }

View File

@ -129,7 +129,7 @@ class RakLibServer extends Thread{
public function startAndWait(int $options = PTHREADS_INHERIT_NONE) : void{ public function startAndWait(int $options = PTHREADS_INHERIT_NONE) : void{
$this->start($options); $this->start($options);
$this->synchronized(function() : void{ $this->synchronized(function() : void{
while(!$this->ready and $this->crashInfo === null){ while(!$this->ready && $this->crashInfo === null){
$this->wait(); $this->wait();
} }
$crashInfo = $this->crashInfo; $crashInfo = $this->crashInfo;

View File

@ -104,7 +104,7 @@ class QueryHandler implements RawPacketHandler{
return true; return true;
case self::STATISTICS: //Stat case self::STATISTICS: //Stat
$token = $stream->getInt(); $token = $stream->getInt();
if($token !== ($t1 = self::getTokenString($this->token, $address)) and $token !== ($t2 = self::getTokenString($this->lastToken, $address))){ if($token !== ($t1 = self::getTokenString($this->token, $address)) && $token !== ($t2 = self::getTokenString($this->lastToken, $address))){
$this->logger->debug("Bad token $token from $address $port, expected $t1 or $t2"); $this->logger->debug("Bad token $token from $address $port, expected $t1 or $t2");
return true; return true;

View File

@ -204,7 +204,7 @@ final class QueryInfo{
$query = ""; $query = "";
$plist = $this->server_engine; $plist = $this->server_engine;
if(count($this->plugins) > 0 and $this->listPlugins){ if(count($this->plugins) > 0 && $this->listPlugins){
$plist .= ":"; $plist .= ":";
foreach($this->plugins as $p){ foreach($this->plugins as $p){
$d = $p->getDescription(); $d = $p->getDescription();