forked from pmmp/RconServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RconThread.php
242 lines (217 loc) · 7.05 KB
/
RconThread.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
<?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 pmmp\RconServer;
use pocketmine\snooze\SleeperHandlerEntry;
use pocketmine\thread\log\ThreadSafeLogger;
use pocketmine\thread\Thread;
use pocketmine\utils\Binary;
use function count;
use function ltrim;
use function microtime;
use function socket_accept;
use function socket_close;
use function socket_getpeername;
use function socket_last_error;
use function socket_read;
use function socket_select;
use function socket_set_block;
use function socket_set_nonblock;
use function socket_set_option;
use function socket_shutdown;
use function socket_strerror;
use function socket_write;
use function str_replace;
use function strlen;
use function substr;
use function trim;
use const SO_KEEPALIVE;
use const SO_LINGER;
use const SOCKET_ECONNRESET;
use const SOL_SOCKET;
class RconThread extends Thread{
public string $cmd = "";
public string $response = "";
private bool $stop = false;
public function __construct(
private \Socket $socket,
private string $password,
private int $maxClients,
private ThreadSafeLogger $logger,
private \Socket $ipcSocket,
private SleeperHandlerEntry $sleeperEntry
){}
private function writePacket(\Socket $client, int $requestID, int $packetType, string $payload) : void{
$pk = Binary::writeLInt($requestID)
. Binary::writeLInt($packetType)
. $payload
. "\x00\x00"; //Terminate payload and packet
socket_write($client, Binary::writeLInt(strlen($pk)) . $pk);
}
private function readPacket(\Socket $client, ?int &$requestID, ?int &$packetType, ?string &$payload) : bool{
$d = @socket_read($client, 4);
socket_getpeername($client, $ip, $port);
if($d === false){
$err = socket_last_error($client);
if($err !== SOCKET_ECONNRESET){
$this->logger->debug("Connection error with $ip $port: " . trim(socket_strerror($err)));
}
return false;
}
if(strlen($d) !== 4){
if($d !== ""){ //empty data is returned on disconnection
$this->logger->debug("Truncated packet from $ip $port (want 4 bytes, have " . strlen($d) . "), disconnecting");
}
return false;
}
$size = Binary::readLInt($d);
if($size < 0 or $size > 65535){
$this->logger->debug("Packet with too-large length header $size from $ip $port, disconnecting");
return false;
}
$buf = @socket_read($client, $size);
if($buf === false){
$err = socket_last_error($client);
if($err !== SOCKET_ECONNRESET){
$this->logger->debug("Connection error with $ip $port: " . trim(socket_strerror($err)));
}
return false;
}
if(strlen($buf) !== $size){
$this->logger->debug("Truncated packet from $ip $port (want $size bytes, have " . strlen($buf) . "), disconnecting");
return false;
}
$requestID = Binary::readLInt(substr($buf, 0, 4));
$packetType = Binary::readLInt(substr($buf, 4, 4));
$payload = substr($buf, 8, -2); //Strip two null bytes
return true;
}
public function close() : void{
$this->stop = true;
}
protected function onRun() : void{
/** @var \Socket[] $clients */
$clients = [];
/** @var bool[] $authenticated */
$authenticated = [];
/** @var float[] $timeouts */
$timeouts = [];
/** @var int $nextClientId */
$nextClientId = 0;
$notifier = $this->sleeperEntry->createNotifier();
while(!$this->stop){
$r = $clients;
$r["main"] = $this->socket; //this is ugly, but we need to be able to mass-select()
$r["ipc"] = $this->ipcSocket;
$w = null;
$e = null;
$disconnect = [];
if(socket_select($r, $w, $e, 5, 0) > 0){
foreach($r as $id => $sock){
if($sock === $this->socket){
if(($client = socket_accept($this->socket)) !== false){
if(count($clients) >= $this->maxClients){
@socket_close($client);
}else{
socket_set_nonblock($client);
socket_set_option($client, SOL_SOCKET, SO_KEEPALIVE, 1);
$id = $nextClientId++;
$clients[$id] = $client;
$authenticated[$id] = false;
$timeouts[$id] = microtime(true) + 5;
}
}
}elseif($sock === $this->ipcSocket){
//read dummy data
socket_read($sock, 65535);
}else{
$p = $this->readPacket($sock, $requestID, $packetType, $payload);
if($p === false){
$disconnect[$id] = $sock;
continue;
}
switch($packetType){
case 3: //Login
if($authenticated[$id]){
$disconnect[$id] = $sock;
break;
}
socket_getpeername($sock, $addr, $port);
if($addr !== "127.0.0.1"){
$disconnect[$id] = $sock;
$this->writePacket($sock, -1, 2, "");
$this->logger->info("Unsuccessful connection from: /$addr:$port (unauthorised ip address)");
}elseif($payload === $this->password){
$this->logger->info("Successful Rcon connection from: /$addr:$port");
$this->writePacket($sock, $requestID, 2, "");
$authenticated[$id] = true;
}else{
$disconnect[$id] = $sock;
$this->writePacket($sock, -1, 2, "");
$this->logger->info("Unsuccessful connection from: /$addr:$port (wrong password)");
}
break;
case 2: //Command
if(!$authenticated[$id]){
$disconnect[$id] = $sock;
break;
}
if($payload !== ""){
$this->cmd = ltrim($payload);
$this->synchronized(function() use ($notifier) : void{
$notifier->wakeupSleeper();
$this->wait();
});
$this->writePacket($sock, $requestID, 0, str_replace("\n", "\r\n", trim($this->response)));
$this->response = "";
$this->cmd = "";
}
break;
}
}
}
}
foreach($authenticated as $id => $status){
if(!isset($disconnect[$id]) and !$authenticated[$id] and $timeouts[$id] < microtime(true)){ //Timeout
$disconnect[$id] = $clients[$id];
}
}
foreach($disconnect as $id => $client){
$this->disconnectClient($client);
unset($clients[$id], $authenticated[$id], $timeouts[$id]);
}
}
foreach($clients as $client){
$this->disconnectClient($client);
}
}
private function disconnectClient(\Socket $client) : void{
socket_getpeername($client, $ip, $port);
@socket_set_option($client, SOL_SOCKET, SO_LINGER, ["l_onoff" => 1, "l_linger" => 1]);
@socket_shutdown($client, 2);
@socket_set_block($client);
@socket_read($client, 1);
@socket_close($client);
$this->logger->info("Disconnected client: /$ip:$port");
}
public function getThreadName() : string{
return "RCON";
}
}