forked from NetherGamesMC/libproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProxyServer.php
310 lines (260 loc) · 10.9 KB
/
ProxyServer.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
<?php
declare(strict_types=1);
namespace libproxy;
use ErrorException;
use libproxy\protocol\DisconnectPacket;
use libproxy\protocol\ForwardPacket;
use libproxy\protocol\LoginPacket;
use libproxy\protocol\ProxyPacket;
use libproxy\protocol\ProxyPacketPool;
use libproxy\protocol\ProxyPacketSerializer;
use pocketmine\network\mcpe\raklib\PthreadsChannelReader;
use pocketmine\network\mcpe\raklib\SnoozeAwarePthreadsChannelWriter;
use pocketmine\network\PacketHandlingException;
use pocketmine\snooze\SleeperNotifier;
use pocketmine\utils\Binary;
use pocketmine\utils\BinaryDataException;
use pocketmine\utils\TextFormat;
use pocketmine\utils\Utils;
use Socket;
use Threaded;
use ThreadedLogger;
use function count;
use function min;
use function socket_accept;
use function socket_close;
use function socket_getpeername;
use function socket_last_error;
use function socket_read;
use function socket_recv;
use function socket_select;
use function socket_shutdown;
use function socket_strerror;
use function socket_write;
use function strlen;
class ProxyServer
{
private const SERVER_SOCKET = -1;
private const NOTIFY_SOCKET = -2;
private const MAX_FRAME_LENGTH = 65535;
private const LENGTH_NEEDED = 0;
private const BUFFER = 1;
/** @var ThreadedLogger */
private ThreadedLogger $logger;
/** @var PthreadsChannelReader */
private PthreadsChannelReader $mainToThreadReader;
/** @var SnoozeAwarePthreadsChannelWriter */
private SnoozeAwarePthreadsChannelWriter $threadToMainWriter;
/** @var Socket */
private Socket $serverSocket;
/** @var Socket */
private Socket $notifySocket;
/** @var Socket[] */
private array $sockets = [];
/** @phpstan-var array<int, array<int|string>> */
private array $socketBuffer = [];
/** @var int */
private int $socketId = 0;
public function __construct(ThreadedLogger $logger, Socket $serverSocket, Threaded $mainToThreadBuffer, Threaded $threadToMainBuffer, SleeperNotifier $notifier, Socket $notifySocket)
{
$this->logger = $logger;
$this->serverSocket = $serverSocket;
$this->notifySocket = $notifySocket;
$this->mainToThreadReader = new PthreadsChannelReader($mainToThreadBuffer);
$this->threadToMainWriter = new SnoozeAwarePthreadsChannelWriter($threadToMainBuffer, $notifier);
}
public function waitShutdown(): void
{
foreach ($this->sockets as $socketId => $socket) {
$this->closeSocket($socketId, "server shutdown");
}
while (count($this->sockets) > 0) {
$this->tickProcessor();
}
@socket_close($this->serverSocket);
@socket_close($this->notifySocket);
}
private function closeSocket(int $socketId, string $reason = TextFormat::EOL): void
{
if (($socket = $this->getSocket($socketId)) !== null) {
try {
socket_shutdown($socket);
} catch (ErrorException $exception) {
$this->logger->debug('Socket is not connected anymore.');
}
socket_close($socket);
unset($this->sockets[$socketId], $this->socketBuffer[$socketId]);
}
$this->logger->debug("Disconnected socket with id " . $socketId);
if ($reason !== TextFormat::EOL) {
$pk = new DisconnectPacket();
$pk->reason = $reason;
$this->putPacket($socketId, $pk);
}
}
public function getSocket(int $socketId): ?Socket
{
return $this->sockets[$socketId] ?? null;
}
private function putPacket(int $socketId, ProxyPacket $pk): void
{
$serializer = new ProxyPacketSerializer();
$serializer->putLInt($socketId);
$pk->encode($serializer);
$this->threadToMainWriter->write($serializer->getBuffer());
}
public function tickProcessor(): void
{
$read = $this->sockets;
$read[self::SERVER_SOCKET] = $this->serverSocket;
$read[self::NOTIFY_SOCKET] = $this->notifySocket;
$write = null;
$except = null;
$select = socket_select($read, $write, $except, 5);
if ($select !== false && $select > 0) {
foreach ($read as $socketId => $socket) {
/** @var int $socketId */
if ($socketId === self::NOTIFY_SOCKET) {
socket_read($socket, self::MAX_FRAME_LENGTH); //clean socket
$this->pushSockets();
} elseif ($socketId === self::SERVER_SOCKET) {
$this->onServerSocketReceive();
} else {
$this->onSocketReceive($socketId);
}
}
}
}
private function pushSockets(): void
{
while (($payload = $this->mainToThreadReader->read()) !== null) {
$stream = new ProxyPacketSerializer($payload);
$socketId = $stream->getLInt();
if (($pk = ProxyPacketPool::getInstance()->getPacket($payload, $stream->getOffset())) === null) {
throw new PacketHandlingException('Packet does not exist');
}
try {
$pk->decode($stream);
} catch (BinaryDataException $e) {
$this->logger->debug('Closed socket with id(' . $socketId . ') because packet was invalid.');
$this->closeSocket($socketId, 'Invalid Packet');
return;
}
try {
switch ($pk->pid()) {
case DisconnectPacket::NETWORK_ID:
/** @var DisconnectPacket $pk */
if ($this->getSocket($socketId) !== null) {
$this->closeSocket($socketId);
}
break;
case ForwardPacket::NETWORK_ID:
/** @var ForwardPacket $pk */
if (($socket = $this->getSocket($socketId)) === null) {
throw new PacketHandlingException('Socket with id (' . $socketId . ") doesn't exist.");
}
try {
if (socket_write($socket, Binary::writeInt(strlen($pk->payload)) . $pk->payload) === false) {
throw new PacketHandlingException('Socket with id (' . $socketId . ") isn't writable.");
}
} catch (ErrorException $exception) {
throw PacketHandlingException::wrap($exception, 'Socket with id (' . $socketId . ") isn't writable.");
}
break;
}
} catch (PacketHandlingException $exception) {
$this->closeSocket($socketId, 'Error handling a Packet');
}
}
}
private function onServerSocketReceive(): void
{
$socket = socket_accept($this->serverSocket);
if ($socket === false) {
$this->logger->debug("Couldn't accept new socket request: " . socket_strerror(socket_last_error($this->serverSocket)));
} else {
try {
if (socket_getpeername($socket, $ip, $port)) {
$this->sockets[$socketId = $this->socketId++] = $socket;
$this->logger->debug('Socket(' . $socketId . ') created a session from ' . $ip . ':' . $port);
socket_set_option($socket, SOL_SOCKET, SO_LINGER, ["l_onoff" => 1, "l_linger" => 0]);
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, ["sec" => 4, "usec" => 0]);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ["sec" => 4, "usec" => 0]);
$pk = new LoginPacket();
$pk->ip = $ip;
$pk->port = $port;
$this->putPacket($socketId, $pk);
} else {
$this->logger->debug('New socket request already disconnected: ' . socket_strerror(socket_last_error($this->serverSocket)));
}
} catch (ErrorException $exception) {
$this->logger->debug('New socket request already disconnected: ' . socket_strerror(socket_last_error($this->serverSocket)));
}
}
}
private function onSocketReceive(int $socketId): void
{
if (isset($this->socketBuffer[$socketId])) {
/** @var int $length */
/** @var string $buffer */
[$length, $buffer] = $this->socketBuffer[$socketId];
$rawFrameData = $this->get($socketId, $length, $buffer);
} elseif (($rawFrameLength = $this->get($socketId, 4)) !== null) {
if ($rawFrameLength === '') {
return; // frame is incomplete
}
try {
$packetLength = Binary::readInt($rawFrameLength);
} catch (BinaryDataException $exception) {
$this->closeSocket($socketId, 'Not enough bytes to read');
$this->logger->logException($exception);
return;
}
$rawFrameData = $this->get($socketId, $packetLength);
} else {
$this->closeSocket($socketId, 'Invalid frame length');
$this->logger->debug('Socket(' . $socketId . ') returned invalid frame data length');
return;
}
if ($rawFrameData === '') {
return; //frame is incomplete;
}
if ($rawFrameData === null) {
$this->closeSocket($socketId, 'Invalid frame length');
$this->logger->debug('Socket(' . $socketId . ') returned invalid frame data');
} else {
unset($this->socketBuffer[$socketId]);
$pk = new ForwardPacket();
$pk->payload = $rawFrameData;
$this->putPacket($socketId, $pk);
}
}
private function get(int $socketId, int $remainingLength, string $previousBuffer = ''): ?string
{
/** @var Socket $socket */
$socket = $this->getSocket($socketId);
try {
$length = min(self::MAX_FRAME_LENGTH, $remainingLength);
if (Utils::getOS() === Utils::OS_WINDOWS) {
// Honestly I do not think this is a problem since we are not going to deploy
// windows as our "production" nodes.
$receivedLength = socket_recv($socket, $buffer, $length, MSG_WAITALL);
} else {
$receivedLength = socket_recv($socket, $buffer, $length, MSG_DONTWAIT);
}
if ($receivedLength === false) {
return null;
}
if ($receivedLength === $remainingLength) {
return $previousBuffer . $buffer;
}
$this->socketBuffer[$socketId] = [
self::LENGTH_NEEDED => $remainingLength - $receivedLength,
self::BUFFER => $previousBuffer . $buffer,
];
return '';
} catch (ErrorException $exception) {
return null;
}
}
}