-
Notifications
You must be signed in to change notification settings - Fork 37
/
Server.php
443 lines (366 loc) · 12 KB
/
Server.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
<?php
/*
* RakLib network library
*
*
* This project is not affiliated with Jenkins Software LLC nor RakNet.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
*/
declare(strict_types=1);
namespace raklib\server;
use pocketmine\utils\BinaryDataException;
use raklib\generic\Socket;
use raklib\generic\SocketException;
use raklib\protocol\ACK;
use raklib\protocol\Datagram;
use raklib\protocol\EncapsulatedPacket;
use raklib\protocol\NACK;
use raklib\protocol\Packet;
use raklib\protocol\PacketSerializer;
use raklib\utils\ExceptionTraceCleaner;
use raklib\utils\InternetAddress;
use function asort;
use function bin2hex;
use function count;
use function get_class;
use function microtime;
use function ord;
use function preg_match;
use function strlen;
use function time;
use function time_sleep_until;
use const PHP_INT_MAX;
use const SOCKET_ECONNRESET;
class Server implements ServerInterface{
private const RAKLIB_TPS = 100;
private const RAKLIB_TIME_PER_TICK = 1 / self::RAKLIB_TPS;
/** @var Socket */
protected $socket;
/** @var \Logger */
protected $logger;
/** @var int */
protected $serverId;
/** @var int */
protected $receiveBytes = 0;
/** @var int */
protected $sendBytes = 0;
/** @var Session[] */
protected $sessionsByAddress = [];
/** @var Session[] */
protected $sessions = [];
/** @var UnconnectedMessageHandler */
protected $unconnectedMessageHandler;
/** @var string */
protected $name = "";
/** @var int */
protected $packetLimit = 200;
/** @var bool */
protected $shutdown = false;
/** @var int */
protected $ticks = 0;
/** @var int[] string (address) => int (unblock time) */
protected $block = [];
/** @var int[] string (address) => int (number of packets) */
protected $ipSec = [];
/** @var string[] regex filters used to block out unwanted raw packets */
protected $rawPacketFilters = [];
/** @var bool */
public $portChecking = false;
/** @var int */
protected $startTimeMS;
/** @var int */
protected $maxMtuSize;
/** @var InternetAddress */
protected $reusableAddress;
/** @var int */
protected $nextSessionId = 0;
/** @var ServerEventSource */
private $eventSource;
/** @var ServerEventListener */
private $eventListener;
/** @var ExceptionTraceCleaner */
private $traceCleaner;
public function __construct(int $serverId, \Logger $logger, Socket $socket, int $maxMtuSize, ProtocolAcceptor $protocolAcceptor, ServerEventSource $eventSource, ServerEventListener $eventListener, ExceptionTraceCleaner $traceCleaner){
$this->serverId = $serverId;
$this->logger = $logger;
$this->socket = $socket;
$this->maxMtuSize = $maxMtuSize;
$this->eventSource = $eventSource;
$this->eventListener = $eventListener;
$this->traceCleaner = $traceCleaner;
$this->startTimeMS = (int) (microtime(true) * 1000);
$this->unconnectedMessageHandler = new UnconnectedMessageHandler($this, $protocolAcceptor);
$this->reusableAddress = clone $this->socket->getBindAddress();
}
/**
* Returns the time in milliseconds since server start.
*/
public function getRakNetTimeMS() : int{
return ((int) (microtime(true) * 1000)) - $this->startTimeMS;
}
public function getPort() : int{
return $this->socket->getBindAddress()->port;
}
public function getMaxMtuSize() : int{
return $this->maxMtuSize;
}
public function getLogger() : \Logger{
return $this->logger;
}
public function tickProcessor() : void{
$start = microtime(true);
/*
* The below code is designed to allow co-op between sending and receiving to avoid slowing down either one
* when high traffic is coming either way. Yielding will occur after 100 messages.
*/
do{
$stream = !$this->shutdown;
for($i = 0; $i < 100 && $stream && !$this->shutdown; ++$i){ //if we received a shutdown event, we don't care about any more messages from the event source
$stream = $this->eventSource->process($this);
}
$socket = true;
for($i = 0; $i < 100 && $socket; ++$i){
$socket = $this->receivePacket();
}
}while($stream || $socket);
$this->tick();
$time = microtime(true) - $start;
if($time < self::RAKLIB_TIME_PER_TICK){
@time_sleep_until(microtime(true) + self::RAKLIB_TIME_PER_TICK - $time);
}
}
/**
* Disconnects all sessions and blocks until everything has been shut down properly.
*/
public function waitShutdown() : void{
$this->shutdown = true;
foreach($this->sessions as $session){
$session->initiateDisconnect("server shutdown");
}
while(count($this->sessions) > 0){
$this->tickProcessor();
}
$this->socket->close();
$this->logger->debug("Graceful shutdown complete");
}
private function tick() : void{
$time = microtime(true);
foreach($this->sessions as $session){
$session->update($time);
if($session->isFullyDisconnected()){
$this->removeSessionInternal($session);
}
}
$this->ipSec = [];
if(!$this->shutdown and ($this->ticks % self::RAKLIB_TPS) === 0){
if($this->sendBytes > 0 or $this->receiveBytes > 0){
$this->eventListener->onBandwidthStatsUpdate($this->sendBytes, $this->receiveBytes);
$this->sendBytes = 0;
$this->receiveBytes = 0;
}
if(count($this->block) > 0){
asort($this->block);
$now = time();
foreach($this->block as $address => $timeout){
if($timeout <= $now){
unset($this->block[$address]);
}else{
break;
}
}
}
}
++$this->ticks;
}
/** @phpstan-impure */
private function receivePacket() : bool{
$address = $this->reusableAddress;
try{
$buffer = $this->socket->readPacket($address->ip, $address->port);
}catch(SocketException $e){
$error = $e->getCode();
if($error === SOCKET_ECONNRESET){ //client disconnected improperly, maybe crash or lost connection
return true;
}
$this->logger->debug($e->getMessage());
return false;
}
if($buffer === null){
return false; //no data
}
$len = strlen($buffer);
$this->receiveBytes += $len;
if(isset($this->block[$address->ip])){
return true;
}
if(isset($this->ipSec[$address->ip])){
if(++$this->ipSec[$address->ip] >= $this->packetLimit){
$this->blockAddress($address->ip);
return true;
}
}else{
$this->ipSec[$address->ip] = 1;
}
if($len < 1){
return true;
}
try{
$session = $this->getSessionByAddress($address);
if($session !== null){
$header = ord($buffer[0]);
if(($header & Datagram::BITFLAG_VALID) !== 0){
if(($header & Datagram::BITFLAG_ACK) !== 0){
$packet = new ACK();
}elseif(($header & Datagram::BITFLAG_NAK) !== 0){
$packet = new NACK();
}else{
$packet = new Datagram();
}
$packet->decode(new PacketSerializer($buffer));
$session->handlePacket($packet);
}else{
$this->logger->debug("Ignored unconnected packet from $address due to session already opened (0x" . bin2hex($buffer[0]) . ")");
}
}elseif(!$this->shutdown){
if(!($handled = $this->unconnectedMessageHandler->handleRaw($buffer, $address))){
foreach($this->rawPacketFilters as $pattern){
if(preg_match($pattern, $buffer) > 0){
$handled = true;
$this->eventListener->onRawPacketReceive($address->ip, $address->port, $buffer);
break;
}
}
}
if(!$handled){
$this->logger->debug("Ignored packet from $address due to no session opened (0x" . bin2hex($buffer[0]) . ")");
}
}
}catch(BinaryDataException $e){
$logFn = function() use ($address, $e, $buffer): void{
$this->logger->debug("Packet from $address (" . strlen($buffer) . " bytes): 0x" . bin2hex($buffer));
$this->logger->debug(get_class($e) . ": " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine());
foreach($this->traceCleaner->getTrace(0, $e->getTrace()) as $line){
$this->logger->debug($line);
}
$this->logger->error("Bad packet from $address: " . $e->getMessage());
};
if($this->logger instanceof \BufferedLogger){
$this->logger->buffer($logFn);
}else{
$logFn();
}
$this->blockAddress($address->ip, 5);
}
return true;
}
public function sendPacket(Packet $packet, InternetAddress $address) : void{
$out = new PacketSerializer(); //TODO: reusable streams to reduce allocations
$packet->encode($out);
try{
$this->sendBytes += $this->socket->writePacket($out->getBuffer(), $address->ip, $address->port);
}catch(SocketException $e){
$this->logger->debug($e->getMessage());
}
}
public function getEventListener() : ServerEventListener{
return $this->eventListener;
}
public function sendEncapsulated(int $sessionId, EncapsulatedPacket $packet, bool $immediate = false) : void{
$session = $this->sessions[$sessionId] ?? null;
if($session !== null and $session->isConnected()){
$session->addEncapsulatedToQueue($packet, $immediate);
}
}
public function sendRaw(string $address, int $port, string $payload) : void{
try{
$this->socket->writePacket($payload, $address, $port);
}catch(SocketException $e){
$this->logger->debug($e->getMessage());
}
}
public function closeSession(int $sessionId) : void{
if(isset($this->sessions[$sessionId])){
$this->sessions[$sessionId]->initiateDisconnect("server disconnect");
}
}
public function setName(string $name) : void{
$this->name = $name;
}
public function setPortCheck(bool $value) : void{
$this->portChecking = $value;
}
public function setPacketsPerTickLimit(int $limit) : void{
$this->packetLimit = $limit;
}
public function blockAddress(string $address, int $timeout = 300) : void{
$final = time() + $timeout;
if(!isset($this->block[$address]) or $timeout === -1){
if($timeout === -1){
$final = PHP_INT_MAX;
}else{
$this->logger->notice("Blocked $address for $timeout seconds");
}
$this->block[$address] = $final;
}elseif($this->block[$address] < $final){
$this->block[$address] = $final;
}
}
public function unblockAddress(string $address) : void{
unset($this->block[$address]);
$this->logger->debug("Unblocked $address");
}
public function addRawPacketFilter(string $regex) : void{
$this->rawPacketFilters[] = $regex;
}
public function getSessionByAddress(InternetAddress $address) : ?Session{
return $this->sessionsByAddress[$address->toString()] ?? null;
}
public function sessionExists(InternetAddress $address) : bool{
return isset($this->sessionsByAddress[$address->toString()]);
}
public function createSession(InternetAddress $address, int $clientId, int $mtuSize) : Session{
$this->checkSessions();
while(isset($this->sessions[$this->nextSessionId])){
$this->nextSessionId++;
$this->nextSessionId &= 0x7fffffff; //we don't expect more than 2 billion simultaneous connections, and this fits in 4 bytes
}
$session = new Session($this, $this->logger, clone $address, $clientId, $mtuSize, $this->nextSessionId);
$this->sessionsByAddress[$address->toString()] = $session;
$this->sessions[$this->nextSessionId] = $session;
$this->logger->debug("Created session for $address with MTU size $mtuSize");
return $session;
}
private function removeSessionInternal(Session $session) : void{
unset($this->sessionsByAddress[$session->getAddress()->toString()], $this->sessions[$session->getInternalId()]);
}
public function openSession(Session $session) : void{
$address = $session->getAddress();
$this->eventListener->onClientConnect($session->getInternalId(), $address->ip, $address->port, $session->getID());
}
private function checkSessions() : void{
if(count($this->sessions) > 4096){
foreach($this->sessions as $sessionId => $session){
if($session->isTemporal()){
$this->removeSessionInternal($session);
if(count($this->sessions) <= 4096){
break;
}
}
}
}
}
public function notifyACK(Session $session, int $identifierACK) : void{
$this->eventListener->onPacketAck($session->getInternalId(), $identifierACK);
}
public function getName() : string{
return $this->name;
}
public function getID() : int{
return $this->serverId;
}
}