use 2 separate counters for nack and ack packets, chunk resends will happen every 2 seconds instead of 1

This commit is contained in:
GameHerobrine 2026-11-02 02:26:18 +03:00
parent f12315bd3f
commit f377361ff0
6 changed files with 148 additions and 63 deletions

View file

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

View file

@ -488,6 +488,7 @@ class Player{
$pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$pk->data[] = $packet; $pk->data[] = $packet;
$pk->seqNumber = $this->counter[0]++; $pk->seqNumber = $this->counter[0]++;
//$this->counter[0] += 5000;
$pk->sendtime = microtime(true); $pk->sendtime = microtime(true);
if($recover !== false){ if($recover !== false){
$this->recoveryQueue[$pk->seqNumber] = $pk; $this->recoveryQueue[$pk->seqNumber] = $pk;
@ -533,18 +534,17 @@ class Player{
if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return false; if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return false;
if(!$this->convertToLocalEIDPacket($packet)) 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(); $packet->encode();
$len = strlen($packet->buffer) + 1; $len = strlen($packet->buffer) + 1;
$MTU = $this->MTU - 24; $MTU = $this->MTU - 24;
if($len > $MTU){ if($len > $MTU){
return $this->sendBigPacketAlwaysRecover($packet); //TODO fix return $this->sendBigPacketAlwaysRecover($packet); //TODO fix
} }
++$this->counter[0]; //sendBigPacketAlwaysRecover increments this counter which results in server not sending a seq number
$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->messageIndex = $this->counter[3]++;
$packet->reliability = RakNetInfo::RELIABILITY_RELIABLE; $packet->reliability = RakNetInfo::RELIABILITY_RELIABLE;
@ -1580,6 +1580,11 @@ class Player{
} }
public function handlePacketQueues(){ 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 if($this->server->ticks % 40 == 0){ //2s
$this->sendPing(); $this->sendPing();
} }
@ -1709,7 +1714,7 @@ class Player{
} }
foreach($this->packetAlwaysRecoverQueue as $cnt => $data){ 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){ if($time - $data->sendtime >= $maxDelay){
$this->resendQueue[$cnt] = $data; $this->resendQueue[$cnt] = $data;
} }
@ -1724,7 +1729,6 @@ class Player{
$this->lag[] = $time - $data->sendtime; $this->lag[] = $time - $data->sendtime;
$data->sendtime = $time; $data->sendtime = $time;
$this->send($data); $this->send($data);
$data->incrementAllowedAck = true;
} }
} }
} }
@ -2028,9 +2032,7 @@ class Player{
} }
public function __destruct(){ //pwease dont leak memory >_< public function __destruct(){ //pwease dont leak memory >_<
$id = "{$this->ip}:{$this->port}"; $this->server->interface->clear($this->ip, $this->port);
unset($this->server->interface->maxACKsAllowed[$id]);
unset($this->server->interface->maxRecordedSeq[$id]);
} }
public function save(){ public function save(){
@ -2104,7 +2106,6 @@ class Player{
} }
public function entityTick(){ public function entityTick(){
if($this->isSleeping) ++$this->sleepingTime; if($this->isSleeping) ++$this->sleepingTime;
if($this->server->difficulty == 0 && $this->entity->counter % (20 * 15) == 0){ if($this->server->difficulty == 0 && $this->entity->counter % (20 * 15) == 0){
if($this->entity->health < 20 && $this->entity->health > 0){ if($this->entity->health < 20 && $this->entity->health > 0){
@ -2200,6 +2201,7 @@ class Player{
$this->close("Incorrect protocol #" . $packet->protocol1, false); $this->close("Incorrect protocol #" . $packet->protocol1, false);
return; return;
} }
if(preg_match('#[^a-zA-Z0-9_]#', $this->username) > 0 || $this->username === "" || isset(Player::$blacklistedUsernames[$this->iusername]) || strlen($this->iusername) > 16){ 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); $this->close("Bad username", false);
return; return;
@ -3572,41 +3574,44 @@ class Player{
return true; return true;
} }
public $maxRecvPacketSeq = 0;
public function handlePacket(RakNetPacket $packet){ public function handlePacket(RakNetPacket $packet){
if($this->connected === true){ if($this->connected === true){
$time = microtime(true); $time = microtime(true);
$this->timeout = $time + 20; $this->timeout = $time + 20;
switch($packet->pid()){ switch($packet->pid()){
case RakNetInfo::NACK: case RakNetInfo::NACK:
foreach($packet->packets as $count){ foreach($packet->packets->sequences as $start => $end){
if(isset($this->packetAlwaysRecoverQueue[$count])){ for($count = $start; $count <= $end; ++$count){
$this->resendQueue[$count] = $this->packetAlwaysRecoverQueue[$count]; if(isset($this->packetAlwaysRecoverQueue[$count])){
$this->resendQueue[$count]->incrementAllowedAck = false; $this->resendQueue[$count] = $this->packetAlwaysRecoverQueue[$count];
}else if(isset($this->recoveryQueue[$count])){ }else if(isset($this->recoveryQueue[$count])){
$this->resendQueue[$count] = $this->recoveryQueue[$count]; $this->resendQueue[$count] = $this->recoveryQueue[$count];
$this->resendQueue[$count]->incrementAllowedAck = false; $this->lag[] = $time - $this->recoveryQueue[$count]->sendtime;
$this->lag[] = $time - $this->recoveryQueue[$count]->sendtime; unset($this->recoveryQueue[$count]);
unset($this->recoveryQueue[$count]); }else{ //lost and wont be recovered
}else{ //lost and wont be recovered ++$this->packetStats[1];
++$this->packetStats[1]; }
} }
} }
break; break;
case RakNetInfo::ACK: case RakNetInfo::ACK:
//if(mt_rand(0, 99) > 50) break; //if(mt_rand(0, 99) > 50) break;
foreach($packet->packets as $count){ foreach($packet->packets->sequences as $start => $end){
if(isset($this->packetAlwaysRecoverQueue[$count])){ for($count = $start; $count <= $end; ++$count){
$this->lag[] = $time - $this->packetAlwaysRecoverQueue[$count]->sendtime; 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->packetAlwaysRecoverQueue[$count]);
unset($this->chunkCount[$count]); unset($this->chunkCount[$count]);
}else if(isset($this->recoveryQueue[$count])){
$this->lag[] = $time - $this->recoveryQueue[$count]->sendtime; unset($this->resendQueue[$count]);
unset($this->recoveryQueue[$count]); ++$this->packetStats[0];
} }
unset($this->resendQueue[$count]);
++$this->packetStats[0];
} }
break; break;
@ -3627,6 +3632,19 @@ class Player{
case RakNetInfo::DATA_PACKET_E: case RakNetInfo::DATA_PACKET_E:
case RakNetInfo::DATA_PACKET_F: case RakNetInfo::DATA_PACKET_F:
$this->ackQueue[] = $packet->seqNumber; $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] = []; $this->receiveQueue[$packet->seqNumber] = [];
foreach($packet->data as $pk){ foreach($packet->data as $pk){
$this->receiveQueue[$packet->seqNumber][] = $pk; $this->receiveQueue[$packet->seqNumber][] = $pk;

View file

@ -36,15 +36,27 @@ class MinecraftInterface{
ServerAPI::request()->api->dhandle("mcinterface.read", ["buffer" => $buf, "source" => $source, "port" => $port]); ServerAPI::request()->api->dhandle("mcinterface.read", ["buffer" => $buf, "source" => $source, "port" => $port]);
return $this->parsePacket($buf, $source, $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]);
}
/** /**
* Stores max ACK packets that the server is allowed to handle. * Max ACK packets the client is allowed to send
*
* @var array * @var array
*/ */
public $maxACKsAllowed = []; public $maxACKsAllowed = [];
/** /**
* Stores max packet seq number. Used to determine allowed ack increment per packet * 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 * @var array
*/ */
@ -56,12 +68,18 @@ class MinecraftInterface{
if(RakNetInfo::isValid($pid)){ if(RakNetInfo::isValid($pid)){
$id = "$source:$port"; $id = "$source:$port";
$ackCnt = 0; $ackCnt = 0;
$nackCnt = 0;
$acks = $this->maxACKsAllowed[$id] ?? 0; $acks = $this->maxACKsAllowed[$id] ?? 0;
$nacks = $this->maxNACKsAllowed[$id] ?? 0;
$packet = RakNetParser::parse($buffer, $acks, $ackCnt); $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($packet !== false){
if($ackCnt != 0 && isset($this->maxACKsAllowed[$id]) && $packet->pid() != RakNetInfo::NACK){ if($ackCnt != 0){
$this->maxACKsAllowed[$id] = $acks - $ackCnt; $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->ip = $source;
$packet->port = $port; $packet->port = $port;
@ -75,7 +93,12 @@ class MinecraftInterface{
$c = $server->clients[$CID] ?? false; $c = $server->clients[$CID] ?? false;
if($c !== false){ if($c !== false){
$username = $c->iusername == "" ? $id : $c->iusername; $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"); $c->close("too many ack packets");
}else{ }else{
//ConsoleAPI::warn("$id sent too many ACK packets (allowed: {$acks}, attempted {$ackCnt} or more)!"); //ConsoleAPI::warn("$id sent too many ACK packets (allowed: {$acks}, attempted {$ackCnt} or more)!");
@ -109,21 +132,32 @@ class MinecraftInterface{
if($packet->pid() >= RakNetInfo::DATA_PACKET_0 && $packet->pid() <= RakNetInfo::DATA_PACKET_F && $packet->incrementAllowedAck){ if($packet->pid() >= RakNetInfo::DATA_PACKET_0 && $packet->pid() <= RakNetInfo::DATA_PACKET_F && $packet->incrementAllowedAck){
$id = "{$packet->ip}:{$packet->port}"; $id = "{$packet->ip}:{$packet->port}";
$seq = $this->maxRecordedSeq[$id] ?? false; $seq = $this->maxRecordedSeq[$id] ?? false;
$incr = 1; $nackIncr = 0;
if($seq === false){ if($seq === false){
$this->maxRecordedSeq[$id] = $packet->seqNumber; $this->maxRecordedSeq[$id] = $packet->seqNumber;
$nackIncr = 1;
}else{ }else{
if($packet->seqNumber > $seq){ if($packet->seqNumber > $seq){
$incr = $packet->seqNumber - $seq; $nackIncr = $packet->seqNumber - $seq;
$this->maxRecordedSeq[$id] = $packet->seqNumber; $this->maxRecordedSeq[$id] = $packet->seqNumber;
}else{
$nackIncr = 0;
} }
} }
if($incr != 1) console("ack incr: $incr");
//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])){ if(isset($this->maxACKsAllowed[$id])){
$this->maxACKsAllowed[$id] += $incr; $this->maxACKsAllowed[$id] += 1;
}else{ }else{
$this->maxACKsAllowed[$id] = $incr; $this->maxACKsAllowed[$id] = 1;
} }
} }
} }

View file

@ -52,7 +52,7 @@ class UDPSocket{
$c = socket_select($read, $_, $_, 0, (int)($waitTime*1000000)); $c = socket_select($read, $_, $_, 0, (int)($waitTime*1000000));
if($c === false || $c <= 0) return false; 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){ public function write($data, $dest, $port){

View file

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