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){ if($additional){
$arqCnt = count($p->packetAlwaysRecoverQueue); $arqCnt = count($p->packetAlwaysRecoverQueue);
$rqCnt = count($p->recoveryQueue); $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); $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

@ -83,8 +83,8 @@ class Player{
private $timeout; private $timeout;
private $connected = true; private $connected = true;
private $clientID; private $clientID;
private $ip; public $ip;
private $port; public $port;
private $counter = [0, 0, 0, 0]; private $counter = [0, 0, 0, 0];
public $username; public $username;
public $iusername; public $iusername;
@ -188,6 +188,9 @@ class Player{
*/ */
public function __construct($clientID, $ip, $port, $MTU){ public function __construct($clientID, $ip, $port, $MTU){
$this->bigCnt = 0; $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->MTU = min($MTU, 1100);
$this->server = ServerAPI::request(); $this->server = ServerAPI::request();
$this->lastBreak = microtime(true); $this->lastBreak = microtime(true);
@ -223,7 +226,7 @@ class Player{
$this->chatMessagesQueue->data = []; $this->chatMessagesQueue->data = [];
$this->server->schedule(20 * 60, [$this, "clearQueue"], [], true); $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"]); $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); 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 = 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;
@ -530,11 +534,6 @@ 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;
@ -542,6 +541,11 @@ class Player{
return $this->sendBigPacketAlwaysRecover($packet); //TODO fix 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->messageIndex = $this->counter[3]++;
$packet->reliability = RakNetInfo::RELIABILITY_RELIABLE; $packet->reliability = RakNetInfo::RELIABILITY_RELIABLE;
@ -1576,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();
} }
@ -1705,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;
} }
@ -2023,7 +2032,8 @@ class Player{
} }
public function __destruct(){ //pwease dont leak memory >_< 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(){ public function save(){
@ -2097,7 +2107,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){
@ -2193,6 +2202,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;
@ -3565,42 +3575,45 @@ 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){
for($count = $start; $count <= $end; ++$count){
if(isset($this->packetAlwaysRecoverQueue[$count])){ if(isset($this->packetAlwaysRecoverQueue[$count])){
$this->resendQueue[$count] = $this->packetAlwaysRecoverQueue[$count]; $this->resendQueue[$count] = $this->packetAlwaysRecoverQueue[$count];
$this->resendQueue[$count]->incrementAllowedAck = false;
}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){
for($count = $start; $count <= $end; ++$count){
if(isset($this->packetAlwaysRecoverQueue[$count])){ if(isset($this->packetAlwaysRecoverQueue[$count])){
$this->lag[] = $time - $this->packetAlwaysRecoverQueue[$count]->sendtime; $this->lag[] = $time - $this->packetAlwaysRecoverQueue[$count]->sendtime;
unset($this->packetAlwaysRecoverQueue[$count]);
unset($this->chunkCount[$count]);
}else if(isset($this->recoveryQueue[$count])){ }else if(isset($this->recoveryQueue[$count])){
$this->lag[] = $time - $this->recoveryQueue[$count]->sendtime; $this->lag[] = $time - $this->recoveryQueue[$count]->sendtime;
unset($this->recoveryQueue[$count]);
} }
unset($this->recoveryQueue[$count]);
unset($this->packetAlwaysRecoverQueue[$count]);
unset($this->chunkCount[$count]);
unset($this->resendQueue[$count]); unset($this->resendQueue[$count]);
++$this->packetStats[0]; ++$this->packetStats[0];
} }
}
break; break;
case RakNetInfo::DATA_PACKET_0: case RakNetInfo::DATA_PACKET_0:
@ -3620,6 +3633,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,13 +36,38 @@ 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]);
}
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 * @var array
*/ */
public $maxACKsAllowed = []; 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){ private function parsePacket($buffer, $source, $port){
$pid = ord($buffer[0]); $pid = ord($buffer[0]);
@ -50,12 +75,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){
$pid = $packet->pid();
if($pid == RakNetInfo::ACK && isset($this->maxACKsAllowed[$id])){
$this->maxACKsAllowed[$id] = $acks - $ackCnt; $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;
@ -69,7 +100,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;
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)!"); 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)!");
@ -102,8 +138,31 @@ class MinecraftInterface{
RakNetCodec::encode($packet); RakNetCodec::encode($packet);
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;
$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])){ if(isset($this->maxACKsAllowed[$id])){
++$this->maxACKsAllowed[$id]; $this->maxACKsAllowed[$id] += 1;
}else{ }else{
$this->maxACKsAllowed[$id] = 1; $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;
}
}
};
}
}