diff --git a/proxy/src/main/java/com/velocitypowered/proxy/Velocity.java b/proxy/src/main/java/com/velocitypowered/proxy/Velocity.java index 8ab722a2e..9c1ee307f 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/Velocity.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/Velocity.java @@ -21,7 +21,7 @@ public class Velocity { startTime = System.currentTimeMillis(); logger.info("Booting up Velocity..."); - final VelocityServer server = VelocityServer.getServer(); + VelocityServer server = new VelocityServer(); server.start(); Runtime.getRuntime().addShutdownHook(new Thread(server::shutdown, "Shutdown thread")); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java b/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java index 95a05d7bb..13fccef60 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java @@ -51,7 +51,6 @@ import java.util.concurrent.atomic.AtomicBoolean; public class VelocityServer implements ProxyServer { private static final Logger logger = LogManager.getLogger(VelocityServer.class); - private static final VelocityServer INSTANCE = new VelocityServer(); public static final Gson GSON = new GsonBuilder() .registerTypeHierarchyAdapter(Component.class, new GsonComponentSerializer()) .registerTypeHierarchyAdapter(Favicon.class, new FaviconSerializer()) @@ -85,14 +84,10 @@ public class VelocityServer implements ProxyServer { private VelocityScheduler scheduler; private VelocityChannelRegistrar channelRegistrar; - private VelocityServer() { + VelocityServer() { commandManager.register(new VelocityCommand(), "velocity"); - commandManager.register(new ServerCommand(), "server"); - commandManager.register(new ShutdownCommand(), "shutdown", "end"); - } - - public static VelocityServer getServer() { - return INSTANCE; + commandManager.register(new ServerCommand(this), "server"); + commandManager.register(new ShutdownCommand(this), "shutdown", "end"); } public KeyPair getServerKeyPair() { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/ServerCommand.java b/proxy/src/main/java/com/velocitypowered/proxy/command/ServerCommand.java index f9d6ac460..b42a9ed26 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/ServerCommand.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/ServerCommand.java @@ -4,9 +4,9 @@ import com.google.common.collect.ImmutableList; import com.velocitypowered.api.command.Command; import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.ServerConnection; import com.velocitypowered.api.proxy.server.ServerInfo; -import com.velocitypowered.proxy.VelocityServer; import net.kyori.text.TextComponent; import net.kyori.text.event.ClickEvent; import net.kyori.text.event.HoverEvent; @@ -17,6 +17,12 @@ import java.util.Optional; import java.util.stream.Collectors; public class ServerCommand implements Command { + private final ProxyServer server; + + public ServerCommand(ProxyServer server) { + this.server = server; + } + @Override public void execute(CommandSource source, String[] args) { if (!(source instanceof Player)) { @@ -28,13 +34,13 @@ public class ServerCommand implements Command { if (args.length == 1) { // Trying to connect to a server. String serverName = args[0]; - Optional server = VelocityServer.getServer().getServerInfo(serverName); - if (!server.isPresent()) { + Optional toConnect = server.getServerInfo(serverName); + if (!toConnect.isPresent()) { player.sendMessage(TextComponent.of("Server " + serverName + " doesn't exist.", TextColor.RED)); return; } - player.createConnectionRequest(server.get()).fireAndForget(); + player.createConnectionRequest(toConnect.get()).fireAndForget(); } else { String currentServer = player.getCurrentServer().map(ServerConnection::getServerInfo).map(ServerInfo::getName) .orElse(""); @@ -42,7 +48,7 @@ public class ServerCommand implements Command { // Assemble the list of servers as components TextComponent.Builder serverListBuilder = TextComponent.builder("Available servers: ").color(TextColor.YELLOW); - List infos = ImmutableList.copyOf(VelocityServer.getServer().getAllServers()); + List infos = ImmutableList.copyOf(server.getAllServers()); for (int i = 0; i < infos.size(); i++) { ServerInfo serverInfo = infos.get(i); TextComponent infoComponent = TextComponent.of(serverInfo.getName()); @@ -67,11 +73,11 @@ public class ServerCommand implements Command { @Override public List suggest(CommandSource source, String[] currentArgs) { if (currentArgs.length == 0) { - return VelocityServer.getServer().getAllServers().stream() + return server.getAllServers().stream() .map(ServerInfo::getName) .collect(Collectors.toList()); } else if (currentArgs.length == 1) { - return VelocityServer.getServer().getAllServers().stream() + return server.getAllServers().stream() .map(ServerInfo::getName) .filter(name -> name.regionMatches(true, 0, currentArgs[0], 0, currentArgs[0].length())) .collect(Collectors.toList()); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/ShutdownCommand.java b/proxy/src/main/java/com/velocitypowered/proxy/command/ShutdownCommand.java index 41eb3135a..7f60c81ff 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/ShutdownCommand.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/ShutdownCommand.java @@ -7,12 +7,18 @@ import net.kyori.text.TextComponent; import net.kyori.text.format.TextColor; public class ShutdownCommand implements Command { + private final VelocityServer server; + + public ShutdownCommand(VelocityServer server) { + this.server = server; + } + @Override public void execute(CommandSource source, String[] args) { - if (source != VelocityServer.getServer().getConsoleCommandSource()) { + if (source != server.getConsoleCommandSource()) { source.sendMessage(TextComponent.of("You are not allowed to use this command.", TextColor.RED)); return; } - VelocityServer.getServer().shutdown(); + server.shutdown(); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java index a6ec95604..6612a9af8 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java @@ -45,9 +45,11 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { private MinecraftSessionHandler sessionHandler; private int protocolVersion; private MinecraftConnectionAssociation association; + private final VelocityServer server; - public MinecraftConnection(Channel channel) { + public MinecraftConnection(Channel channel, VelocityServer server) { this.channel = channel; + this.server = server; this.state = StateRegistry.HANDSHAKE; } @@ -192,7 +194,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { return; } - int level = VelocityServer.getServer().getConfiguration().getCompressionLevel(); + int level = server.getConfiguration().getCompressionLevel(); VelocityCompressor compressor = Natives.compressor.get().create(level); MinecraftCompressEncoder encoder = new MinecraftCompressEncoder(threshold, compressor); MinecraftCompressDecoder decoder = new MinecraftCompressDecoder(threshold, compressor); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java index 639fe070d..60ed678c0 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java @@ -13,16 +13,17 @@ import com.velocitypowered.proxy.protocol.util.PluginMessageUtil; import io.netty.buffer.ByteBuf; public class BackendPlaySessionHandler implements MinecraftSessionHandler { + private final VelocityServer server; private final VelocityServerConnection connection; - public BackendPlaySessionHandler(VelocityServerConnection connection) { + public BackendPlaySessionHandler(VelocityServer server, VelocityServerConnection connection) { + this.server = server; this.connection = connection; } @Override public void activated() { - VelocityServer.getServer().getEventManager().fireAndForget(new ServerConnectedEvent(connection.getPlayer(), - connection.getServerInfo())); + server.getEventManager().fireAndForget(new ServerConnectedEvent(connection.getPlayer(), connection.getServerInfo())); } @Override @@ -67,8 +68,8 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler { return; } - MessageHandler.ForwardStatus status = VelocityServer.getServer().getChannelRegistrar().handlePluginMessage( - connection, ChannelSide.FROM_SERVER, pm); + MessageHandler.ForwardStatus status = server.getChannelRegistrar().handlePluginMessage(connection, + ChannelSide.FROM_SERVER, pm); if (status == MessageHandler.ForwardStatus.FORWARD) { connection.getPlayer().getConnection().write(pm); } @@ -97,14 +98,13 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler { private boolean canForwardPluginMessage(PluginMessage message) { ClientPlaySessionHandler playerHandler = (ClientPlaySessionHandler) connection.getPlayer().getConnection().getSessionHandler(); + boolean isMCMessage; if (connection.getMinecraftConnection().getProtocolVersion() <= ProtocolConstants.MINECRAFT_1_12_2) { - return message.getChannel().startsWith("MC|") || - playerHandler.getClientPluginMsgChannels().contains(message.getChannel()) || - VelocityServer.getServer().getChannelRegistrar().registered(message.getChannel()); + isMCMessage = message.getChannel().startsWith("MC|"); } else { - return message.getChannel().startsWith("minecraft:") || - playerHandler.getClientPluginMsgChannels().contains(message.getChannel()) || - VelocityServer.getServer().getChannelRegistrar().registered(message.getChannel()); + isMCMessage = message.getChannel().startsWith("minecraft:"); } + return isMCMessage || playerHandler.getClientPluginMsgChannels().contains(message.getChannel()) || + server.getChannelRegistrar().registered(message.getChannel()); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java index feb28ee2e..fba410951 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java @@ -26,10 +26,12 @@ import java.security.NoSuchAlgorithmException; import java.util.concurrent.CompletableFuture; public class LoginSessionHandler implements MinecraftSessionHandler { + private final VelocityServer server; private final VelocityServerConnection connection; private boolean informationForwarded; - public LoginSessionHandler(VelocityServerConnection connection) { + public LoginSessionHandler(VelocityServer server, VelocityServerConnection connection) { + this.server = server; this.connection = connection; } @@ -39,7 +41,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler { throw new IllegalStateException("Backend server is online-mode!"); } else if (packet instanceof LoginPluginMessage) { LoginPluginMessage message = (LoginPluginMessage) packet; - VelocityConfiguration configuration = VelocityServer.getServer().getConfiguration(); + VelocityConfiguration configuration = server.getConfiguration(); if (configuration.getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN && message.getChannel().equals(VelocityConstants.VELOCITY_IP_FORWARDING_CHANNEL)) { LoginPluginResponse response = new LoginPluginResponse(); @@ -67,8 +69,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler { SetCompression sc = (SetCompression) packet; connection.getMinecraftConnection().setCompressionThreshold(sc.getThreshold()); } else if (packet instanceof ServerLoginSuccess) { - if (VelocityServer.getServer().getConfiguration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN && - !informationForwarded) { + if (server.getConfiguration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN && !informationForwarded) { doNotify(ConnectionRequestResults.forDisconnect( TextComponent.of("Your server did not send a forwarding request to the proxy. Is it set up correctly?"))); connection.disconnect(); @@ -80,14 +81,14 @@ public class LoginSessionHandler implements MinecraftSessionHandler { VelocityServerConnection existingConnection = connection.getPlayer().getConnectedServer(); if (existingConnection == null) { // Strap on the play session handler - connection.getPlayer().getConnection().setSessionHandler(new ClientPlaySessionHandler(connection.getPlayer())); + connection.getPlayer().getConnection().setSessionHandler(new ClientPlaySessionHandler(server, connection.getPlayer())); } else { // The previous server connection should become obsolete. existingConnection.disconnect(); } doNotify(ConnectionRequestResults.SUCCESSFUL); - connection.getMinecraftConnection().setSessionHandler(new BackendPlaySessionHandler(connection)); + connection.getMinecraftConnection().setSessionHandler(new BackendPlaySessionHandler(server, connection)); connection.getPlayer().setConnectedServer(connection); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java index 23e4f6062..367e33463 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java @@ -26,6 +26,7 @@ import io.netty.util.AttributeKey; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; +import static com.velocitypowered.proxy.VelocityServer.GSON; import static com.velocitypowered.proxy.network.Connections.FRAME_DECODER; import static com.velocitypowered.proxy.network.Connections.FRAME_ENCODER; import static com.velocitypowered.proxy.network.Connections.HANDLER; @@ -63,7 +64,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation, .addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolConstants.Direction.SERVERBOUND)); ch.attr(CONNECTION_NOTIFIER).set(result); - MinecraftConnection connection = new MinecraftConnection(ch); + MinecraftConnection connection = new MinecraftConnection(ch, server); connection.setState(StateRegistry.HANDSHAKE); connection.setAssociation(VelocityServerConnection.this); ch.pipeline().addLast(HANDLER, connection); @@ -77,7 +78,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation, minecraftConnection = future.channel().pipeline().get(MinecraftConnection.class); // Kick off the connection process - minecraftConnection.setSessionHandler(new LoginSessionHandler(VelocityServerConnection.this)); + minecraftConnection.setSessionHandler(new LoginSessionHandler(server, VelocityServerConnection.this)); startHandshake(); } else { result.completeExceptionally(future.cause()); @@ -94,11 +95,11 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation, return serverInfo.getAddress().getHostString() + "\0" + proxyPlayer.getRemoteAddress().getHostString() + "\0" + proxyPlayer.getProfile().getId() + "\0" + - VelocityServer.GSON.toJson(proxyPlayer.getProfile().getProperties()); + GSON.toJson(proxyPlayer.getProfile().getProperties()); } private void startHandshake() { - PlayerInfoForwarding forwardingMode = VelocityServer.getServer().getConfiguration().getPlayerInfoForwardingMode(); + PlayerInfoForwarding forwardingMode = server.getConfiguration().getPlayerInfoForwardingMode(); // Initiate a handshake. Handshake handshake = new Handshake(); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java index 82a4e0384..9c36766ef 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java @@ -32,18 +32,20 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { private boolean spawned = false; private final List serverBossBars = new ArrayList<>(); private final Set clientPluginMsgChannels = new HashSet<>(); + private final VelocityServer server; - public ClientPlaySessionHandler(ConnectedPlayer player) { + public ClientPlaySessionHandler(VelocityServer server, ConnectedPlayer player) { this.player = player; + this.server = server; } @Override public void activated() { PluginMessage message; if (player.getProtocolVersion() >= ProtocolConstants.MINECRAFT_1_13) { - message = PluginMessageUtil.constructChannelsPacket("minecraft:register", VelocityServer.getServer().getChannelRegistrar().getModernChannelIds()); + message = PluginMessageUtil.constructChannelsPacket("minecraft:register", server.getChannelRegistrar().getModernChannelIds()); } else { - message = PluginMessageUtil.constructChannelsPacket("REGISTER", VelocityServer.getServer().getChannelRegistrar().getIdsForLegacyConnections()); + message = PluginMessageUtil.constructChannelsPacket("REGISTER", server.getChannelRegistrar().getIdsForLegacyConnections()); } player.getConnection().write(message); } @@ -72,7 +74,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { String msg = ((Chat) packet).getMessage(); if (msg.startsWith("/")) { try { - if (!VelocityServer.getServer().getCommandManager().execute(player, msg.substring(1))) { + if (!server.getCommandManager().execute(player, msg.substring(1))) { player.getConnectedServer().getMinecraftConnection().write(chat); } } catch (Exception e) { @@ -92,7 +94,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { if (!req.isAssumeCommand() && lastSpace != -1) { String command = req.getCommand().substring(1); try { - Optional> offers = VelocityServer.getServer().getCommandManager().offerSuggestions(player, command); + Optional> offers = server.getCommandManager().offerSuggestions(player, command); if (offers.isPresent()) { TabCompleteResponse response = new TabCompleteResponse(); response.setTransactionId(req.getTransactionId()); @@ -131,7 +133,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { @Override public void disconnected() { player.teardown(); - VelocityServer.getServer().getEventManager().fireAndForget(new DisconnectEvent(player)); + server.getEventManager().fireAndForget(new DisconnectEvent(player)); } @Override @@ -181,9 +183,9 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { // Tell the server about this client's plugin messages. Velocity will forward them on to the client. Collection toRegister = new HashSet<>(clientPluginMsgChannels); if (player.getProtocolVersion() >= ProtocolConstants.MINECRAFT_1_13) { - toRegister.addAll(VelocityServer.getServer().getChannelRegistrar().getModernChannelIds()); + toRegister.addAll(server.getChannelRegistrar().getModernChannelIds()); } else { - toRegister.addAll(VelocityServer.getServer().getChannelRegistrar().getIdsForLegacyConnections()); + toRegister.addAll(server.getChannelRegistrar().getIdsForLegacyConnections()); } if (!toRegister.isEmpty()) { String channel = player.getConnection().getProtocolVersion() >= ProtocolConstants.MINECRAFT_1_13 ? @@ -233,8 +235,8 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { return; } - MessageHandler.ForwardStatus status = VelocityServer.getServer().getChannelRegistrar().handlePluginMessage( - player, ChannelSide.FROM_CLIENT, packet); + MessageHandler.ForwardStatus status = server.getChannelRegistrar().handlePluginMessage(player, + ChannelSide.FROM_CLIENT, packet); if (status == MessageHandler.ForwardStatus.FORWARD) { // We're going to forward on the original packet. player.getConnectedServer().getMinecraftConnection().write(packet); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java index 4e47c3145..e82fd354f 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java @@ -6,8 +6,7 @@ import com.velocitypowered.proxy.protocol.packet.ClientSettings; import java.util.Locale; public class ClientSettingsWrapper implements PlayerSettings { - - public static PlayerSettings DEFAULT = new ClientSettingsWrapper(new ClientSettings("en_US", (byte) 10, 0, true, (short)127, 1)); + static PlayerSettings DEFAULT = new ClientSettingsWrapper(new ClientSettings("en_US", (byte) 10, 0, true, (short)127, 1)); private final ClientSettings settings; private final SkinParts parts; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java index d518e9eef..d8c6765f8 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java @@ -58,8 +58,10 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { private VelocityServerConnection connectedServer; private VelocityServerConnection connectionInFlight; private PlayerSettings settings; + private final VelocityServer server; - public ConnectedPlayer(GameProfile profile, MinecraftConnection connection, InetSocketAddress virtualHost) { + public ConnectedPlayer(VelocityServer server, GameProfile profile, MinecraftConnection connection, InetSocketAddress virtualHost) { + this.server = server; this.profile = profile; this.connection = connection; this.virtualHost = virtualHost; @@ -103,7 +105,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { public void setPlayerSettings(ClientSettings settings) { this.settings = new ClientSettingsWrapper(settings); - VelocityServer.getServer().getEventManager().fireAndForget(new PlayerSettingsChangedEvent(this, this.settings)); + server.getEventManager().fireAndForget(new PlayerSettingsChangedEvent(this, this.settings)); } @Override @@ -230,14 +232,14 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { } Optional getNextServerToTry() { - List serversToTry = VelocityServer.getServer().getConfiguration().getAttemptConnectionOrder(); + List serversToTry = server.getConfiguration().getAttemptConnectionOrder(); if (tryIndex >= serversToTry.size()) { return Optional.empty(); } String toTryName = serversToTry.get(tryIndex); tryIndex++; - return VelocityServer.getServer().getServers().getServer(toTryName); + return server.getServers().getServer(toTryName); } private CompletableFuture connect(ConnectionRequestBuilderImpl request) { @@ -255,7 +257,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { // Otherwise, initiate the connection. ServerPreConnectEvent event = new ServerPreConnectEvent(this, ServerPreConnectEvent.ServerResult.allowed(request.getServer())); - return VelocityServer.getServer().getEventManager().fire(event) + return server.getEventManager().fire(event) .thenCompose((newEvent) -> { if (!newEvent.getResult().isAllowed()) { return CompletableFuture.completedFuture( @@ -263,7 +265,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { ); } - return new VelocityServerConnection(newEvent.getResult().getInfo().get(), this, VelocityServer.getServer()).connect(); + return new VelocityServerConnection(newEvent.getResult().getInfo().get(), this, server).connect(); }); } @@ -285,7 +287,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { if (connectedServer != null) { connectedServer.disconnect(); } - VelocityServer.getServer().unregisterConnection(this); + server.unregisterConnection(this); } @Override diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java index fab30d067..5a5abaf67 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java @@ -31,7 +31,7 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler { public HandshakeSessionHandler(MinecraftConnection connection, VelocityServer server) { this.connection = Preconditions.checkNotNull(connection, "connection"); - this.server = server; + this.server = Preconditions.checkNotNull(server, "server"); } @Override @@ -53,7 +53,7 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler { case StateRegistry.STATUS_ID: connection.setState(StateRegistry.STATUS); connection.setProtocolVersion(handshake.getProtocolVersion()); - connection.setSessionHandler(new StatusSessionHandler(connection, ic)); + connection.setSessionHandler(new StatusSessionHandler(server, connection, ic)); break; case StateRegistry.LOGIN_ID: connection.setState(StateRegistry.LOGIN); @@ -65,7 +65,7 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler { } InetAddress address = ((InetSocketAddress) connection.getChannel().remoteAddress()).getAddress(); - if (!VelocityServer.getServer().getIpAttemptLimiter().attempt(address)) { + if (!server.getIpAttemptLimiter().attempt(address)) { connection.closeWith(Disconnect.create(TextComponent.of("You are logging in too fast, try again later."))); return; } @@ -85,8 +85,8 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler { return; } - VelocityServer.getServer().getEventManager().fireAndForget(new ConnectionHandshakeEvent(ic)); - connection.setSessionHandler(new LoginSessionHandler(connection, ic)); + server.getEventManager().fireAndForget(new ConnectionHandshakeEvent(ic)); + connection.setSessionHandler(new LoginSessionHandler(server, connection, ic)); break; default: throw new IllegalArgumentException("Invalid state " + handshake.getNextStatus()); @@ -100,15 +100,15 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler { private void handleLegacy(MinecraftPacket packet) { if (packet instanceof LegacyPing) { - VelocityConfiguration configuration = VelocityServer.getServer().getConfiguration(); + VelocityConfiguration configuration = server.getConfiguration(); ServerPing ping = new ServerPing( new ServerPing.Version(ProtocolConstants.MAXIMUM_GENERIC_VERSION, "Velocity " + ProtocolConstants.SUPPORTED_GENERIC_VERSION_STRING), - new ServerPing.Players(VelocityServer.getServer().getPlayerCount(), configuration.getShowMaxPlayers(), ImmutableList.of()), + new ServerPing.Players(server.getPlayerCount(), configuration.getShowMaxPlayers(), ImmutableList.of()), configuration.getMotdComponent(), null ); ProxyPingEvent event = new ProxyPingEvent(new LegacyInboundConnection(connection), ping); - VelocityServer.getServer().getEventManager().fire(event) + server.getEventManager().fire(event) .thenRunAsync(() -> { // The disconnect packet is the same as the server response one. connection.closeWith(LegacyDisconnect.fromPingResponse(LegacyPingResponse.from(event.getPing()))); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/LoginSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/LoginSessionHandler.java index 67b3cdf82..6db9f4104 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/LoginSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/LoginSessionHandler.java @@ -39,14 +39,16 @@ public class LoginSessionHandler implements MinecraftSessionHandler { private static final Logger logger = LogManager.getLogger(LoginSessionHandler.class); private static final String MOJANG_SERVER_AUTH_URL = "https://sessionserver.mojang.com/session/minecraft/hasJoined?username=%s&serverId=%s&ip=%s"; - + + private final VelocityServer server; private final MinecraftConnection inbound; private final InboundConnection apiInbound; private ServerLogin login; private byte[] verify; private int playerInfoId; - public LoginSessionHandler(MinecraftConnection inbound, InboundConnection apiInbound) { + public LoginSessionHandler(VelocityServer server, MinecraftConnection inbound, InboundConnection apiInbound) { + this.server = Preconditions.checkNotNull(server, "server"); this.inbound = Preconditions.checkNotNull(inbound, "inbound"); this.apiInbound = Preconditions.checkNotNull(apiInbound, "apiInbound"); } @@ -81,7 +83,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler { } } else if (packet instanceof EncryptionResponse) { try { - KeyPair serverKeyPair = VelocityServer.getServer().getServerKeyPair(); + KeyPair serverKeyPair = server.getServerKeyPair(); EncryptionResponse response = (EncryptionResponse) packet; byte[] decryptedVerifyToken = EncryptionUtils.decryptRsa(serverKeyPair, response.getVerifyToken()); if (!Arrays.equals(verify, decryptedVerifyToken)) { @@ -92,7 +94,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler { String serverId = EncryptionUtils.generateServerId(decryptedSharedSecret, serverKeyPair.getPublic()); String playerIp = ((InetSocketAddress) inbound.getChannel().remoteAddress()).getHostString(); - VelocityServer.getServer().getHttpClient() + server.getHttpClient() .get(new URL(String.format(MOJANG_SERVER_AUTH_URL, login.getUsername(), serverId, playerIp))) .thenAcceptAsync(profileResponse -> { if (inbound.isClosed()) { @@ -124,7 +126,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler { private void beginPreLogin() { PreLoginEvent event = new PreLoginEvent(apiInbound, login.getUsername()); - VelocityServer.getServer().getEventManager().fire(event) + server.getEventManager().fire(event) .thenRunAsync(() -> { if (inbound.isClosed()) { // The player was disconnected @@ -137,7 +139,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler { return; } - if (VelocityServer.getServer().getConfiguration().isOnlineMode() || result.isOnlineModeAllowed()) { + if (server.getConfiguration().isOnlineMode() || result.isOnlineModeAllowed()) { // Request encryption. EncryptionRequest request = generateRequest(); this.verify = Arrays.copyOf(request.getVerifyToken(), 4); @@ -153,7 +155,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler { ThreadLocalRandom.current().nextBytes(verify); EncryptionRequest request = new EncryptionRequest(); - request.setPublicKey(VelocityServer.getServer().getServerKeyPair().getPublic().getEncoded()); + request.setPublicKey(server.getServerKeyPair().getPublic().getEncoded()); request.setVerifyToken(verify); return request; } @@ -161,17 +163,17 @@ public class LoginSessionHandler implements MinecraftSessionHandler { private void initializePlayer(GameProfile profile, boolean onlineMode) { GameProfileRequestEvent profileRequestEvent = new GameProfileRequestEvent(apiInbound, profile, onlineMode); - VelocityServer.getServer().getEventManager().fire(profileRequestEvent).thenCompose(profileEvent -> { + server.getEventManager().fire(profileRequestEvent).thenCompose(profileEvent -> { // Initiate a regular connection and move over to it. - ConnectedPlayer player = new ConnectedPlayer(profileEvent.getGameProfile(), inbound, + ConnectedPlayer player = new ConnectedPlayer(server, profileEvent.getGameProfile(), inbound, apiInbound.getVirtualHost().orElse(null)); - return VelocityServer.getServer().getEventManager().fire(new PermissionsSetupEvent(player, ConnectedPlayer.DEFAULT_PERMISSIONS)) + return server.getEventManager().fire(new PermissionsSetupEvent(player, ConnectedPlayer.DEFAULT_PERMISSIONS)) .thenCompose(event -> { // wait for permissions to load, then set the players permission function player.setPermissionFunction(event.createFunction(player)); // then call & wait for the login event - return VelocityServer.getServer().getEventManager().fire(new LoginEvent(player)); + return server.getEventManager().fire(new LoginEvent(player)); }) // then complete the connection .thenAcceptAsync(event -> { @@ -198,7 +200,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler { return; } - int threshold = VelocityServer.getServer().getConfiguration().getCompressionThreshold(); + int threshold = server.getConfiguration().getCompressionThreshold(); if (threshold >= 0) { inbound.write(new SetCompression(threshold)); inbound.setCompressionThreshold(threshold); @@ -212,7 +214,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler { inbound.setAssociation(player); inbound.setState(StateRegistry.PLAY); - if (!VelocityServer.getServer().registerConnection(player)) { + if (!server.registerConnection(player)) { inbound.closeWith(Disconnect.create(TextComponent.of("You are already on this proxy!", TextColor.RED))); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java index fb70edd02..863c32e59 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java @@ -18,10 +18,12 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; public class StatusSessionHandler implements MinecraftSessionHandler { + private final VelocityServer server; private final MinecraftConnection connection; private final InboundConnection inboundWrapper; - public StatusSessionHandler(MinecraftConnection connection, InboundConnection inboundWrapper) { + public StatusSessionHandler(VelocityServer server, MinecraftConnection connection, InboundConnection inboundWrapper) { + this.server = server; this.connection = connection; this.inboundWrapper = inboundWrapper; } @@ -37,20 +39,20 @@ public class StatusSessionHandler implements MinecraftSessionHandler { return; } - VelocityConfiguration configuration = VelocityServer.getServer().getConfiguration(); + VelocityConfiguration configuration = server.getConfiguration(); // Status request int shownVersion = ProtocolConstants.isSupported(connection.getProtocolVersion()) ? connection.getProtocolVersion() : ProtocolConstants.MAXIMUM_GENERIC_VERSION; ServerPing initialPing = new ServerPing( new ServerPing.Version(shownVersion, "Velocity " + ProtocolConstants.SUPPORTED_GENERIC_VERSION_STRING), - new ServerPing.Players(VelocityServer.getServer().getPlayerCount(), configuration.getShowMaxPlayers(), ImmutableList.of()), + new ServerPing.Players(server.getPlayerCount(), configuration.getShowMaxPlayers(), ImmutableList.of()), configuration.getMotdComponent(), configuration.getFavicon() ); ProxyPingEvent event = new ProxyPingEvent(inboundWrapper, initialPing); - VelocityServer.getServer().getEventManager().fire(event) + server.getEventManager().fire(event) .thenRunAsync(() -> { StatusResponse response = new StatusResponse(); response.setStatus(VelocityServer.GSON.toJson(event.getPing())); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java b/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java index 1d283e7a0..fb08b63a8 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java @@ -84,7 +84,7 @@ public final class ConnectionManager { .addLast(MINECRAFT_DECODER, new MinecraftDecoder(ProtocolConstants.Direction.SERVERBOUND)) .addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolConstants.Direction.CLIENTBOUND)); - final MinecraftConnection connection = new MinecraftConnection(ch); + final MinecraftConnection connection = new MinecraftConnection(ch, server); connection.setState(StateRegistry.HANDSHAKE); connection.setSessionHandler(new HandshakeSessionHandler(connection, server)); ch.pipeline().addLast(Connections.HANDLER, connection); @@ -109,7 +109,7 @@ public final class ConnectionManager { Bootstrap bootstrap = new Bootstrap() .channel(transportType.datagramChannelClass) .group(this.workerGroup) - .handler(new GS4QueryHandler()) + .handler(new GS4QueryHandler(server)) .localAddress(hostname, port); bootstrap.bind() .addListener((ChannelFutureListener) future -> { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GS4QueryHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GS4QueryHandler.java index b0c5a838b..df093d78d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GS4QueryHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GS4QueryHandler.java @@ -42,10 +42,16 @@ public class GS4QueryHandler extends SimpleChannelInboundHandler "hostip" ); - private final static Cache sessions = CacheBuilder.newBuilder() + private final Cache sessions = CacheBuilder.newBuilder() .expireAfterWrite(30, TimeUnit.SECONDS) .build(); + private final VelocityServer server; + + public GS4QueryHandler(VelocityServer server) { + this.server = server; + } + @Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { ByteBuf queryMessage = msg.content(); @@ -96,7 +102,6 @@ public class GS4QueryHandler extends SimpleChannelInboundHandler queryResponse.writeInt(sessionId); // Fetch information - VelocityServer server = VelocityServer.getServer(); Collection players = server.getAllPlayers(); // Start writing the response