Compare commits

...

3 commits

Author SHA1 Message Date
GameHerobrine
8208e4119c small tweaks 2026-11-02 03:36:26 +03:00
GameHerobrine
f377361ff0 use 2 separate counters for nack and ack packets, chunk resends will happen every 2 seconds instead of 1 2026-11-02 02:26:18 +03:00
GameHerobrine
f12315bd3f better max ack detection 2026-11-01 22:49:58 +03:00
6 changed files with 176 additions and 57 deletions

View file

@ -148,7 +148,9 @@ class PlayerAPI{
if($additional){
$arqCnt = count($p->packetAlwaysRecoverQueue);
$rqCnt = count($p->recoveryQueue);
$additionalInfo = "ARQ/RQ/EMPS: $arqCnt/$rqCnt";
$maxAck = $this->server->interface->maxACKsAllowed["{$p->ip}:{$p->port}"] ?? "???";
$maxNack = $this->server->interface->maxNACKsAllowed["{$p->ip}:{$p->port}"] ?? "???";
$additionalInfo = "ARQ/RQ/MACK/MNAK: $arqCnt/$rqCnt/$maxAck/$maxNack";
}
$chunksCnt = count($p->chunkDataSent);
return "{$p->username}'s ping: {$ping}ms, packet loss {$pkLoss}%, $transfer KB/s. Chunks: $chunksCnt/256\n$additionalInfo";

View file

@ -83,8 +83,8 @@ class Player{
private $timeout;
private $connected = true;
private $clientID;
private $ip;
private $port;
public $ip;
public $port;
private $counter = [0, 0, 0, 0];
public $username;
public $iusername;
@ -188,6 +188,9 @@ class Player{
*/
public function __construct($clientID, $ip, $port, $MTU){
$this->bigCnt = 0;
//setting it above 1100 may cause issues for players on some servers
//(see 236e98be23c7f0d0654ae9af40703e4e4e89516a)
//(duplicated here cuz i wanted to remove it)
$this->MTU = min($MTU, 1100);
$this->server = ServerAPI::request();
$this->lastBreak = microtime(true);
@ -223,7 +226,7 @@ class Player{
$this->chatMessagesQueue->data = [];
$this->server->schedule(20 * 60, [$this, "clearQueue"], [], true);
$this->server->interface->maxACKsAllowed["{$this->ip}:{$this->port}"] = 0;
$this->server->interface->init($this->ip, $this->port);
$this->evid[] = $this->server->event("server.close", [$this, "close"]);
console("[DEBUG] New Session started with $ip:$port. MTU {$this->MTU}, Client ID {$this->clientID}", true, true, 2);
}
@ -485,6 +488,7 @@ class Player{
$pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$pk->data[] = $packet;
$pk->seqNumber = $this->counter[0]++;
//$this->counter[0] += 5000;
$pk->sendtime = microtime(true);
if($recover !== false){
$this->recoveryQueue[$pk->seqNumber] = $pk;
@ -530,11 +534,6 @@ class Player{
if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return false;
if(!$this->convertToLocalEIDPacket($packet)) return false;
$pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$pk->data[] = $packet;
$pk->seqNumber = $this->counter[0]++;
$pk->sendtime = microtime(true);
$packet->encode();
$len = strlen($packet->buffer) + 1;
$MTU = $this->MTU - 24;
@ -542,6 +541,11 @@ class Player{
return $this->sendBigPacketAlwaysRecover($packet); //TODO fix
}
$pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$pk->data[] = $packet;
$pk->seqNumber = $this->counter[0]++;
$pk->sendtime = microtime(true);
$packet->messageIndex = $this->counter[3]++;
$packet->reliability = RakNetInfo::RELIABILITY_RELIABLE;
@ -1574,8 +1578,13 @@ class Player{
}
}
}
public function handlePacketQueues(){
/*$acks = $this->server->interface->maxACKsAllowed["{$this->ip}:{$this->port}"] ?? 0;
$nacks = $this->server->interface->maxNACKsAllowed["{$this->ip}:{$this->port}"] ?? 0;
console("acK: {$acks} nack: {$nacks}");*/
if($this->server->ticks % 40 == 0){ //2s
$this->sendPing();
}
@ -1594,7 +1603,7 @@ class Player{
$this->close("timeout");
return false;
}
if(($ackCnt = count($this->ackQueue)) > 0){
rsort($this->ackQueue);
$safeCount = (int) (($this->MTU - 1) / 4);
@ -1705,7 +1714,7 @@ class Player{
}
foreach($this->packetAlwaysRecoverQueue as $cnt => $data){
$maxDelay = (isset($this->chunkCount[$cnt])) ? 1 : 5;
$maxDelay = (isset($this->chunkCount[$cnt])) ? 2 : 5;
if($time - $data->sendtime >= $maxDelay){
$this->resendQueue[$cnt] = $data;
}
@ -2023,7 +2032,8 @@ class Player{
}
public function __destruct(){ //pwease dont leak memory >_<
unset($this->server->interface->maxACKsAllowed["{$this->ip}:{$this->port}"]);
$server = ServerAPI::request();
$server->interface->clear($this->ip, $this->port);
}
public function save(){
@ -2097,7 +2107,6 @@ class Player{
}
public function entityTick(){
if($this->isSleeping) ++$this->sleepingTime;
if($this->server->difficulty == 0 && $this->entity->counter % (20 * 15) == 0){
if($this->entity->health < 20 && $this->entity->health > 0){
@ -2193,6 +2202,7 @@ class Player{
$this->close("Incorrect protocol #" . $packet->protocol1, false);
return;
}
if(preg_match('#[^a-zA-Z0-9_]#', $this->username) > 0 || $this->username === "" || isset(Player::$blacklistedUsernames[$this->iusername]) || strlen($this->iusername) > 16){
$this->close("Bad username", false);
return;
@ -3565,41 +3575,44 @@ class Player{
return true;
}
public $maxRecvPacketSeq = 0;
public function handlePacket(RakNetPacket $packet){
if($this->connected === true){
$time = microtime(true);
$this->timeout = $time + 20;
switch($packet->pid()){
case RakNetInfo::NACK:
foreach($packet->packets as $count){
if(isset($this->packetAlwaysRecoverQueue[$count])){
$this->resendQueue[$count] = $this->packetAlwaysRecoverQueue[$count];
$this->resendQueue[$count]->incrementAllowedAck = false;
}else if(isset($this->recoveryQueue[$count])){
$this->resendQueue[$count] =& $this->recoveryQueue[$count];
$this->resendQueue[$count]->incrementAllowedAck = false;
$this->lag[] = $time - $this->recoveryQueue[$count]->sendtime;
unset($this->recoveryQueue[$count]);
}else{ //lost and wont be recovered
++$this->packetStats[1];
foreach($packet->packets->sequences as $start => $end){
for($count = $start; $count <= $end; ++$count){
if(isset($this->packetAlwaysRecoverQueue[$count])){
$this->resendQueue[$count] = $this->packetAlwaysRecoverQueue[$count];
}else if(isset($this->recoveryQueue[$count])){
$this->resendQueue[$count] = $this->recoveryQueue[$count];
$this->lag[] = $time - $this->recoveryQueue[$count]->sendtime;
unset($this->recoveryQueue[$count]);
}else{ //lost and wont be recovered
++$this->packetStats[1];
}
}
}
break;
case RakNetInfo::ACK:
//if(mt_rand(0, 99) > 50) break;
foreach($packet->packets as $count){
if(isset($this->packetAlwaysRecoverQueue[$count])){
$this->lag[] = $time - $this->packetAlwaysRecoverQueue[$count]->sendtime;
foreach($packet->packets->sequences as $start => $end){
for($count = $start; $count <= $end; ++$count){
if(isset($this->packetAlwaysRecoverQueue[$count])){
$this->lag[] = $time - $this->packetAlwaysRecoverQueue[$count]->sendtime;
}else if(isset($this->recoveryQueue[$count])){
$this->lag[] = $time - $this->recoveryQueue[$count]->sendtime;
}
unset($this->recoveryQueue[$count]);
unset($this->packetAlwaysRecoverQueue[$count]);
unset($this->chunkCount[$count]);
}else if(isset($this->recoveryQueue[$count])){
$this->lag[] = $time - $this->recoveryQueue[$count]->sendtime;
unset($this->recoveryQueue[$count]);
unset($this->resendQueue[$count]);
++$this->packetStats[0];
}
unset($this->resendQueue[$count]);
++$this->packetStats[0];
}
break;
@ -3620,6 +3633,19 @@ class Player{
case RakNetInfo::DATA_PACKET_E:
case RakNetInfo::DATA_PACKET_F:
$this->ackQueue[] = $packet->seqNumber;
if($packet->seqNumber > $this->maxRecvPacketSeq){
/*
TODO send NACKs
$diff = $packet->seqNumber - $this->maxRecvPacketSeq;
if($diff > 1){
console("diff is more than 1, sending nacks");
$diff = $diff > 1000 ? 1000 : $diff;
$this->nackQueue[$packet->seqNumber] = $packet->seqNumber+$diff;
}*/
$this->maxRecvPacketSeq = $packet->seqNumber;
}
$this->receiveQueue[$packet->seqNumber] = [];
foreach($packet->data as $pk){
$this->receiveQueue[$packet->seqNumber][] = $pk;

View file

@ -36,13 +36,38 @@ class MinecraftInterface{
ServerAPI::request()->api->dhandle("mcinterface.read", ["buffer" => $buf, "source" => $source, "port" => $port]);
return $this->parsePacket($buf, $source, $port);
}
public function clear($ip, $port){
$id = "$ip:$port";
unset($this->maxACKsAllowed[$id]);
unset($this->maxRecordedSeq[$id]);
unset($this->maxNACKsAllowed[$id]);
}
public function init($ip, $port){
$id = "$ip:$port";
$this->maxACKsAllowed[$id] = 0;
unset($this->maxRecordedSeq[$id]);
$this->maxNACKsAllowed[$id] = 0;
}
/**
* Stores max ACK packets that the server is allowed to handle.
*
* Max ACK packets the client is allowed to send
* @var array
*/
public $maxACKsAllowed = [];
/**
* Max NACK packets the client is allowed to send
* @var array
*/
public $maxNACKsAllowed = [];
/**
* Max packet seq number. Used to determine allowed nack cnt increment per packet
*
* @var array
*/
public $maxRecordedSeq = [];
private function parsePacket($buffer, $source, $port){
$pid = ord($buffer[0]);
@ -50,12 +75,18 @@ class MinecraftInterface{
if(RakNetInfo::isValid($pid)){
$id = "$source:$port";
$ackCnt = 0;
$nackCnt = 0;
$acks = $this->maxACKsAllowed[$id] ?? 0;
$packet = RakNetParser::parse($buffer, $acks, $ackCnt);
$nacks = $this->maxNACKsAllowed[$id] ?? 0;
$packet = RakNetParser::parse($buffer, $acks, $nacks, $ackCnt, $nackCnt); //TODO rewrite this mess later (hai "this code is still horribly ugly, messy, and unmaintainable")
if($packet !== false){
if($ackCnt != 0 && isset($this->maxACKsAllowed[$id]) && $packet->pid() != RakNetInfo::NACK){
$this->maxACKsAllowed[$id] = $acks - $ackCnt;
if($ackCnt != 0){
$pid = $packet->pid();
if($pid == RakNetInfo::ACK && isset($this->maxACKsAllowed[$id])){
$this->maxACKsAllowed[$id] = $acks - $ackCnt;
}else if($pid == RakNetInfo::NACK && isset($this->maxNACKsAllowed[$id])){
$this->maxNACKsAllowed[$id] = $nacks - $ackCnt;
}
}
$packet->ip = $source;
$packet->port = $port;
@ -69,7 +100,12 @@ class MinecraftInterface{
$c = $server->clients[$CID] ?? false;
if($c !== false){
$username = $c->iusername == "" ? $id : $c->iusername;
ConsoleAPI::warn("Player '$username' sent too many ACK packets (allowed: {$acks}, attempted {$ackCnt} or more)!");
if($nackCnt > 0){
ConsoleAPI::warn("Player '$username' sent too many NACK packets (allowed: {$nacks}, attempted {$ackCnt} or more)!");
}else{
ConsoleAPI::warn("Player '$username' sent too many ACK packets (allowed: {$acks}, attempted {$ackCnt} or more)!");
}
$c->close("too many ack packets");
}else{
//ConsoleAPI::warn("$id sent too many ACK packets (allowed: {$acks}, attempted {$ackCnt} or more)!");
@ -102,8 +138,31 @@ class MinecraftInterface{
RakNetCodec::encode($packet);
if($packet->pid() >= RakNetInfo::DATA_PACKET_0 && $packet->pid() <= RakNetInfo::DATA_PACKET_F && $packet->incrementAllowedAck){
$id = "{$packet->ip}:{$packet->port}";
$seq = $this->maxRecordedSeq[$id] ?? false;
$nackIncr = 0;
if($seq === false){
$this->maxRecordedSeq[$id] = $packet->seqNumber;
$nackIncr = 1;
}else{
if($packet->seqNumber > $seq){
$nackIncr = $packet->seqNumber - $seq;
$this->maxRecordedSeq[$id] = $packet->seqNumber;
}else{
$nackIncr = 0;
}
}
//seems like real raknet would never attempt to send more than 1000 nack packets per single packet (CCRakNetSlidingWindow::OnGotPacket)
//raknet also does something if it received more than 50000 packets?
$nackIncr = $nackIncr > 1000 ? 1000 : $nackIncr;
if(isset($this->maxNACKsAllowed[$id])){
$this->maxNACKsAllowed[$id] += $nackIncr;
}else{
$this->maxNACKsAllowed[$id] = $nackIncr;
}
if(isset($this->maxACKsAllowed[$id])){
++$this->maxACKsAllowed[$id];
$this->maxACKsAllowed[$id] += 1;
}else{
$this->maxACKsAllowed[$id] = 1;
}

View file

@ -52,7 +52,7 @@ class UDPSocket{
$c = socket_select($read, $_, $_, 0, (int)($waitTime*1000000));
if($c === false || $c <= 0) return false;
}
return @socket_recvfrom($this->sock, $buf, 65535, 0, $source, $port);
return @socket_recvfrom($this->sock, $buf, 2048, 0, $source, $port); //TODO make it read client's max mtu if exists?
}
public function write($data, $dest, $port){

View file

@ -1,13 +1,13 @@
<?php
class RakNetParser{
public static function parse(&$buffer, $maxACKAllowed = -1, &$ackCnt = 0){
public static function parse(&$buffer, $maxACKAllowed = -1, $maxNACKsAllowed = -1, &$ackCnt = 0, &$nackCnt = 0){
$offset = 0;
++$offset;
$packet = new RakNetPacket(ord(substr($buffer, $offset - 1, 1)));
$packet->buffer = &$buffer;
$packet->length = strlen($buffer);
switch($packet->pid()){
switch($pid = $packet->pid()){
case RakNetInfo::UNCONNECTED_PING:
case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS:
$offset += 8;
@ -56,10 +56,15 @@ class RakNetParser{
}
break;
case RakNetInfo::NACK:
$maxRangeSize = 1000;
$maxACKAllowed = $maxNACKsAllowed;
goto handle_ack;
case RakNetInfo::ACK:
$maxRangeSize = -1;
handle_ack:
$offset += 2;
$count = Utils::readShort(substr($buffer, $offset - 2, 2), false);
$packet->packets = [];
$packet->packets = new RangeList();
$acks = 0;
for($i = 0; $i < $count && isset($buffer[$offset]); ++$i){
++$offset;
@ -68,34 +73,36 @@ class RakNetParser{
$start = Utils::readTriad(strrev(substr($buffer, $offset - 3, 3)));
$offset += 3;
$end = Utils::readTriad(strrev(substr($buffer, $offset - 3, 3)));
$acks += ($end - $start)+1;
if($acks <= 0 || $maxACKAllowed >= 0 && ($maxACKAllowed - $acks) < 0){
$range = ($end - $start)+1;
if($range <= 0 || ($maxRangeSize >= 0 && $range > $maxRangeSize)){
$packet = false;
break;
}
/*if(($end - $start) > 4096){ //not really needed?
$end = $start + 4096;
}*/
for($c = $start; $c <= $end; ++$c){
$packet->packets[] = $c;
$acks += $range;
if($acks <= 0 || ($maxACKAllowed >= 0 && ($maxACKAllowed - $acks) < 0)){
$packet = false;
break;
}
$packet->packets->addRange($start, $end);
}else{
$offset += 3;
$acks += 1;
if($maxACKAllowed >= 0 && ($maxACKAllowed - $acks) < 0){
if(($maxACKAllowed >= 0 && ($maxACKAllowed - $acks) < 0)){
$packet = false;
break;
}
$packet->packets[] = Utils::readTriad(strrev(substr($buffer, $offset - 3, 3)));
$packet->packets->add(Utils::readTriad(strrev(substr($buffer, $offset - 3, 3))));
}
}
$ackCnt = $acks;
if($pid == RakNetInfo::NACK) $nackCnt = $acks;
break;
default:
$packet = false;
break;
}
//console("recv $ackCnt n $nackCnt");
return $packet;
}

25
src/utils/RangeList.php Normal file
View file

@ -0,0 +1,25 @@
<?php
class RangeList implements IteratorAggregate
{
public $sequences = [];
public function addRange($start, $finish){
$this->sequences[$start] = $finish;
}
public function add($start){
$this->sequences[$start] = $start;
}
#[ReturnTypeWillChange]
public function getIterator(){
return function(){
foreach($this->sequences as $start => $end){
for($s = $start; $s <= $end; ++$s){
yield $s;
}
}
};
}
}