Implement DataPacketPreReceiveEvent (#5559)

closes #5554

This is called just before the packet is decoded, allowing the event to be used to drop packets from clients without wasting CPU time decoding them. This can be particularly useful for mitigating denial-of-service attacks.
This commit is contained in:
Armen Deroian 2023-03-15 18:47:19 -04:00 committed by GitHub
parent 08ee825d91
commit 183d1f4038
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 61 additions and 0 deletions

View File

@ -0,0 +1,54 @@
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\event\server;
use pocketmine\event\Cancellable;
use pocketmine\event\CancellableTrait;
use pocketmine\network\mcpe\NetworkSession;
/**
* Called before a packet is decoded and handled by the network session.
* Cancelling this event will drop the packet without decoding it, minimizing wasted CPU time.
*/
class DataPacketPreReceiveEvent extends ServerEvent implements Cancellable{
use CancellableTrait;
public function __construct(
private NetworkSession $origin,
private int $packetId,
private string $packetBuffer
){}
public function getOrigin() : NetworkSession{
return $this->origin;
}
public function getPacketId() : int{
return $this->packetId;
}
public function getPacketBuffer() : string{
return $this->packetBuffer;
}
}

View File

@ -25,6 +25,7 @@ namespace pocketmine\network\mcpe;
use pocketmine\entity\effect\EffectInstance;
use pocketmine\event\player\PlayerDuplicateLoginEvent;
use pocketmine\event\server\DataPacketPreReceiveEvent;
use pocketmine\event\server\DataPacketReceiveEvent;
use pocketmine\event\server\DataPacketSendEvent;
use pocketmine\form\Form;
@ -412,6 +413,12 @@ class NetworkSession{
$timings->startTiming();
try{
$ev = new DataPacketPreReceiveEvent($this, $packet->pid(), $buffer);
$ev->call();
if($ev->isCancelled()){
return;
}
$decodeTimings = Timings::getDecodeDataPacketTimings($packet);
$decodeTimings->startTiming();
try{