-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathClientConnection.php
749 lines (721 loc) · 19.1 KB
/
ClientConnection.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
<?php
namespace Phpcraft;
use Asyncore\Asyncore;
use BadMethodCallException;
use DomainException;
use GMP;
use hellsh\UUID;
use Phpcraft\
{Command\ServerCommandSender, Entity\Player, Enum\ChatPosition, Enum\Gamemode, Exception\IOException, Packet\ClientboundAbilitiesPacket, Packet\ClientboundChatMessagePacket, Packet\ClientboundPacketId, Packet\UnloadChunkPacket, World\Chunk, World\World};
/** A server-to-client connection. */
class ClientConnection extends Connection implements ServerCommandSender
{
/**
* The hostname the client had connected to.
*
* @see ClientConnection::getHost
* @see ClientConnection::handleInitialPacket
* @var string $hostname
*/
public $hostname;
/**
* The port the client had connected to.
*
* @see ClientConnection::handleInitialPacket
* @see ClientConnection::getHost
* @var int $hostport
*/
public $hostport;
/**
* Additional data the client had provided in the handshake.
* E.g., "FML" is in this array for Forge clients.
*
* @var array<string> $join_specs
*/
public $join_specs = [];
/**
* The client's in-game name.
*
* @var string $username
*/
public $username;
/**
* The UUID of the client.
*
* @var UUID $uuid
*/
public $uuid;
/**
* @var ClientConfiguration $config
*/
public $config;
/**
* This variable is for servers to keep track of when to send the next keep alive packet to clients.
*
* @var float $next_heartbeat
*/
public $next_heartbeat = 0;
/**
* This variable is for servers to keep track of how long clients have to answer keep alive packets.
*
* @var float $disconnect_after
*/
public $disconnect_after = 0;
/**
* Used by proxy servers to store the downstream connection instance.
*
* @var ServerConnection $downstream
*/
public $downstream;
/**
* Used by proxy servers to store if the client is incompatible with the downstream server and needs packets to be converted.
*
* @var bool $convert_packets
*/
public $convert_packets;
/**
* The client's entity ID.
*
* @var GMP $eid
*/
public $eid;
/**
* The downstream entity ID. Used only on proxy servers.
*
* @var GMP $downstream_eid
*/
public $downstream_eid;
/**
* The name of the world the client is in.
*
* @var string $world
* @since 0.5.6
*/
public $world = "world";
/**
* The client's position in the world they are in.
*
* @var Point3D $pos
*/
public $pos;
/**
* @var int|null $chunk_x
*/
public $chunk_x;
/**
* @var int|null $chunk_z
*/
public $chunk_z;
/**
* The client's rotation on the X axis, 0 to 359.9.
*
* @var float $yaw
*/
public $yaw = 0;
/**
* The client's rotation on the Y axis, -90 to 90.
*
* @var float $pitch
*/
public $pitch = 0;
/**
* @var Counter $tpidCounter
*/
public $tpidCounter;
/**
* @var float $tp_confirm_deadline
*/
public $tp_confirm_deadline = 0;
/**
* @var boolean $on_ground
* @see ServerOnGroundChangeEvent
*/
public $on_ground = false;
/**
* @var int $render_distance
*/
public $render_distance = 8;
/**
* @var array $chunks
*/
public $chunks = [];
/**
* @var array $chunk_queue
*/
public $chunk_queue = [];
/**
* @var int $gamemode
*/
public $gamemode = Gamemode::SURVIVAL;
/**
* @var Player|null $entityMetadata
* @todo Create sendMetadata method
*/
public $entityMetadata;
/**
* @var boolean $invulnerable
* @see ClientConnection::sendAbilities
*/
public $invulnerable = false;
/**
* @var boolean $flying
* @see ClientConnection::sendAbilities
* @see ServerFlyChangeEvent
*/
public $flying = false;
/**
* @var boolean $can_fly
* @see ClientConnection::sendAbilities
*/
public $can_fly = false;
/**
* @var boolean $instant_breaking
* @see ClientConnection::sendAbilities
* @see ClientConnection::setGamemode
*/
public $instant_breaking = false;
/**
* @var float $fly_speed
* @see ClientConnection::sendAbilities
*/
public $fly_speed = 0.05;
/**
* @var float $walk_speed
* @see ClientConnection::sendAbilities
*/
public $walk_speed = 0.1;
/**
* After this, you should call ClientConnection::handleInitialPacket().
*
* @param resource $stream
* @param Server|null $server
*/
function __construct($stream, ?Server &$server = null)
{
parent::__construct(-1, $stream);
$this->tpidCounter = new Counter();
if($server)
{
$this->config = new ClientConfiguration($server, $this);
}
}
/**
* Deals with the first packet the client has sent.
* This function deals with the handshake or legacy list ping packet.
* Errors will cause the connection to be closed.
*
* @return int Status: 0 = The client is yet to present an initial packet. 1 = Handshake was successfully read; use Connection::$state to see if the client wants to get the status (1) or login to play (2). 2 = A legacy list ping packet has been received. 3 = An error occured and the connection has been closed.
*/
function handleInitialPacket(): int
{
try
{
if($this->readRawPacket(0, 1))
{
$packet_length = $this->readUnsignedByte();
if($packet_length == 0xFE)
{
if($this->readRawPacket(0) && $this->readUnsignedByte() == 0x01 && $this->readUnsignedByte() == 0xFA && $this->readShort() == 11 && $this->readRaw(22) == mb_convert_encoding("MC|PingHost", "utf-16be"))
{
$this->ignoreBytes(2);
$this->protocol_version = $this->readByte();
$this->setHostname(mb_convert_encoding($this->readRaw($this->readShort() * 2), "utf-8", "utf-16be"));
$this->hostport = gmp_intval($this->readInt());
return 2;
}
}
else if($this->readRawPacket(0, $packet_length))
{
$packet_id = gmp_intval($this->readVarInt());
if($packet_id === 0x00)
{
$this->protocol_version = gmp_intval($this->readVarInt());
$this->setHostname($this->readString());
$this->hostport = $this->readUnsignedShort();
$this->state = gmp_intval($this->readVarInt());
if($this->state == self::STATE_STATUS || $this->state == self::STATE_LOGIN)
{
return 1;
}
throw new IOException("Invalid state: ".$this->state);
}
}
}
}
catch(IOException $e)
{
$this->disconnect($e->getMessage());
return 3;
}
return 0;
}
private function setHostname(string $hostname): void
{
$arr = explode("\0", $hostname);
$this->hostname = $arr[0];
$this->join_specs = array_slice($arr, 1);
}
/**
* Disconnects the client with an optional reason.
*
* @param array|string|null|ChatComponent $reason The reason for the disconnect.
* @return void
*/
function disconnect($reason = null): void
{
if($this->state == self::STATE_PLAY || $this->state == self::STATE_LOGIN)
{
try
{
if($this->state == self::STATE_PLAY)
{
$this->startPacket("disconnect");
}
else // STATE_LOGIN
{
$this->write_buffer = Connection::varInt(0x00);
}
$this->writeChat(ChatComponent::cast($reason));
$this->send();
@fflush($this->stream);
}
catch(IOException $ignored)
{
}
}
$this->close();
}
/**
* Clears the write buffer and starts a new packet.
*
* @param string|integer $packet The name or ID of the new packet.
* @return Connection $this
*/
function startPacket($packet): Connection
{
if(gettype($packet) == "string")
{
$packetId = ClientboundPacketId::get($packet);
if(!$packetId)
{
throw new DomainException("Unknown packet name: ".$packet);
}
$packet = $packetId->getId($this->protocol_version);
}
return parent::startPacket($packet);
}
/**
* Returns the host the client had connected to, e.g. localhost:25565.
* Note that SRV records are pre-connection redirects, so if _minecraft._tcp.example.com points to mc.example.com which is an A or AAAA record, this will return mc.example.com:25565.
*
* @return string
*/
function getHost(): string
{
return $this->hostname.":".$this->hostport;
}
/**
* Sends an Encryption Request Packet.
*
* @param resource $private_key Your OpenSSL private key resource.
* @return ClientConnection $this
* @throws IOException
*/
function sendEncryptionRequest($private_key): ClientConnection
{
if($this->state == self::STATE_LOGIN)
{
$this->write_buffer = Connection::varInt(0x01);
$this->writeString(""); // Server ID
$this->writeString(base64_decode(trim(substr(openssl_pkey_get_details($private_key)["key"], 26, -24)))); // Public Key
$this->writeString("1337"); // Verify Token
$this->send();
}
return $this;
}
/**
* Reads an encryption response packet and starts asynchronous authentication with Mojang.
* This requires ClientConnection::$username to be set.
* In case of an error, the client is disconnected and the callback is called with false.
* Should the authentication with Mojang finish successfully, the callback is called with an array like this as argument:
* <pre>[
* "id" => "11111111222233334444555555555555",
* "name" => "Notch",
* "properties" => [
* [
* "name" => "textures",
* "value" => "<base64 string>",
* "signature" => "<base64 string; signed data using Yggdrasil's private key>"
* ]
* ]
* ]</pre>
*
* @param resource $private_key Your OpenSSL private key resource.
* @param callable $callback
* @return boolean
* @throws IOException
*/
function handleEncryptionResponse($private_key, callable $callback): bool
{
openssl_private_decrypt($this->readString(), $shared_secret, $private_key, OPENSSL_PKCS1_PADDING);
openssl_private_decrypt($this->readString(), $verify_token, $private_key, OPENSSL_PKCS1_PADDING);
if($verify_token !== "1337")
{
$this->close();
return false;
}
$opts = [
"mode" => "cfb",
"iv" => $shared_secret,
"key" => $shared_secret
];
stream_filter_append($this->stream, "mcrypt.rijndael-128", STREAM_FILTER_WRITE, $opts);
stream_filter_append($this->stream, "mdecrypt.rijndael-128", STREAM_FILTER_READ, $opts);
$ch = curl_init("https://sessionserver.mojang.com/session/minecraft/hasJoined?username=".$this->username."&serverId=".Phpcraft::sha1($shared_secret.base64_decode(trim(substr(openssl_pkey_get_details($private_key)["key"], 26, -24))))."&ip=".$this->getRemoteAddress());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(Phpcraft::isWindows())
{
curl_setopt($ch, CURLOPT_CAINFO, __DIR__."/cacert.pem");
}
Asyncore::curl_exec($ch, function($res) use (&$ch, &$callback)
{
curl_close($ch);
$json = json_decode($res, true);
if(!$json || empty($json["id"]) || @$json["name"] !== $this->username)
{
$this->disconnect("Failed to authenticate against the session server.");
}
$callback($json);
});
return true;
}
/**
* Sets the compression threshold and finishes the login.
*
* @param UUID $uuid The UUID of the client.
* @param Counter $eidCounter The server's Counter to assign an entity ID to the client.
* @param int $compression_threshold The amount of bytes a packet needs to have before it is compressed. Use -1 to disable compression. Compression will always be disabled on loopback connections.
* @return ClientConnection $this
* @throws IOException
*/
function finishLogin(UUID $uuid, Counter $eidCounter, int $compression_threshold = 256): ClientConnection
{
if($this->state != self::STATE_LOGIN)
{
throw new BadMethodCallException("Call to finishLogin on Connection in state ".$this->state);
}
if($compression_threshold > -1 && in_array($this->getRemoteAddress(), [
"127.0.0.1",
"::1"
]))
{
$compression_threshold = -1;
}
if($compression_threshold > -1 || $this->protocol_version < 48)
{
$this->write_buffer = Connection::varInt(0x03);
$this->writeVarInt($compression_threshold);
$this->send();
}
$this->compression_threshold = $compression_threshold;
$this->uuid = $uuid;
$this->write_buffer = Connection::varInt(0x02); // Login Success
if($this->protocol_version >= 707)
{
$this->writeUUID($this->uuid);
}
else
{
$this->writeString($this->uuid->toString(true));
}
$this->writeString($this->username);
$this->send();
$this->eid = $eidCounter->next();
$this->entityMetadata = new Player();
$this->state = self::STATE_PLAY;
if($this->config && $this->config->server->persist_configs)
{
$this->config->setFile("config/player_data/".$this->uuid->toString(false).".json");
}
return $this;
}
/**
* Teleports the client to the given position, and optionally, changes their rotation.
*
* @param Point3D $pos
* @param float|null $yaw
* @param float|null $pitch
* @param int $deadline
* @return ClientConnection $this
* @throws IOException
*/
function teleport(Point3D $pos, ?float $yaw = null, ?float $pitch = null, int $deadline = 3): ClientConnection
{
$this->pos = $pos;
$this->chunk_x = floor($pos->x / 16);
$this->chunk_z = floor($pos->x / 16);
$flags = 0;
if($yaw === null)
{
$flags |= 0x10;
}
else
{
$this->yaw = $yaw;
}
if($pitch === null)
{
$flags |= 0x08;
}
else
{
$this->pitch = $pitch;
}
$this->startPacket("teleport");
$this->writePrecisePosition($this->pos);
$this->writeFloat($yaw ?? 0);
$this->writeFloat($pitch ?? 0);
$this->writeByte($flags);
if($this->protocol_version > 47)
{
$this->writeVarInt($this->tpidCounter->next());
$this->tp_confirm_deadline = microtime(true) + $deadline;
}
$this->send();
return $this;
}
/**
* Changes the client's rotation.
*
* @param int $yaw
* @param int $pitch
* @return ClientConnection $this
* @throws IOException
*/
function rotate(int $yaw, int $pitch): ClientConnection
{
$this->startPacket("teleport");
$this->writeDouble(0);
$this->writeDouble(0);
$this->writeDouble(0);
$this->writeFloat($this->yaw = $yaw);
$this->writeFloat($this->pitch = $pitch);
$this->writeByte(0b111);
if($this->protocol_version > 47)
{
$this->writeVarInt($this->tpidCounter->next());
$this->tp_confirm_deadline = microtime(true) + 3;
}
$this->send();
return $this;
}
function getEyePosition(): Point3D
{
return $this->pos->add(0, $this->entityMetadata->crouching ? 1.28 : 1.62, 0);
}
/**
* Returns a unit vector goin in the direction the client is looking.
*
* @return Point3D
*/
function getUnitVector(): Point3D
{
return Point3D::getUnitVector($this->yaw, $this->pitch);
}
/**
* @return void
* @since 0.5
*/
function generateChunkQueue(): void
{
$this->chunk_queue = [];
for($x = $this->chunk_x - $this->render_distance; $x <= $this->chunk_x + $this->render_distance; $x++)
{
for($z = $this->chunk_z - $this->render_distance; $z <= $this->chunk_z + $this->render_distance; $z++)
{
$name = "$x:$z";
if(!array_key_exists($name, $this->chunks))
{
$this->chunk_queue[$name] = [
$x,
$z
];
}
}
}
}
/**
* @return void
* @throws IOException
* @since 0.5.9
*/
function unloadChunks(): void
{
foreach($this->chunks as $chunk)
{
$arr = explode(":", $chunk);
(new UnloadChunkPacket($arr[0], $arr[1]))->send($this);
}
$this->chunks = [];
}
/**
* Returns the chunk the client is standing in or null if there's no applicable world.
*
* @return Chunk|null
*/
function getChunk(): ?Chunk
{
$world = $this->getWorld();
return $world instanceof World ? $world->getChunk($this->chunk_x, $this->chunk_z) : null;
}
/**
* Returns a World that you can directly interact with or null if not applicable.
*
* @return World|null
*/
function getWorld(): ?World
{
$server = $this->getServer();
return $server instanceof IntegratedServer && $this->downstream === null ? $this->getServer()->worlds[$this->world] : null;
}
function getServer(): Server
{
return $this->config->server;
}
/**
* Sends a message to the client and "[{$this->username}: $message]" to the server console and players with the given permission.
*
* @param array|string|null|ChatComponent $message
* @param string $permission
* @return void
* @throws IOException
*/
function sendAdminBroadcast($message, string $permission = "everything"): void
{
$this->sendMessage($message);
$message = ChatComponent::text("[{$this->username}: ")
->gray()
->add($message)
->add("]");
echo $message->toString(ChatComponent::FORMAT_ANSI)."\n";
foreach($this->getServer()->clients as $con)
{
assert($con instanceof ClientConnection);
try
{
if($con != $this && $con->state == self::STATE_PLAY && $con->hasPermission($permission))
{
$con->sendMessage($message);
}
}
catch(IOException $e)
{
}
}
}
/**
* Sends a chat message to the client.
*
* @param array|string|null|ChatComponent $message
* @param int $position
* @return void
* @throws IOException
*/
function sendMessage($message, int $position = ChatPosition::SYSTEM): void
{
(new ClientboundChatMessagePacket($message))->send($this);
}
function hasPermission(string $permission): bool
{
return $this->config->hasPermission($permission);
}
/**
* Sets the client's gamemode and adjusts their abilities accordingly.
*
* @param int $gamemode
* @param bool $abilities If false, abilities will not be touched.
* @return ClientConnection $this
* @throws Exception\NoConnectionException
* @throws IOException
* @since 0.5.14 Added $abilities parameter
* @see Gamemode
*/
function setGamemode(int $gamemode, bool $abilities = true): ClientConnection
{
if(!Gamemode::validateValue($gamemode))
{
throw new DomainException("Invalid gamemode: ".$gamemode);
}
$this->gamemode = $gamemode;
$this->startPacket("change_game_state");
$this->writeByte(3);
$this->writeFloat($gamemode);
$this->send();
if($abilities)
{
$this->setAbilitiesFromGamemode($gamemode)
->sendAbilities();
}
return $this;
}
/**
* Sends the client their abilities.
*
* @return ClientConnection $this
* @throws IOException
* @see ClientConnection::$invulnerable
* @see ClientConnection::$flying
* @see ClientConnection::$can_fly
* @see ClientConnection::$instant_breaking
* @see ClientConnection::$fly_speed
* @see ClientConnection::$walk_speed
*/
function sendAbilities(): ClientConnection
{
$packet = new ClientboundAbilitiesPacket();
$packet->invulnerable = $this->invulnerable;
$packet->flying = $this->flying;
$packet->can_fly = $this->can_fly;
$packet->instant_breaking = $this->instant_breaking;
$packet->fly_speed = $this->fly_speed;
$packet->walk_speed = $this->walk_speed;
$packet->send($this);
return $this;
}
/**
* Sets the client's abilities according to the given gamemode.
*
* @param int $gamemode
* @return ClientConnection $this
* @see ClientConnection::sendAbilities
* @see ClientConnection::setGamemode
*/
function setAbilitiesFromGamemode(int $gamemode): ClientConnection
{
$this->instant_breaking = ($gamemode == Gamemode::CREATIVE);
$this->flying = ($gamemode == Gamemode::SPECTATOR);
$this->invulnerable = $this->can_fly = ($gamemode == Gamemode::CREATIVE || $gamemode == Gamemode::SPECTATOR);
return $this;
}
function getName(): string
{
return $this->username;
}
function hasPosition(): bool
{
return $this->pos !== null;
}
function getPosition(): ?Point3D
{
return $this->pos;
}
/**
* Available in accordance with the CommandSender interface.
*
* @return bool true
*/
function hasServer(): bool
{
return true;
}
}