-
Notifications
You must be signed in to change notification settings - Fork 6
/
ProxyNetworkInterface.php
336 lines (287 loc) · 12 KB
/
ProxyNetworkInterface.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
<?php
declare(strict_types=1);
namespace libproxy;
use Error;
use Exception;
use libproxy\data\LatencyData;
use libproxy\data\TickSyncPacket;
use libproxy\protocol\AckPacket;
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 pmmp\thread\Thread as NativeThread;
use pmmp\thread\ThreadSafeArray;
use pocketmine\network\mcpe\compression\ZlibCompressor;
use pocketmine\network\mcpe\convert\TypeConverter;
use pocketmine\network\mcpe\EntityEventBroadcaster;
use pocketmine\network\mcpe\NetworkSession;
use pocketmine\network\mcpe\PacketBroadcaster;
use pocketmine\network\mcpe\protocol\PacketPool;
use pocketmine\network\mcpe\raklib\PthreadsChannelReader;
use pocketmine\network\mcpe\raklib\PthreadsChannelWriter;
use pocketmine\network\NetworkInterface;
use pocketmine\network\PacketHandlingException;
use pocketmine\plugin\PluginBase;
use pocketmine\scheduler\ClosureTask;
use pocketmine\Server;
use pocketmine\snooze\SleeperHandlerEntry;
use pocketmine\thread\ThreadCrashException;
use pocketmine\utils\Binary;
use pocketmine\utils\BinaryDataException;
use Socket;
use ThreadedArray;
use WeakMap;
use function base64_encode;
use function bin2hex;
use function socket_close;
use function socket_create_pair;
use function socket_last_error;
use function socket_strerror;
use function socket_write;
use function strlen;
use function substr;
use function trim;
use const AF_INET;
use const AF_UNIX;
use const SOCK_STREAM;
use const SOCKET_ENOPROTOOPT;
use const SOCKET_EPROTONOSUPPORT;
final class ProxyNetworkInterface implements NetworkInterface
{
/** @var WeakMap<NetworkSession, LatencyData> */
public static WeakMap $latencyMap;
/** @var Server */
private Server $server;
/** @var ProxyThread */
private ProxyThread $proxy;
/** @var SleeperHandlerEntry */
private SleeperHandlerEntry $sleeperEntry;
/** @var Socket */
private Socket $threadNotifier;
/** @var PthreadsChannelWriter */
private PthreadsChannelWriter $mainToThreadWriter;
/** @var PthreadsChannelReader */
private PthreadsChannelReader $threadToMainReader;
/** @var PacketBroadcaster */
private PacketBroadcaster $packetBroadcaster;
/** @var EntityEventBroadcaster */
private EntityEventBroadcaster $entityEventBroadcaster;
/** @var int */
private int $receiveBytes = 0;
/** @var int */
private int $sendBytes = 0;
/** @var NetworkSession[] */
private array $sessions = [];
public function __construct(PluginBase $plugin, int $port, ?string $composerPath = null)
{
$server = $plugin->getServer();
$ret = @socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $ipc);
if (!$ret) {
$err = socket_last_error();
if (($err !== SOCKET_EPROTONOSUPPORT && $err !== SOCKET_ENOPROTOOPT) || !@socket_create_pair(AF_INET, SOCK_STREAM, 0, $ipc)) {
throw new Exception('Failed to open IPC socket: ' . trim(socket_strerror(socket_last_error())));
}
}
/** @phpstan-ignore-next-line */
self::$latencyMap = new WeakMap();
/** @var Socket $threadNotifier */
/** @var Socket $threadNotification */
[$threadNotifier, $threadNotification] = $ipc;
$this->threadNotifier = $threadNotifier;
$this->server = $server;
$this->sleeperEntry = $plugin->getServer()->getTickSleeper()->addNotifier(function (): void {
while (($payload = $this->threadToMainReader->read()) !== null) {
$this->onPacketReceive($payload);
}
});
$mainToThreadBuffer = new ThreadSafeArray();
$threadToMainBuffer = new ThreadSafeArray();
$this->proxy = new ProxyThread(
$composerPath,
$server->getIp(),
$port,
$server->getLogger(),
$mainToThreadBuffer,
$threadToMainBuffer,
$this->sleeperEntry,
$threadNotification,
);
$this->mainToThreadWriter = new PthreadsChannelWriter($mainToThreadBuffer);
$this->threadToMainReader = new PthreadsChannelReader($threadToMainBuffer);
$this->packetBroadcaster = PMUtils::getPacketBroadcaster($server);
$this->entityEventBroadcaster = PMUtils::getEntityEventBroadcaster($server);
PacketPool::getInstance()->registerPacket(new TickSyncPacket());
$bandwidthTracker = $plugin->getServer()->getNetwork()->getBandwidthTracker();
$plugin->getScheduler()->scheduleDelayedRepeatingTask(new ClosureTask(function () use ($bandwidthTracker): void {
$bandwidthTracker->add($this->sendBytes, $this->receiveBytes);
$this->sendBytes = 0;
$this->receiveBytes = 0;
}), 20, 20);
}
public static function handleRawLatency(NetworkSession $session, int $upstream, int $downstream): void
{
self::$latencyMap[$session] = $data = new LatencyData($upstream, $downstream);
$session->updatePing($data->getLatency());
}
public static function getLatencyData(NetworkSession $session): ?LatencyData
{
return self::$latencyMap[$session] ?? null;
}
public function start(): void
{
$this->server->getLogger()->debug('Waiting for Proxy to start...');
$this->proxy->startAndWait(NativeThread::INHERIT_CONSTANTS); //HACK: MainLogger needs constants for exception logging
$this->server->getLogger()->debug('Proxy booted successfully');
}
/**
* @throws PacketHandlingException
*/
private function onPacketReceive(string $buffer): void
{
$stream = new ProxyPacketSerializer($buffer);
$socketId = $stream->getLInt();
if (($pk = ProxyPacketPool::getInstance()->getPacket($buffer, $stream->getOffset())) === null) {
$offset = 0;
throw new PacketHandlingException('Proxy packet with id (' . Binary::readUnsignedVarInt($buffer, $offset) . ') does not exist');
}
try {
$pk->decode($stream);
} catch (BinaryDataException $e) {
$this->server->getLogger()->debug('Closed socket with id(' . $socketId . ') because packet was invalid.');
$this->close($socketId, 'Invalid Packet');
return;
}
if (!$stream->feof()) {
$remains = substr($stream->getBuffer(), $stream->getOffset());
$this->server->getLogger()->debug('Still ' . strlen($remains) . ' bytes unread in ' . $pk->pid() . ': ' . bin2hex($remains));
}
try {
switch ($pk->pid()) {
case LoginPacket::NETWORK_ID:
/** @var LoginPacket $pk */
if ($this->getSession($socketId) === null) {
$this->createSession($socketId, $pk->ip, $pk->port);
} else {
throw new PacketHandlingException('Socket with id (' . $socketId . ') already has a session.');
}
break;
case DisconnectPacket::NETWORK_ID:
/** @var DisconnectPacket $pk */
if ($this->getSession($socketId) === null) {
break;
}
$this->close($socketId, $pk->reason, true);
break;
case ForwardPacket::NETWORK_ID:
/** @var ForwardPacket $pk */
if (($session = $this->getSession($socketId)) === null || !(fn() => $this->connected)->call($session)) {
break; // might be data arriving from the client after the server has closed the connection
}
$packet = PacketPool::getInstance()->getPacket($pk->payload);
if ($packet === null) {
$session->getLogger()->debug("Unknown packet: " . base64_encode($pk->payload));
throw new PacketHandlingException("Unknown packet received");
}
try {
$session->handleDataPacket($packet, $pk->payload);
} catch (PacketHandlingException $e) {
$session->getLogger()->debug($packet->getName() . ": " . base64_encode($pk->payload));
throw PacketHandlingException::wrap($e, "Error processing " . $packet->getName());
}
$this->receiveBytes += strlen($pk->payload);
break;
case AckPacket::NETWORK_ID:
/** @var AckPacket $pk */
if (($session = $this->getSession($socketId)) === null || !(fn() => $this->connected)->call($session)) {
break; // might be data arriving from the client after the server has closed the connection
}
$session->handleAckReceipt($pk->receiptId);
break;
}
} catch (PacketHandlingException|BinaryDataException $exception) {
$this->close($socketId, 'Error handling a Packet (Server)');
$this->server->getLogger()->logException($exception);
}
}
public function tick(): void
{
if (!$this->proxy->isRunning()) {
$e = $this->proxy->getCrashInfo();
if ($e !== null) {
throw new ThreadCrashException("Proxy crashed", $e);
}
throw new \Exception("Proxy Thread crashed without crash information");
}
}
public function close(int $socketId, string $reason, bool $fromThread = false, bool $kicked = false): void
{
static $disconnectGuard = false;
if ($disconnectGuard) {
return;
}
$session = $this->getSession($socketId);
unset($this->sessions[$socketId]);
if (!$kicked && $session !== null) {
/**
* {@link NetworkSession::tryDisconnect()} is calling the current method when calls {@link ProxyPacketSender::close()}
*/
$disconnectGuard = true;
$session->onClientDisconnect($reason);
$disconnectGuard = false;
}
if (!$fromThread) {
$pk = new DisconnectPacket();
$pk->reason = $reason;
$this->putPacket($socketId, $pk);
}
}
public function getSession(int $socketId): ?NetworkSession
{
return $this->sessions[$socketId] ?? null;
}
public function putPacket(int $socketId, ProxyPacket $pk): void
{
$serializer = new ProxyPacketSerializer();
$serializer->putLInt($socketId);
$pk->encode($serializer);
$this->mainToThreadWriter->write($serializer->getBuffer());
$this->sendBytes += strlen($serializer->getBuffer());
try {
socket_write($this->threadNotifier, "\x00"); // wakes up the socket_select function
} catch (Error $exception) {
$this->server->getLogger()->debug('Packet was send while the client was already shut down');
}
}
public function createSession(int $socketId, string $ip, int $port): NetworkSession
{
$session = new NetworkSession(
$this->server,
$this->server->getNetwork()->getSessionManager(),
PacketPool::getInstance(),
new ProxyPacketSender($socketId, $this),
$this->packetBroadcaster,
$this->entityEventBroadcaster,
ZlibCompressor::getInstance(),
TypeConverter::getInstance(),
$ip,
$port
);
$this->sessions[$socketId] = $session;
return $session;
}
public function setName(string $name): void
{
//NOPEH
}
public function shutdown(): void
{
$this->proxy->shutdown();
socket_write($this->threadNotifier, "\x00");
$this->proxy->quit();
@socket_close($this->threadNotifier);
$this->server->getTickSleeper()->removeNotifier($this->sleeperEntry->getNotifierId());
}
}