-
-
Notifications
You must be signed in to change notification settings - Fork 904
Expand file tree
/
Copy pathVelocityServer.java
More file actions
880 lines (770 loc) · 32.3 KB
/
Copy pathVelocityServer.java
File metadata and controls
880 lines (770 loc) · 32.3 KB
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
/*
* Copyright (C) 2018-2023 Velocity Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.velocitypowered.proxy;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.velocitypowered.api.command.BrigadierCommand;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.proxy.ProxyPreShutdownEvent;
import com.velocitypowered.api.event.proxy.ProxyReloadEvent;
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
import com.velocitypowered.api.network.ProtocolVersion;
import com.velocitypowered.api.plugin.PluginContainer;
import com.velocitypowered.api.plugin.PluginDescription;
import com.velocitypowered.api.plugin.PluginManager;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.player.ResourcePackInfo;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.proxy.server.ServerInfo;
import com.velocitypowered.api.util.Favicon;
import com.velocitypowered.api.util.GameProfile;
import com.velocitypowered.api.util.ProxyVersion;
import com.velocitypowered.proxy.command.VelocityCommandManager;
import com.velocitypowered.proxy.command.builtin.CallbackCommand;
import com.velocitypowered.proxy.command.builtin.GlistCommand;
import com.velocitypowered.proxy.command.builtin.SendCommand;
import com.velocitypowered.proxy.command.builtin.ServerCommand;
import com.velocitypowered.proxy.command.builtin.ShutdownCommand;
import com.velocitypowered.proxy.command.builtin.VelocityCommand;
import com.velocitypowered.proxy.config.VelocityConfiguration;
import com.velocitypowered.proxy.connection.client.ConnectedPlayer;
import com.velocitypowered.proxy.connection.player.resourcepack.VelocityResourcePackInfo;
import com.velocitypowered.proxy.connection.util.ServerListPingHandler;
import com.velocitypowered.proxy.console.VelocityConsole;
import com.velocitypowered.proxy.crypto.EncryptionUtils;
import com.velocitypowered.proxy.event.VelocityEventManager;
import com.velocitypowered.proxy.network.ConnectionManager;
import com.velocitypowered.proxy.plugin.VelocityPluginManager;
import com.velocitypowered.proxy.plugin.loader.VelocityPluginContainer;
import com.velocitypowered.proxy.plugin.loader.VelocityPluginDescription;
import com.velocitypowered.proxy.plugin.virtual.VelocityVirtualPlugin;
import com.velocitypowered.proxy.protocol.ProtocolUtils;
import com.velocitypowered.proxy.protocol.util.FaviconSerializer;
import com.velocitypowered.proxy.protocol.util.GameProfileSerializer;
import com.velocitypowered.proxy.scheduler.VelocityScheduler;
import com.velocitypowered.proxy.server.ServerMap;
import com.velocitypowered.proxy.util.AddressUtil;
import com.velocitypowered.proxy.util.ClosestLocaleMatcher;
import com.velocitypowered.proxy.util.ResourceUtils;
import com.velocitypowered.proxy.util.VelocityChannelRegistrar;
import com.velocitypowered.proxy.util.ratelimit.Ratelimiter;
import com.velocitypowered.proxy.util.ratelimit.Ratelimiters;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyPair;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.translation.MiniMessageTranslationStore;
import net.kyori.adventure.translation.GlobalTranslator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bstats.MetricsBase;
import org.checkerframework.checker.nullness.qual.EnsuresNonNull;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Implementation of {@link ProxyServer}.
*/
public class VelocityServer implements ProxyServer, ForwardingAudience {
public static final String VELOCITY_URL = "https://papermc.io/software/velocity";
private static final Logger logger = LogManager.getLogger(VelocityServer.class);
public static final Gson GENERAL_GSON = new GsonBuilder()
.registerTypeHierarchyAdapter(Favicon.class, FaviconSerializer.INSTANCE)
.registerTypeHierarchyAdapter(GameProfile.class, GameProfileSerializer.INSTANCE)
.create();
private static final Gson PRE_1_16_PING_SERIALIZER = new GsonBuilder()
.registerTypeHierarchyAdapter(
Component.class,
ProtocolUtils.getJsonChatSerializer(ProtocolVersion.MINECRAFT_1_15_2)
.serializer().getAdapter(Component.class)
)
.registerTypeHierarchyAdapter(Favicon.class, FaviconSerializer.INSTANCE)
.create();
private static final Gson PRE_1_20_3_PING_SERIALIZER = new GsonBuilder()
.registerTypeHierarchyAdapter(
Component.class,
ProtocolUtils.getJsonChatSerializer(ProtocolVersion.MINECRAFT_1_20_2)
.serializer().getAdapter(Component.class)
)
.registerTypeHierarchyAdapter(Favicon.class, FaviconSerializer.INSTANCE)
.create();
private static final Gson MODERN_PING_SERIALIZER = new GsonBuilder()
.registerTypeHierarchyAdapter(
Component.class,
ProtocolUtils.getJsonChatSerializer(ProtocolVersion.MINECRAFT_1_20_3)
.serializer().getAdapter(Component.class)
)
.registerTypeHierarchyAdapter(Favicon.class, FaviconSerializer.INSTANCE)
.create();
private static final int PRE_SHUTDOWN_TIMEOUT =
Integer.getInteger("velocity.pre-shutdown-timeout", 10);
private final ConnectionManager cm;
private final ProxyOptions options;
private @MonotonicNonNull VelocityConfiguration configuration;
private @MonotonicNonNull KeyPair serverKeyPair;
private final ServerMap servers;
private final VelocityCommandManager commandManager;
private final AtomicBoolean shutdownInProgress = new AtomicBoolean(false);
private boolean shutdown = false;
private final VelocityPluginManager pluginManager;
private final Map<UUID, ConnectedPlayer> connectionsByUuid = new ConcurrentHashMap<>();
private final Map<String, ConnectedPlayer> connectionsByName = new ConcurrentHashMap<>();
private final VelocityConsole console;
private @MonotonicNonNull Ratelimiter<InetAddress> ipAttemptLimiter;
private @MonotonicNonNull Ratelimiter<UUID> commandRateLimiter;
private @MonotonicNonNull Ratelimiter<UUID> tabCompleteRateLimiter;
private final VelocityEventManager eventManager;
private final VelocityScheduler scheduler;
private final VelocityChannelRegistrar channelRegistrar = new VelocityChannelRegistrar();
private final ServerListPingHandler serverListPingHandler;
VelocityServer(final ProxyOptions options) {
pluginManager = new VelocityPluginManager(this);
eventManager = new VelocityEventManager(pluginManager);
commandManager = new VelocityCommandManager(eventManager, pluginManager);
scheduler = new VelocityScheduler(pluginManager);
console = new VelocityConsole(this);
cm = new ConnectionManager(this);
servers = new ServerMap(this);
serverListPingHandler = new ServerListPingHandler(this);
this.options = options;
}
public KeyPair getServerKeyPair() {
return serverKeyPair;
}
@Override
public VelocityConfiguration getConfiguration() {
return this.configuration;
}
@Override
public ProxyVersion getVersion() {
Package pkg = VelocityServer.class.getPackage();
String implName;
String implVersion;
String implVendor;
if (pkg != null) {
implName = MoreObjects.firstNonNull(pkg.getImplementationTitle(), "Velocity");
implVersion = MoreObjects.firstNonNull(pkg.getImplementationVersion(), "<unknown>");
implVendor = MoreObjects.firstNonNull(pkg.getImplementationVendor(), "Velocity Contributors");
} else {
implName = "Velocity";
implVersion = "<unknown>";
implVendor = "Velocity Contributors";
}
return new ProxyVersion(implName, implVendor, implVersion);
}
private VelocityPluginContainer createVirtualPlugin() {
ProxyVersion version = getVersion();
PluginDescription description = new VelocityPluginDescription(
"velocity", version.getName(), version.getVersion(), "The Velocity proxy",
version.getName().equals("Velocity") ? VELOCITY_URL : null,
ImmutableList.of(version.getVendor()), Collections.emptyList(), null);
VelocityPluginContainer container = new VelocityPluginContainer(description);
container.setInstance(VelocityVirtualPlugin.INSTANCE);
return container;
}
@Override
public VelocityCommandManager getCommandManager() {
return commandManager;
}
void awaitProxyShutdown() {
cm.getBossGroup().terminationFuture().syncUninterruptibly();
}
@EnsuresNonNull({"serverKeyPair", "servers", "pluginManager", "eventManager", "scheduler",
"console", "cm", "configuration"})
void start() {
logger.info("Booting up {} {}...", getVersion().getName(), getVersion().getVersion());
console.setupStreams();
pluginManager.registerPlugin(this.createVirtualPlugin());
// Yes, you're reading that correctly. We're generating a 1024-bit RSA keypair. Sounds
// dangerous, right? We're well within the realm of factoring such a key...
//
// You can blame Mojang. For the record, we also don't consider the Minecraft protocol
// encryption scheme to be secure, and it has reached the point where any serious cryptographic
// protocol needs a refresh. There are multiple obvious weaknesses, and this is far from the
// most serious.
//
// If you are using Minecraft in a security-sensitive application, *I don't know what to say.*
serverKeyPair = EncryptionUtils.createRsaKeyPair(1024);
cm.logChannelInformation();
// Initialize commands first
final BrigadierCommand velocityParentCommand = VelocityCommand.create(this);
commandManager.register(
commandManager.metaBuilder(velocityParentCommand)
.plugin(VelocityVirtualPlugin.INSTANCE)
.build(),
velocityParentCommand
);
final BrigadierCommand callbackCommand = CallbackCommand.create();
commandManager.register(
commandManager.metaBuilder(callbackCommand)
.plugin(VelocityVirtualPlugin.INSTANCE)
.build(),
callbackCommand
);
final BrigadierCommand serverCommand = ServerCommand.create(this);
commandManager.register(
commandManager.metaBuilder(serverCommand)
.plugin(VelocityVirtualPlugin.INSTANCE)
.build(),
serverCommand
);
final BrigadierCommand shutdownCommand = ShutdownCommand.command(this);
commandManager.register(
commandManager.metaBuilder(shutdownCommand)
.plugin(VelocityVirtualPlugin.INSTANCE)
.aliases("end", "stop")
.build(),
shutdownCommand
);
new GlistCommand(this).register();
new SendCommand(this).register();
this.doStartupConfigLoad();
registerTranslations();
for (ServerInfo cliServer : options.getServers()) {
servers.register(cliServer);
}
if (!options.isIgnoreConfigServers()) {
for (Map.Entry<String, String> entry : configuration.getServers().entrySet()) {
servers.register(new ServerInfo(entry.getKey(), AddressUtil.parseAddress(entry.getValue())));
}
}
ipAttemptLimiter = Ratelimiters.createWithMilliseconds(configuration.getLoginRatelimit());
commandRateLimiter = Ratelimiters.createWithMilliseconds(configuration.getCommandRatelimit());
tabCompleteRateLimiter = Ratelimiters.createWithMilliseconds(configuration.getTabCompleteRatelimit());
loadPlugins();
// Go ahead and fire the proxy initialization event. We block since plugins should have a chance
// to fully initialize before we accept any connections to the server.
eventManager.fire(new ProxyInitializeEvent()).join();
// init console permissions after plugins are loaded
console.setupPermissions();
final Integer port = this.options.getPort();
if (port != null) {
logger.debug("Overriding bind port to {} from command line option", port);
this.cm.bind(new InetSocketAddress(configuration.getBind().getHostString(), port));
} else {
this.cm.bind(configuration.getBind());
}
final Boolean haproxy = this.options.isHaproxy();
if (haproxy != null) {
logger.debug("Overriding HAProxy protocol to {} from command line option", haproxy);
configuration.setProxyProtocol(haproxy);
}
if (configuration.isQueryEnabled()) {
this.cm.queryBind(configuration.getBind().getHostString(), configuration.getQueryPort());
}
final String defaultPackage = new String(
new byte[] { 'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's' });
if (!MetricsBase.class.getPackage().getName().startsWith(defaultPackage)) {
Metrics.VelocityMetrics.startMetrics(this, configuration.getMetrics());
} else {
logger.warn("debug environment, metrics is disabled!");
}
}
private void registerTranslations() {
final MiniMessageTranslationStore translationRegistry =
MiniMessageTranslationStore.create(Key.key("velocity", "translations"));
translationRegistry.defaultLocale(Locale.US);
try {
ResourceUtils.visitResources(VelocityServer.class, path -> {
logger.info("Loading localizations...");
final Path langPath = Path.of("lang");
try {
if (!Files.exists(langPath)) {
Files.createDirectory(langPath);
try (final Stream<Path> files = Files.walk(path)) {
files.filter(Files::isRegularFile).forEach(file -> {
try {
final Path langFile = langPath.resolve(file.getFileName().toString());
if (!Files.exists(langFile)) {
try (final InputStream is = Files.newInputStream(file)) {
Files.copy(is, langFile);
}
}
} catch (IOException e) {
logger.error("Encountered an I/O error whilst loading translations", e);
}
});
}
}
try (final Stream<Path> files = Files.walk(langPath)) {
files.filter(Files::isRegularFile).forEach(file -> {
final String filename = com.google.common.io.Files
.getNameWithoutExtension(file.getFileName().toString());
final String localeName = filename.replace("messages_", "")
.replace("messages", "")
.replace('_', '-');
final Locale locale = localeName.isBlank()
? Locale.US
: Locale.forLanguageTag(localeName);
translationRegistry.registerAll(locale, file, false);
ClosestLocaleMatcher.INSTANCE.registerKnown(locale);
});
}
} catch (IOException e) {
logger.error("Encountered an I/O error whilst loading translations", e);
}
}, "com", "velocitypowered", "proxy", "l10n");
} catch (IOException e) {
logger.error("Encountered an I/O error whilst loading translations", e);
return;
}
GlobalTranslator.translator().addSource(translationRegistry);
}
@SuppressFBWarnings("DM_EXIT")
private void doStartupConfigLoad() {
try {
Path configPath = Path.of("velocity.toml");
configuration = VelocityConfiguration.read(configPath);
if (!configuration.validate()) {
logger.error("Your configuration is invalid. Velocity will not start up until the errors "
+ "are resolved.");
LogManager.shutdown();
System.exit(1);
}
commandManager.setAnnounceProxyCommands(configuration.isAnnounceProxyCommands());
} catch (Exception e) {
logger.error("Unable to read/load/save your velocity.toml. The server will shut down.", e);
LogManager.shutdown();
System.exit(1);
}
}
private void loadPlugins() {
logger.info("Loading plugins...");
try {
Path pluginPath = Path.of("plugins");
if (!pluginPath.toFile().exists()) {
Files.createDirectory(pluginPath);
} else if (!pluginPath.toFile().isDirectory()) {
logger.warn("Plugin location {} is not a directory, continuing without loading plugins",
pluginPath);
return;
}
pluginManager.loadPlugins(pluginPath, options.getExtraPluginDirectories(),
options.getExtraPluginJars());
} catch (Exception e) {
logger.error("Couldn't load plugins", e);
}
// Register the plugin main classes so that we can fire the proxy initialize event
for (PluginContainer plugin : pluginManager.getPlugins()) {
Optional<?> instance = plugin.getInstance();
if (instance.isPresent()) {
try {
eventManager.registerInternally(plugin, instance.get());
} catch (Exception e) {
logger.error("Unable to register plugin listener for {}",
plugin.getDescription().getName().orElse(plugin.getDescription().getId()), e);
}
}
}
logger.info("Loaded {} plugins", pluginManager.getPlugins().size());
}
public Bootstrap createBootstrap(@Nullable EventLoopGroup group) {
return this.cm.createWorker(group);
}
public ChannelInitializer<Channel> getBackendChannelInitializer() {
return this.cm.backendChannelInitializer.get();
}
public ServerListPingHandler getServerListPingHandler() {
return serverListPingHandler;
}
public boolean isShutdown() {
return shutdown;
}
/**
* Reloads the proxy's configuration.
*
* @return {@code true} if successful, {@code false} if we can't read the configuration
* @throws IOException if we can't read {@code velocity.toml}
*/
public boolean reloadConfiguration() throws IOException {
Path configPath = Path.of("velocity.toml");
VelocityConfiguration newConfiguration = VelocityConfiguration.read(configPath);
if (!newConfiguration.validate()) {
return false;
}
// Re-register servers. If a server is being replaced, make sure to note what players need to
// move back to a fallback server.
Collection<ConnectedPlayer> evacuate = new ArrayList<>();
for (Map.Entry<String, String> entry : newConfiguration.getServers().entrySet()) {
ServerInfo newInfo = new ServerInfo(entry.getKey(), AddressUtil.parseAddress(entry.getValue()));
Optional<RegisteredServer> rs = servers.getServer(entry.getKey());
if (rs.isEmpty()) {
servers.register(newInfo);
} else if (!rs.get().getServerInfo().equals(newInfo)) {
for (Player player : rs.get().getPlayersConnected()) {
if (!(player instanceof ConnectedPlayer)) {
throw new IllegalStateException("ConnectedPlayer not found for player " + player
+ " in server " + rs.get().getServerInfo().getName());
}
evacuate.add((ConnectedPlayer) player);
}
servers.unregister(rs.get().getServerInfo());
servers.register(newInfo);
}
}
// If we had any players to evacuate, let's move them now. Wait until they are all moved off.
if (!evacuate.isEmpty()) {
CountDownLatch latch = new CountDownLatch(evacuate.size());
for (ConnectedPlayer player : evacuate) {
Optional<RegisteredServer> next = player.getNextServerToTry();
if (next.isPresent()) {
player.createConnectionRequest(next.get()).connectWithIndication()
.whenComplete((success, ex) -> {
if (ex != null || success == null || !success) {
player.disconnect(Component.text("Your server has been changed, but we could "
+ "not move you to any fallback servers."));
}
latch.countDown();
});
} else {
latch.countDown();
player.disconnect(Component.text("Your server has been changed, but we could "
+ "not move you to any fallback servers."));
}
}
try {
latch.await();
} catch (InterruptedException e) {
logger.error("Interrupted whilst moving players", e);
Thread.currentThread().interrupt();
}
}
// If we have a new bind address, bind to it
if (!configuration.getBind().equals(newConfiguration.getBind())) {
this.cm.bind(newConfiguration.getBind());
this.cm.close(configuration.getBind());
}
boolean queryPortChanged = newConfiguration.getQueryPort() != configuration.getQueryPort();
boolean queryAlreadyEnabled = configuration.isQueryEnabled();
boolean queryEnabled = newConfiguration.isQueryEnabled();
if (queryAlreadyEnabled && (!queryEnabled || queryPortChanged)) {
this.cm.close(new InetSocketAddress(
configuration.getBind().getHostString(), configuration.getQueryPort()));
}
if (queryEnabled && (!queryAlreadyEnabled || queryPortChanged)) {
this.cm.queryBind(newConfiguration.getBind().getHostString(),
newConfiguration.getQueryPort());
}
commandManager.setAnnounceProxyCommands(newConfiguration.isAnnounceProxyCommands());
ipAttemptLimiter = Ratelimiters.createWithMilliseconds(newConfiguration.getLoginRatelimit());
this.configuration = newConfiguration;
eventManager.fireAndForget(new ProxyReloadEvent());
return true;
}
/**
* Shuts down the proxy, kicking players with the specified reason.
*
* @param explicitExit whether the user explicitly shut down the proxy
* @param reason message to kick online players with
*/
public void shutdown(boolean explicitExit, Component reason) {
if (eventManager == null || pluginManager == null || cm == null || scheduler == null) {
throw new AssertionError();
}
if (!shutdownInProgress.compareAndSet(false, true)) {
return;
}
Runnable shutdownProcess = () -> {
logger.info("Shutting down the proxy...");
// Shutdown the connection manager, this should be
// done first to refuse new connections
cm.shutdown();
try {
eventManager.fire(new ProxyPreShutdownEvent())
.toCompletableFuture()
.get(PRE_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS);
} catch (TimeoutException ignored) {
logger.warn("Your plugins took over {} seconds during pre shutdown.",
PRE_SHUTDOWN_TIMEOUT);
} catch (ExecutionException ee) {
logger.error("Exception in ProxyPreShutdownEvent handler; continuing shutdown.", ee);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
logger.warn("Interrupted while waiting for ProxyPreShutdownEvent; continuing shutdown.");
}
ImmutableList<ConnectedPlayer> players = ImmutableList.copyOf(connectionsByUuid.values());
for (ConnectedPlayer player : players) {
player.disconnect(reason);
}
try {
boolean timedOut = false;
try {
// Wait for the connections finish tearing down, this
// makes sure that all the disconnect events are being fired
CompletableFuture<Void> playersTeardownFuture = CompletableFuture.allOf(players.stream()
.map(ConnectedPlayer::getTeardownFuture)
.toArray((IntFunction<CompletableFuture<Void>[]>) CompletableFuture[]::new));
playersTeardownFuture.get(10, TimeUnit.SECONDS);
} catch (TimeoutException e) {
timedOut = true;
} catch (ExecutionException e) {
timedOut = true;
logger.error("Exception while tearing down player connections", e);
}
eventManager.fire(new ProxyShutdownEvent()).join();
timedOut = !scheduler.shutdown() || timedOut;
if (timedOut) {
logger.error("Your plugins took over 10 seconds to shut down.");
}
} catch (InterruptedException e) {
// Not much we can do about this...
Thread.currentThread().interrupt();
}
// Since we manually removed the shutdown hook, we need to handle the shutdown ourselves.
LogManager.shutdown();
shutdown = true;
if (explicitExit) {
System.exit(0);
}
};
if (explicitExit) {
Thread thread = new Thread(shutdownProcess);
thread.start();
} else {
shutdownProcess.run();
}
}
/**
* Calls {@link #shutdown(boolean, Component)} with the default reason "Proxy shutting down."
*
* @param explicitExit whether the user explicitly shut down the proxy
*/
public void shutdown(boolean explicitExit) {
shutdown(explicitExit, Component.translatable("velocity.kick.shutdown"));
}
@Override
public void shutdown(Component reason) {
shutdown(true, reason);
}
@Override
public void shutdown() {
shutdown(true);
}
@Override
public void closeListeners() {
this.cm.closeEndpoints(false);
}
public HttpClient createHttpClient() {
return cm.createHttpClient();
}
public @MonotonicNonNull Ratelimiter<InetAddress> getIpAttemptLimiter() {
return ipAttemptLimiter;
}
public @MonotonicNonNull Ratelimiter<UUID> getCommandRateLimiter() {
return commandRateLimiter;
}
public @MonotonicNonNull Ratelimiter<UUID> getTabCompleteRateLimiter() {
return tabCompleteRateLimiter;
}
/**
* Checks if the {@code connection} can be registered with the proxy.
*
* @param connection the connection to check
* @return {@code true} if we can register the connection, {@code false} if not
*/
public boolean canRegisterConnection(ConnectedPlayer connection) {
if (configuration.isOnlineMode() && configuration.isOnlineModeKickExistingPlayers()) {
return true;
}
String lowerName = connection.getUsername().toLowerCase(Locale.US);
return !(connectionsByName.containsKey(lowerName)
|| connectionsByUuid.containsKey(connection.getUniqueId()));
}
/**
* Attempts to register the {@code connection} with the proxy.
*
* @param connection the connection to register
* @return {@code true} if we registered the connection, {@code false} if not
*/
public boolean registerConnection(ConnectedPlayer connection) {
String lowerName = connection.getUsername().toLowerCase(Locale.US);
if (!this.configuration.isOnlineModeKickExistingPlayers()) {
if (connectionsByName.putIfAbsent(lowerName, connection) != null) {
return false;
}
if (connectionsByUuid.putIfAbsent(connection.getUniqueId(), connection) != null) {
connectionsByName.remove(lowerName, connection);
return false;
}
} else {
ConnectedPlayer existing = connectionsByUuid.get(connection.getUniqueId());
if (existing != null) {
existing.disconnect(Component.translatable("multiplayer.disconnect.duplicate_login"));
}
// We can now replace the entries as needed.
connectionsByName.put(lowerName, connection);
connectionsByUuid.put(connection.getUniqueId(), connection);
}
return true;
}
/**
* Unregisters the given player from the proxy.
*
* @param connection the connection to unregister
*/
public void unregisterConnection(ConnectedPlayer connection) {
connectionsByName.remove(connection.getUsername().toLowerCase(Locale.US), connection);
connectionsByUuid.remove(connection.getUniqueId(), connection);
connection.disconnected();
}
@Override
public Optional<Player> getPlayer(String username) {
Preconditions.checkNotNull(username, "username");
return Optional.ofNullable(connectionsByName.get(username.toLowerCase(Locale.US)));
}
@Override
public Optional<Player> getPlayer(UUID uuid) {
Preconditions.checkNotNull(uuid, "uuid");
return Optional.ofNullable(connectionsByUuid.get(uuid));
}
@Override
public Collection<Player> matchPlayer(String partialName) {
Objects.requireNonNull(partialName);
return getAllPlayers().stream().filter(p -> p.getUsername()
.regionMatches(true, 0, partialName, 0, partialName.length()))
.collect(Collectors.toList());
}
@Override
public Collection<RegisteredServer> matchServer(String partialName) {
Objects.requireNonNull(partialName);
return getAllServers().stream().filter(s -> s.getServerInfo().getName()
.regionMatches(true, 0, partialName, 0, partialName.length()))
.collect(Collectors.toList());
}
@Override
public Collection<Player> getAllPlayers() {
return ImmutableList.copyOf(connectionsByUuid.values());
}
@Override
public int getPlayerCount() {
return connectionsByUuid.size();
}
@Override
public Optional<RegisteredServer> getServer(String name) {
return servers.getServer(name);
}
@Override
public Collection<RegisteredServer> getAllServers() {
return servers.getAllServers();
}
@Override
public RegisteredServer createRawRegisteredServer(ServerInfo server) {
return servers.createRawRegisteredServer(server);
}
@Override
public RegisteredServer registerServer(ServerInfo server) {
return servers.register(server);
}
@Override
public void unregisterServer(ServerInfo server) {
servers.unregister(server);
}
@Override
public VelocityConsole getConsoleCommandSource() {
return console;
}
@Override
public PluginManager getPluginManager() {
return pluginManager;
}
@Override
public VelocityEventManager getEventManager() {
return eventManager;
}
@Override
public VelocityScheduler getScheduler() {
return scheduler;
}
@Override
public VelocityChannelRegistrar getChannelRegistrar() {
return channelRegistrar;
}
@Override
public boolean isShuttingDown() {
return shutdownInProgress.get();
}
@Override
public InetSocketAddress getBoundAddress() {
if (configuration == null) {
throw new IllegalStateException(
"No configuration"); // even though you'll never get the chance... heh, heh
}
return configuration.getBind();
}
@Override
public @NonNull Iterable<? extends Audience> audiences() {
Collection<Audience> audiences = new ArrayList<>(this.getPlayerCount() + 1);
audiences.add(this.console);
audiences.addAll(this.getAllPlayers());
return audiences;
}
/**
* Returns a Gson instance for use in serializing server ping instances.
*
* @param version the protocol version in use
* @return the Gson instance
*/
public static Gson getPingGsonInstance(ProtocolVersion version) {
if (version == ProtocolVersion.UNKNOWN
|| version.noLessThan(ProtocolVersion.MINECRAFT_1_20_3)) {
return MODERN_PING_SERIALIZER;
}
if (version.noLessThan(ProtocolVersion.MINECRAFT_1_16)) {
return PRE_1_20_3_PING_SERIALIZER;
}
return PRE_1_16_PING_SERIALIZER;
}
@Override
public ResourcePackInfo.Builder createResourcePackBuilder(String url) {
return new VelocityResourcePackInfo.BuilderImpl(url);
}
}