-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathIntegratedServer.php
666 lines (660 loc) · 18.8 KB
/
IntegratedServer.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
<?php
namespace Phpcraft;
use Exception;
use hellsh\UUID;
use Phpcraft\
{Command\Command, Entity\Player, Enum\Difficulty, Enum\Gamemode, Event\ServerChatEvent, Event\ServerChunkBorderEvent, Event\ServerClientMetadataEvent, Event\ServerClientSettingsEvent, Event\ServerFlyingChangeEvent, Event\ServerJoinEvent, Event\ServerLeaveEvent, Event\ServerListPingEvent, Event\ServerMovementEvent, Event\ServerOnGroundChangeEvent, Event\ServerPacketEvent, Event\ServerRotationEvent, Exception\IOException, Packet\ChunkDataPacket, Packet\ClientboundChatMessagePacket, Packet\ClientSettingsPacket, Packet\DifficultyPacket, Packet\JoinGamePacket, Packet\PluginMessage\ClientboundBrandPluginMessagePacket, Packet\ServerboundPacketId, World\BlockState, World\Chunk, World\ChunkSection, World\StaticChunkGenerator, World\World};
use RuntimeException;
class IntegratedServer extends Server
{
/**
* @var string $name
*/
public $name;
/**
* @var PlainUserInterface $ui
*/
public $ui;
/**
* @var array<string,mixed> $config
*/
public $config;
/**
* @var array<string,mixed> $custom_config_defaults
*/
public $custom_config_defaults;
/**
* The function called after the config has been reloaded.
*
* @var callable|null $config_reloaded_function
*/
public $config_reloaded_function;
/**
* The position where clients will spawn at.
* Defaults to <pre>new Point3D(0, 16, 0)</pre>.
*
* @var Point3D $spawn_position
*/
public $spawn_position;
/**
* @param string|null $name
* @param array $custom_config_defaults
* @param UserInterface|null $ui
* @param resource|null $private_key A private key generated using openssl_pkey_new(["private_key_bits" => 1024, "private_key_type" => OPENSSL_KEYTYPE_RSA]) to use for online mode, or null to use offline mode.
*/
function __construct(?string $name = null, array $custom_config_defaults = [], ?UserInterface $ui = null, $private_key = null)
{
parent::__construct([], $private_key);
$this->name = $name ?? static::getDefaultName();
$this->custom_config_defaults = $custom_config_defaults;
$this->spawn_position = new Point3D(0, 16, 0);
$this->ui = $ui ?? new PlainUserInterface($name);
$this->persist_configs = true;
$this->reloadConfig();
if($this->ui instanceof FancyUserInterface)
{
$this->ui->setInputPrefix("[".$this->name."] ");
$this->ui->tabcomplete_function = function(string $word)
{
$word = strtolower($word);
$completions = [];
$len = strlen($word);
foreach($this->clients as $c)
{
if($c->state == Connection::STATE_PLAY && strtolower(substr($c->username, 0, $len)) == $word)
{
array_push($completions, $c->username);
}
}
return $completions;
};
}
$default_list_ping_function = $this->list_ping_function;
$this->list_ping_function = function(ClientConnection $con = null) use (&$default_list_ping_function)
{
$data = $default_list_ping_function($con);
if($this->config["server_list_appearance"]["show_question_marks_instead_of_player_count"])
{
unset($data["players"]);
}
$data["description"] = $this->config["server_list_appearance"]["description"];
$data["modinfo"] = [
"type" => "FML",
"modList" => []
];
if($this->config["server_list_appearance"]["show_no_connection_instead_of_ping"])
{
$data["no_ping"] = true;
}
$event = new ServerListPingEvent($this, $con, $data);
return PluginManager::fire($event) ? null : $event->data;
};
$this->join_function = function(ClientConnection $con)
{
if(!$this->isOnlineMode())
{
foreach($this->clients as $client)
{
if($client !== $con && $client->state == Connection::STATE_PLAY && $client->username == $con->username)
{
if(strlen($con->username) <= 13)
{
for($i = 2; $i <= 9; $i++)
{
if($this->getPlayer("{$con->username}($i)") === null)
{
$con->username .= "($i)";
$con->uuid = UUID::name("OfflinePlayer:".$con->username);
$con->sendMessage([
"text" => "To avoid conflicts, your name has been changed to {$con->username}.",
"color" => "red"
]);
break 2;
}
}
}
$con->disconnect(ChatComponent::text("")
->add(ChatComponent::text("You")
->italic())
->add("'re already on this server, and the best solution I have is kicking ")
->add(ChatComponent::text("you.")
->bold()));
$con->state = Connection::STATE_LOGIN; // prevent ServerLeaveEvent being fired
return;
}
}
}
$packet = new JoinGamePacket($con->eid);
$packet->gamemode = $con->gamemode = Gamemode::CREATIVE;
$packet->render_distance = 32;
$packet->send($con);
(new DifficultyPacket(Difficulty::PEACEFUL))->send($con);
(new ClientboundBrandPluginMessagePacket($this->name))->send($con);
$con->setAbilitiesFromGamemode($con->gamemode)
->sendAbilities();
$con->startPacket("spawn_position");
$con->writePosition($con->pos = $this->spawn_position);
$con->send();
$con->teleport($con->pos, null, null, 10);
if(PluginManager::fire(new ServerJoinEvent($this, $con)))
{
$con->close();
return;
}
foreach($this->getPlayers() as $c)
{
try
{
$c->startPacket("player_info");
$c->writeVarInt(0);
$c->writeVarInt(1);
$c->writeUUID($con->uuid);
$c->writeString($con->username);
$c->writeVarInt(0);
$c->writeVarInt(-1);
$c->writeVarInt(-1);
$c->writeBoolean(false);
$c->send();
if($c !== $con)
{
$con->startPacket("player_info");
$con->writeVarInt(0);
$con->writeVarInt(1);
$con->writeUUID($c->uuid);
$con->writeString($c->username);
$con->writeVarInt(0);
$con->writeVarInt(0);
$con->writeVarInt(-1);
$con->writeBoolean(false);
$con->send();
}
}
catch(Exception $ignored)
{
}
}
if($con->protocol_version > 47)
{
// This is required so F3+N doesn't fail due to "no permission"
$con->startPacket("entity_status");
$con->writeInt($con->eid);
$con->writeByte(Player::STATUS_OP_LEVEL_4);
$con->send();
}
$con->generateChunkQueue();
};
$this->packet_function = function(ClientConnection $con, ServerboundPacketId $packetId)
{
if(PluginManager::fire(new ServerPacketEvent($this, $con, $packetId)))
{
return;
}
if($packetId->name == "position" || $packetId->name == "position_and_look" || $packetId->name == "look" || $packetId->name == "no_movement")
{
if($con->tp_confirm_deadline != 0)
{
return;
}
if($packetId->name == "position" || $packetId->name == "position_and_look")
{
$prev_pos = $con->pos;
$con->pos = $con->readPrecisePosition();
if(PluginManager::fire(new ServerMovementEvent($this, $con, $prev_pos)))
{
$con->teleport($prev_pos);
}
else
{
$chunk_x = (int) floor($con->pos->x / 16);
$chunk_z = (int) floor($con->pos->z / 16);
if($chunk_x != $con->chunk_x || $chunk_z != $con->chunk_z)
{
$prev_chunk_x = $con->chunk_x;
$prev_chunk_z = $con->chunk_z;
$con->chunk_x = $chunk_x;
$con->chunk_z = $chunk_z;
if(PluginManager::fire(new ServerChunkBorderEvent($this, $con, $prev_pos, $prev_chunk_x, $prev_chunk_z)))
{
$con->teleport($prev_pos);
}
else
{
if($con->protocol_version >= 472)
{
$con->startPacket("update_view_position");
$con->writeVarInt($con->chunk_x);
$con->writeVarInt($con->chunk_z);
$con->send();
}
$con->generateChunkQueue();
}
}
}
}
if($packetId->name == "position_and_look" || $packetId->name == "look")
{
$prev_yaw = $con->yaw;
$prev_pitch = $con->pitch;
$con->yaw = $con->readFloat();
if($con->yaw < 0 || $con->yaw > 360)
{
$con->yaw -= floor($con->yaw / 360) * 360;
}
$con->pitch = $con->readFloat();
if($con->pitch < -90 || $con->pitch > 90)
{
throw new IOException("Invalid Y rotation: ".$con->pitch);
}
if(PluginManager::fire(new ServerRotationEvent($this, $con, $prev_yaw, $prev_pitch)))
{
$con->rotate($prev_yaw, $prev_pitch);
}
}
$_on_ground = $con->on_ground;
$con->on_ground = $con->readBoolean();
if($_on_ground != $con->on_ground)
{
PluginManager::fire(new ServerOnGroundChangeEvent($this, $con, $_on_ground));
}
}
else if($packetId->name == "entity_action")
{
if(gmp_cmp($con->readVarInt(), $con->eid) != 0)
{
throw new IOException("Entity ID mismatch in Entity Action packet");
}
$prev_metadata = clone $con->entityMetadata;
switch($con->readByte())
{
case 0:
$con->entityMetadata->crouching = true;
break;
case 1:
$con->entityMetadata->crouching = false;
break;
case 3:
$con->entityMetadata->sprinting = true;
break;
case 4:
$con->entityMetadata->sprinting = false;
break;
}
if($con->entityMetadata->crouching !== $prev_metadata->crouching || $con->entityMetadata->sprinting !== $prev_metadata->sprinting)
{
if(PluginManager::fire(new ServerClientMetadataEvent($this, $con, $prev_metadata)))
{
// TODO: Revert metadata when cancelled.
}
}
}
else if($packetId->name == "serverbound_abilities")
{
$flags = $con->readByte();
$_flying = $con->flying;
$con->flying = ($flags & 0x02);
if($_flying != $con->flying)
{
PluginManager::fire(new ServerFlyingChangeEvent($this, $con, $_flying));
}
}
else if($packetId->name == "serverbound_chat_message")
{
$msg = $con->readString($con->protocol_version < 314 ? 100 : 256);
if(strpos($msg, "§") !== false)
{
$con->disconnect("Illegal chat message");
}
if(Command::handleMessage($con, $msg) || PluginManager::fire(new ServerChatEvent($this, $con, $msg)))
{
return;
}
$msg = ChatComponent::translate("chat.type.text", [
$con->username,
$msg
]);
$this->ui->add($msg->toString(ChatComponent::FORMAT_ANSI));
$msg = new ClientboundChatMessagePacket($msg);
foreach($this->getPlayers() as $c)
{
try
{
$msg->send($c);
}
catch(Exception $ignored)
{
}
}
}
else if($packetId->name == "client_settings")
{
$packet = ClientSettingsPacket::read($con);
PluginManager::fire(new ServerClientSettingsEvent($this, $con, $packet));
$con->render_distance = max(min($packet->render_distance, 32), 2);
}
};
$this->disconnect_function = function(ClientConnection $con)
{
if($con->state == Connection::STATE_PLAY)
{
PluginManager::fire(new ServerLeaveEvent($this, $con));
foreach($this->getPlayers() as $c)
{
try
{
$c->startPacket("player_info");
$c->writeVarInt(4);
$c->writeVarInt(1);
$c->writeUUID($con->uuid);
$c->send();
}
catch(Exception $ignored)
{
}
}
}
};
$this->open_condition->add(function(bool $lagging)
{
if($lagging)
{
return;
}
$changes = false;
foreach($this->getPlayers() as $player)
{
$world = $player->getWorld();
if($world instanceof World && count($world->changed_chunks) > 0)
{
$player->chunks = array_filter($player->chunks, function($name) use (&$world)
{
return !array_key_exists($name, $world->changed_chunks);
});
$player->generateChunkQueue();
$changes = true;
}
}
if($changes)
{
foreach($this->worlds as $world)
{
$world->changed_chunks = [];
}
}
$chunks_limit = 20; // chunks/tick limit
foreach($this->clients as $con)
{
assert($con instanceof ClientConnection);
if($con->downstream !== null)
{
continue;
}
try
{
foreach($con->chunk_queue as $chunk_name => $chunk_coords)
{
(new ChunkDataPacket($chunk_coords[0], $chunk_coords[1], true, $con->getWorld()
->getChunk($chunk_coords[0], $chunk_coords[1])))->send($con);
$con->chunks[$chunk_name] = $chunk_name;
unset($con->chunk_queue[$chunk_name]);
if(--$chunks_limit == 0)
{
return;
}
}
}
catch(Exception $ignored)
{
}
}
}, 0.05);
}
static function getDefaultName(): string
{
return "Phpcraft Integrated Server";
}
/**
* @return void
*/
function reloadConfig(): void
{
if(!is_dir("config"))
{
mkdir("config");
}
if(is_file("config/".$this->name.".json"))
{
$this->config = json_decode(file_get_contents("config/".$this->name.".json"), true);
}
else
{
$this->config = [];
}
foreach($this->custom_config_defaults as $key => $default)
{
if(!array_key_exists($key, $this->config))
{
$this->config[$key] = $default;
}
}
if(array_key_exists("world_is_made_of", $this->config))
{
$this->config["worlds"] = [
"world" => $this->config["world_is_made_of"]
];
unset($this->config["world_is_made_of"]);
}
else if(!array_key_exists("worlds", $this->config))
{
$this->config["worlds"] = [
"world" => "grass_block[snowy=false]"
];
}
$changed_chunks = [];
foreach($this->worlds as $world_name => $world)
{
foreach($world->chunks as $chunk_name => $chunk)
{
$changed_chunks[$world_name][$chunk_name] = $chunk_name;
}
}
$this->worlds = [];
foreach($this->config["worlds"] as $world_name => $world_is_made_of)
{
$blockState = BlockState::get($world_is_made_of) ?? BlockState::get("grass_block[snowy=false]");
$this->config["worlds"][$world_name] = $blockState->__toString();
$chunk = new Chunk();
$chunk->setSection(0, ChunkSection::filled($blockState));
$this->worlds[$world_name] = (new StaticChunkGenerator(new World(), $chunk))->init();
$this->worlds[$world_name]->changed_chunks = $changed_chunks;
}
if(!array_key_exists("groups", $this->config))
{
$this->config["groups"] = [
"default" => [
"allow" => [
"use /me",
"use /gamemode",
"use /metadata"
]
],
"user" => [
"inherit" => "default",
"allow" => [
"use /abilities",
"change the world"
]
],
"admin" => [
"allow" => "everything"
]
];
}
if(!array_key_exists("ports", $this->config))
{
$this->config["ports"] = [25565];
}
if(!array_key_exists("server_list_appearance", $this->config))
{
$this->config["server_list_appearance"] = [];
}
if(array_key_exists("description", $this->config["server_list_appearance"]))
{
$this->config["server_list_appearance"]["description"] = ChatComponent::fromArray($this->config["server_list_appearance"]["description"])
->toArray();
}
else
{
$this->config["server_list_appearance"]["description"] = [
"text" => "A {$this->name} instance"
];
}
if(!array_key_exists("show_question_marks_instead_of_player_count", $this->config["server_list_appearance"]))
{
$this->config["server_list_appearance"]["show_question_marks_instead_of_player_count"] = false;
}
if(!array_key_exists("show_no_connection_instead_of_ping", $this->config["server_list_appearance"]))
{
$this->config["server_list_appearance"]["show_no_connection_instead_of_ping"] = false;
}
if(!array_key_exists("compression_threshold", $this->config))
{
$this->config["compression_threshold"] = 256;
}
$this->saveConfig();
$this->compression_threshold = $this->config["compression_threshold"];
$this->setGroups($this->config["groups"]);
$open_ports = [];
$streams_ = [];
foreach($this->streams as $stream)
{
$name = stream_socket_get_name($stream, false);
$port = intval(substr($name, strpos($name, ":", -6) + 1));
if(in_array($port, $this->config["ports"]))
{
array_push($open_ports, $port);
array_push($streams_, $stream);
}
else
{
stream_socket_shutdown($stream, STREAM_SHUT_RDWR);
fclose($stream);
$this->adminBroadcast("Unbound from ".$name);
}
}
$this->streams = $streams_;
foreach($this->config["ports"] as $port)
{
if(in_array($port, $open_ports))
{
continue;
}
foreach([
"0.0.0.0:",
"[::0]:"
] as $prefix)
{
if($stream = @stream_socket_server("tcp://".$prefix.$port, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN))
{
stream_set_blocking($stream, false);
array_push($this->streams, $stream);
$this->adminBroadcast("Successfully bound to ".$prefix.$port);
}
else
{
$this->adminBroadcast("Failed to bind to ".$prefix.$port);
}
}
}
if(!$this->isListening() && $this->isOpen())
{
$this->adminBroadcast($this->name." is not listening on any ports. It will shutdown once empty.");
}
else if($this->config_reloaded_function)
{
($this->config_reloaded_function)();
}
}
/**
* @return void
*/
function saveConfig(): void
{
file_put_contents("config/".$this->name.".json", json_encode($this->config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}
/**
* Starts the integrated server using $argv.
*
* @param string|null $name
* @param array $custom_config_defaults
* @return IntegratedServer
*/
static function cliStart(?string $name = null, array $custom_config_defaults = []): IntegratedServer
{
global $argv;
$options = [
"offline" => false,
"plain" => false
];
for($i = 1; $i < count($argv); $i++)
{
$arg = ltrim($argv[$i], "-/");
switch($arg)
{
case "offline":
case "plain":
$options[$arg] = true;
break;
case "?":
case "help":
echo "offline disables online mode and allows cracked players\n";
echo "plain uses the plain user interface e.g. for writing logs to a file\n";
exit;
default:
die("Unknown flag '$arg' -- use 'help' to get a list of supported flags.\n");
}
}
return self::start($name, $options["offline"], $options["plain"], $custom_config_defaults);
}
/**
* Starts the integrated server using the given settings.
*
* @param string|null $name
* @param bool $offline
* @param bool $plain
* @param array $custom_config_defaults
* @return IntegratedServer
*/
static function start(?string $name = null, bool $offline = false, bool $plain = false, array $custom_config_defaults = []): IntegratedServer
{
try
{
$ui = ($plain ? new PlainUserInterface($name) : new FancyUserInterface($name));
}
catch(RuntimeException $e)
{
echo "Since you're on PHP <7.2.0 and Windows <10.0.10586, the plain user interface is forcefully enabled.\n";
$ui = new PlainUserInterface($name);
}
if($offline)
{
$private_key = null;
}
else
{
$ui->add("Generating 1024-bit RSA keypair... ")
->render();
$args = [
"private_key_bits" => 1024,
"private_key_type" => OPENSSL_KEYTYPE_RSA
];
if(Phpcraft::isWindows())
{
$args["config"] = __DIR__."/openssl.cnf";
}
$private_key = openssl_pkey_new($args) or die("Failed to generate private key.\n");
$ui->append("Done.")
->render();
}
return new static($name, $custom_config_defaults, $ui, $private_key);
}
}