3
0
Mirror von https://github.com/PaperMC/Velocity.git synchronisiert 2024-12-24 23:30:26 +01:00

Removed all references to the static VelocityServer instance.

Dieser Commit ist enthalten in:
Andrew Steinborn 2018-08-27 00:45:00 -04:00
Ursprung fead4783af
Commit 6f8dae3a7e
16 geänderte Dateien mit 112 neuen und 89 gelöschten Zeilen

Datei anzeigen

@ -21,7 +21,7 @@ public class Velocity {
startTime = System.currentTimeMillis(); startTime = System.currentTimeMillis();
logger.info("Booting up Velocity..."); logger.info("Booting up Velocity...");
final VelocityServer server = VelocityServer.getServer(); VelocityServer server = new VelocityServer();
server.start(); server.start();
Runtime.getRuntime().addShutdownHook(new Thread(server::shutdown, "Shutdown thread")); Runtime.getRuntime().addShutdownHook(new Thread(server::shutdown, "Shutdown thread"));

Datei anzeigen

@ -51,7 +51,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
public class VelocityServer implements ProxyServer { public class VelocityServer implements ProxyServer {
private static final Logger logger = LogManager.getLogger(VelocityServer.class); private static final Logger logger = LogManager.getLogger(VelocityServer.class);
private static final VelocityServer INSTANCE = new VelocityServer();
public static final Gson GSON = new GsonBuilder() public static final Gson GSON = new GsonBuilder()
.registerTypeHierarchyAdapter(Component.class, new GsonComponentSerializer()) .registerTypeHierarchyAdapter(Component.class, new GsonComponentSerializer())
.registerTypeHierarchyAdapter(Favicon.class, new FaviconSerializer()) .registerTypeHierarchyAdapter(Favicon.class, new FaviconSerializer())
@ -85,14 +84,10 @@ public class VelocityServer implements ProxyServer {
private VelocityScheduler scheduler; private VelocityScheduler scheduler;
private VelocityChannelRegistrar channelRegistrar; private VelocityChannelRegistrar channelRegistrar;
private VelocityServer() { VelocityServer() {
commandManager.register(new VelocityCommand(), "velocity"); commandManager.register(new VelocityCommand(), "velocity");
commandManager.register(new ServerCommand(), "server"); commandManager.register(new ServerCommand(this), "server");
commandManager.register(new ShutdownCommand(), "shutdown", "end"); commandManager.register(new ShutdownCommand(this), "shutdown", "end");
}
public static VelocityServer getServer() {
return INSTANCE;
} }
public KeyPair getServerKeyPair() { public KeyPair getServerKeyPair() {

Datei anzeigen

@ -4,9 +4,9 @@ import com.google.common.collect.ImmutableList;
import com.velocitypowered.api.command.Command; import com.velocitypowered.api.command.Command;
import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.ServerConnection; import com.velocitypowered.api.proxy.ServerConnection;
import com.velocitypowered.api.proxy.server.ServerInfo; import com.velocitypowered.api.proxy.server.ServerInfo;
import com.velocitypowered.proxy.VelocityServer;
import net.kyori.text.TextComponent; import net.kyori.text.TextComponent;
import net.kyori.text.event.ClickEvent; import net.kyori.text.event.ClickEvent;
import net.kyori.text.event.HoverEvent; import net.kyori.text.event.HoverEvent;
@ -17,6 +17,12 @@ import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ServerCommand implements Command { public class ServerCommand implements Command {
private final ProxyServer server;
public ServerCommand(ProxyServer server) {
this.server = server;
}
@Override @Override
public void execute(CommandSource source, String[] args) { public void execute(CommandSource source, String[] args) {
if (!(source instanceof Player)) { if (!(source instanceof Player)) {
@ -28,13 +34,13 @@ public class ServerCommand implements Command {
if (args.length == 1) { if (args.length == 1) {
// Trying to connect to a server. // Trying to connect to a server.
String serverName = args[0]; String serverName = args[0];
Optional<ServerInfo> server = VelocityServer.getServer().getServerInfo(serverName); Optional<ServerInfo> toConnect = server.getServerInfo(serverName);
if (!server.isPresent()) { if (!toConnect.isPresent()) {
player.sendMessage(TextComponent.of("Server " + serverName + " doesn't exist.", TextColor.RED)); player.sendMessage(TextComponent.of("Server " + serverName + " doesn't exist.", TextColor.RED));
return; return;
} }
player.createConnectionRequest(server.get()).fireAndForget(); player.createConnectionRequest(toConnect.get()).fireAndForget();
} else { } else {
String currentServer = player.getCurrentServer().map(ServerConnection::getServerInfo).map(ServerInfo::getName) String currentServer = player.getCurrentServer().map(ServerConnection::getServerInfo).map(ServerInfo::getName)
.orElse("<unknown>"); .orElse("<unknown>");
@ -42,7 +48,7 @@ public class ServerCommand implements Command {
// Assemble the list of servers as components // Assemble the list of servers as components
TextComponent.Builder serverListBuilder = TextComponent.builder("Available servers: ").color(TextColor.YELLOW); TextComponent.Builder serverListBuilder = TextComponent.builder("Available servers: ").color(TextColor.YELLOW);
List<ServerInfo> infos = ImmutableList.copyOf(VelocityServer.getServer().getAllServers()); List<ServerInfo> infos = ImmutableList.copyOf(server.getAllServers());
for (int i = 0; i < infos.size(); i++) { for (int i = 0; i < infos.size(); i++) {
ServerInfo serverInfo = infos.get(i); ServerInfo serverInfo = infos.get(i);
TextComponent infoComponent = TextComponent.of(serverInfo.getName()); TextComponent infoComponent = TextComponent.of(serverInfo.getName());
@ -67,11 +73,11 @@ public class ServerCommand implements Command {
@Override @Override
public List<String> suggest(CommandSource source, String[] currentArgs) { public List<String> suggest(CommandSource source, String[] currentArgs) {
if (currentArgs.length == 0) { if (currentArgs.length == 0) {
return VelocityServer.getServer().getAllServers().stream() return server.getAllServers().stream()
.map(ServerInfo::getName) .map(ServerInfo::getName)
.collect(Collectors.toList()); .collect(Collectors.toList());
} else if (currentArgs.length == 1) { } else if (currentArgs.length == 1) {
return VelocityServer.getServer().getAllServers().stream() return server.getAllServers().stream()
.map(ServerInfo::getName) .map(ServerInfo::getName)
.filter(name -> name.regionMatches(true, 0, currentArgs[0], 0, currentArgs[0].length())) .filter(name -> name.regionMatches(true, 0, currentArgs[0], 0, currentArgs[0].length()))
.collect(Collectors.toList()); .collect(Collectors.toList());

Datei anzeigen

@ -7,12 +7,18 @@ import net.kyori.text.TextComponent;
import net.kyori.text.format.TextColor; import net.kyori.text.format.TextColor;
public class ShutdownCommand implements Command { public class ShutdownCommand implements Command {
private final VelocityServer server;
public ShutdownCommand(VelocityServer server) {
this.server = server;
}
@Override @Override
public void execute(CommandSource source, String[] args) { 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)); source.sendMessage(TextComponent.of("You are not allowed to use this command.", TextColor.RED));
return; return;
} }
VelocityServer.getServer().shutdown(); server.shutdown();
} }
} }

Datei anzeigen

@ -45,9 +45,11 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter {
private MinecraftSessionHandler sessionHandler; private MinecraftSessionHandler sessionHandler;
private int protocolVersion; private int protocolVersion;
private MinecraftConnectionAssociation association; private MinecraftConnectionAssociation association;
private final VelocityServer server;
public MinecraftConnection(Channel channel) { public MinecraftConnection(Channel channel, VelocityServer server) {
this.channel = channel; this.channel = channel;
this.server = server;
this.state = StateRegistry.HANDSHAKE; this.state = StateRegistry.HANDSHAKE;
} }
@ -192,7 +194,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter {
return; return;
} }
int level = VelocityServer.getServer().getConfiguration().getCompressionLevel(); int level = server.getConfiguration().getCompressionLevel();
VelocityCompressor compressor = Natives.compressor.get().create(level); VelocityCompressor compressor = Natives.compressor.get().create(level);
MinecraftCompressEncoder encoder = new MinecraftCompressEncoder(threshold, compressor); MinecraftCompressEncoder encoder = new MinecraftCompressEncoder(threshold, compressor);
MinecraftCompressDecoder decoder = new MinecraftCompressDecoder(threshold, compressor); MinecraftCompressDecoder decoder = new MinecraftCompressDecoder(threshold, compressor);

Datei anzeigen

@ -13,16 +13,17 @@ import com.velocitypowered.proxy.protocol.util.PluginMessageUtil;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
public class BackendPlaySessionHandler implements MinecraftSessionHandler { public class BackendPlaySessionHandler implements MinecraftSessionHandler {
private final VelocityServer server;
private final VelocityServerConnection connection; private final VelocityServerConnection connection;
public BackendPlaySessionHandler(VelocityServerConnection connection) { public BackendPlaySessionHandler(VelocityServer server, VelocityServerConnection connection) {
this.server = server;
this.connection = connection; this.connection = connection;
} }
@Override @Override
public void activated() { public void activated() {
VelocityServer.getServer().getEventManager().fireAndForget(new ServerConnectedEvent(connection.getPlayer(), server.getEventManager().fireAndForget(new ServerConnectedEvent(connection.getPlayer(), connection.getServerInfo()));
connection.getServerInfo()));
} }
@Override @Override
@ -67,8 +68,8 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
return; return;
} }
MessageHandler.ForwardStatus status = VelocityServer.getServer().getChannelRegistrar().handlePluginMessage( MessageHandler.ForwardStatus status = server.getChannelRegistrar().handlePluginMessage(connection,
connection, ChannelSide.FROM_SERVER, pm); ChannelSide.FROM_SERVER, pm);
if (status == MessageHandler.ForwardStatus.FORWARD) { if (status == MessageHandler.ForwardStatus.FORWARD) {
connection.getPlayer().getConnection().write(pm); connection.getPlayer().getConnection().write(pm);
} }
@ -97,14 +98,13 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
private boolean canForwardPluginMessage(PluginMessage message) { private boolean canForwardPluginMessage(PluginMessage message) {
ClientPlaySessionHandler playerHandler = ClientPlaySessionHandler playerHandler =
(ClientPlaySessionHandler) connection.getPlayer().getConnection().getSessionHandler(); (ClientPlaySessionHandler) connection.getPlayer().getConnection().getSessionHandler();
boolean isMCMessage;
if (connection.getMinecraftConnection().getProtocolVersion() <= ProtocolConstants.MINECRAFT_1_12_2) { if (connection.getMinecraftConnection().getProtocolVersion() <= ProtocolConstants.MINECRAFT_1_12_2) {
return message.getChannel().startsWith("MC|") || isMCMessage = message.getChannel().startsWith("MC|");
playerHandler.getClientPluginMsgChannels().contains(message.getChannel()) ||
VelocityServer.getServer().getChannelRegistrar().registered(message.getChannel());
} else { } else {
return message.getChannel().startsWith("minecraft:") || isMCMessage = message.getChannel().startsWith("minecraft:");
playerHandler.getClientPluginMsgChannels().contains(message.getChannel()) || }
VelocityServer.getServer().getChannelRegistrar().registered(message.getChannel()); return isMCMessage || playerHandler.getClientPluginMsgChannels().contains(message.getChannel()) ||
} server.getChannelRegistrar().registered(message.getChannel());
} }
} }

Datei anzeigen

@ -26,10 +26,12 @@ import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
public class LoginSessionHandler implements MinecraftSessionHandler { public class LoginSessionHandler implements MinecraftSessionHandler {
private final VelocityServer server;
private final VelocityServerConnection connection; private final VelocityServerConnection connection;
private boolean informationForwarded; private boolean informationForwarded;
public LoginSessionHandler(VelocityServerConnection connection) { public LoginSessionHandler(VelocityServer server, VelocityServerConnection connection) {
this.server = server;
this.connection = connection; this.connection = connection;
} }
@ -39,7 +41,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
throw new IllegalStateException("Backend server is online-mode!"); throw new IllegalStateException("Backend server is online-mode!");
} else if (packet instanceof LoginPluginMessage) { } else if (packet instanceof LoginPluginMessage) {
LoginPluginMessage message = (LoginPluginMessage) packet; LoginPluginMessage message = (LoginPluginMessage) packet;
VelocityConfiguration configuration = VelocityServer.getServer().getConfiguration(); VelocityConfiguration configuration = server.getConfiguration();
if (configuration.getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN && if (configuration.getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN &&
message.getChannel().equals(VelocityConstants.VELOCITY_IP_FORWARDING_CHANNEL)) { message.getChannel().equals(VelocityConstants.VELOCITY_IP_FORWARDING_CHANNEL)) {
LoginPluginResponse response = new LoginPluginResponse(); LoginPluginResponse response = new LoginPluginResponse();
@ -67,8 +69,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
SetCompression sc = (SetCompression) packet; SetCompression sc = (SetCompression) packet;
connection.getMinecraftConnection().setCompressionThreshold(sc.getThreshold()); connection.getMinecraftConnection().setCompressionThreshold(sc.getThreshold());
} else if (packet instanceof ServerLoginSuccess) { } else if (packet instanceof ServerLoginSuccess) {
if (VelocityServer.getServer().getConfiguration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN && if (server.getConfiguration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN && !informationForwarded) {
!informationForwarded) {
doNotify(ConnectionRequestResults.forDisconnect( doNotify(ConnectionRequestResults.forDisconnect(
TextComponent.of("Your server did not send a forwarding request to the proxy. Is it set up correctly?"))); TextComponent.of("Your server did not send a forwarding request to the proxy. Is it set up correctly?")));
connection.disconnect(); connection.disconnect();
@ -80,14 +81,14 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
VelocityServerConnection existingConnection = connection.getPlayer().getConnectedServer(); VelocityServerConnection existingConnection = connection.getPlayer().getConnectedServer();
if (existingConnection == null) { if (existingConnection == null) {
// Strap on the play session handler // Strap on the play session handler
connection.getPlayer().getConnection().setSessionHandler(new ClientPlaySessionHandler(connection.getPlayer())); connection.getPlayer().getConnection().setSessionHandler(new ClientPlaySessionHandler(server, connection.getPlayer()));
} else { } else {
// The previous server connection should become obsolete. // The previous server connection should become obsolete.
existingConnection.disconnect(); existingConnection.disconnect();
} }
doNotify(ConnectionRequestResults.SUCCESSFUL); doNotify(ConnectionRequestResults.SUCCESSFUL);
connection.getMinecraftConnection().setSessionHandler(new BackendPlaySessionHandler(connection)); connection.getMinecraftConnection().setSessionHandler(new BackendPlaySessionHandler(server, connection));
connection.getPlayer().setConnectedServer(connection); connection.getPlayer().setConnectedServer(connection);
} }
} }

Datei anzeigen

@ -26,6 +26,7 @@ import io.netty.util.AttributeKey;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit; 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_DECODER;
import static com.velocitypowered.proxy.network.Connections.FRAME_ENCODER; import static com.velocitypowered.proxy.network.Connections.FRAME_ENCODER;
import static com.velocitypowered.proxy.network.Connections.HANDLER; 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)); .addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolConstants.Direction.SERVERBOUND));
ch.attr(CONNECTION_NOTIFIER).set(result); ch.attr(CONNECTION_NOTIFIER).set(result);
MinecraftConnection connection = new MinecraftConnection(ch); MinecraftConnection connection = new MinecraftConnection(ch, server);
connection.setState(StateRegistry.HANDSHAKE); connection.setState(StateRegistry.HANDSHAKE);
connection.setAssociation(VelocityServerConnection.this); connection.setAssociation(VelocityServerConnection.this);
ch.pipeline().addLast(HANDLER, connection); ch.pipeline().addLast(HANDLER, connection);
@ -77,7 +78,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
minecraftConnection = future.channel().pipeline().get(MinecraftConnection.class); minecraftConnection = future.channel().pipeline().get(MinecraftConnection.class);
// Kick off the connection process // Kick off the connection process
minecraftConnection.setSessionHandler(new LoginSessionHandler(VelocityServerConnection.this)); minecraftConnection.setSessionHandler(new LoginSessionHandler(server, VelocityServerConnection.this));
startHandshake(); startHandshake();
} else { } else {
result.completeExceptionally(future.cause()); result.completeExceptionally(future.cause());
@ -94,11 +95,11 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
return serverInfo.getAddress().getHostString() + "\0" + return serverInfo.getAddress().getHostString() + "\0" +
proxyPlayer.getRemoteAddress().getHostString() + "\0" + proxyPlayer.getRemoteAddress().getHostString() + "\0" +
proxyPlayer.getProfile().getId() + "\0" + proxyPlayer.getProfile().getId() + "\0" +
VelocityServer.GSON.toJson(proxyPlayer.getProfile().getProperties()); GSON.toJson(proxyPlayer.getProfile().getProperties());
} }
private void startHandshake() { private void startHandshake() {
PlayerInfoForwarding forwardingMode = VelocityServer.getServer().getConfiguration().getPlayerInfoForwardingMode(); PlayerInfoForwarding forwardingMode = server.getConfiguration().getPlayerInfoForwardingMode();
// Initiate a handshake. // Initiate a handshake.
Handshake handshake = new Handshake(); Handshake handshake = new Handshake();

Datei anzeigen

@ -32,18 +32,20 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
private boolean spawned = false; private boolean spawned = false;
private final List<UUID> serverBossBars = new ArrayList<>(); private final List<UUID> serverBossBars = new ArrayList<>();
private final Set<String> clientPluginMsgChannels = new HashSet<>(); private final Set<String> clientPluginMsgChannels = new HashSet<>();
private final VelocityServer server;
public ClientPlaySessionHandler(ConnectedPlayer player) { public ClientPlaySessionHandler(VelocityServer server, ConnectedPlayer player) {
this.player = player; this.player = player;
this.server = server;
} }
@Override @Override
public void activated() { public void activated() {
PluginMessage message; PluginMessage message;
if (player.getProtocolVersion() >= ProtocolConstants.MINECRAFT_1_13) { 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 { } else {
message = PluginMessageUtil.constructChannelsPacket("REGISTER", VelocityServer.getServer().getChannelRegistrar().getIdsForLegacyConnections()); message = PluginMessageUtil.constructChannelsPacket("REGISTER", server.getChannelRegistrar().getIdsForLegacyConnections());
} }
player.getConnection().write(message); player.getConnection().write(message);
} }
@ -72,7 +74,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
String msg = ((Chat) packet).getMessage(); String msg = ((Chat) packet).getMessage();
if (msg.startsWith("/")) { if (msg.startsWith("/")) {
try { try {
if (!VelocityServer.getServer().getCommandManager().execute(player, msg.substring(1))) { if (!server.getCommandManager().execute(player, msg.substring(1))) {
player.getConnectedServer().getMinecraftConnection().write(chat); player.getConnectedServer().getMinecraftConnection().write(chat);
} }
} catch (Exception e) { } catch (Exception e) {
@ -92,7 +94,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
if (!req.isAssumeCommand() && lastSpace != -1) { if (!req.isAssumeCommand() && lastSpace != -1) {
String command = req.getCommand().substring(1); String command = req.getCommand().substring(1);
try { try {
Optional<List<String>> offers = VelocityServer.getServer().getCommandManager().offerSuggestions(player, command); Optional<List<String>> offers = server.getCommandManager().offerSuggestions(player, command);
if (offers.isPresent()) { if (offers.isPresent()) {
TabCompleteResponse response = new TabCompleteResponse(); TabCompleteResponse response = new TabCompleteResponse();
response.setTransactionId(req.getTransactionId()); response.setTransactionId(req.getTransactionId());
@ -131,7 +133,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public void disconnected() { public void disconnected() {
player.teardown(); player.teardown();
VelocityServer.getServer().getEventManager().fireAndForget(new DisconnectEvent(player)); server.getEventManager().fireAndForget(new DisconnectEvent(player));
} }
@Override @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. // Tell the server about this client's plugin messages. Velocity will forward them on to the client.
Collection<String> toRegister = new HashSet<>(clientPluginMsgChannels); Collection<String> toRegister = new HashSet<>(clientPluginMsgChannels);
if (player.getProtocolVersion() >= ProtocolConstants.MINECRAFT_1_13) { if (player.getProtocolVersion() >= ProtocolConstants.MINECRAFT_1_13) {
toRegister.addAll(VelocityServer.getServer().getChannelRegistrar().getModernChannelIds()); toRegister.addAll(server.getChannelRegistrar().getModernChannelIds());
} else { } else {
toRegister.addAll(VelocityServer.getServer().getChannelRegistrar().getIdsForLegacyConnections()); toRegister.addAll(server.getChannelRegistrar().getIdsForLegacyConnections());
} }
if (!toRegister.isEmpty()) { if (!toRegister.isEmpty()) {
String channel = player.getConnection().getProtocolVersion() >= ProtocolConstants.MINECRAFT_1_13 ? String channel = player.getConnection().getProtocolVersion() >= ProtocolConstants.MINECRAFT_1_13 ?
@ -233,8 +235,8 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
return; return;
} }
MessageHandler.ForwardStatus status = VelocityServer.getServer().getChannelRegistrar().handlePluginMessage( MessageHandler.ForwardStatus status = server.getChannelRegistrar().handlePluginMessage(player,
player, ChannelSide.FROM_CLIENT, packet); ChannelSide.FROM_CLIENT, packet);
if (status == MessageHandler.ForwardStatus.FORWARD) { if (status == MessageHandler.ForwardStatus.FORWARD) {
// We're going to forward on the original packet. // We're going to forward on the original packet.
player.getConnectedServer().getMinecraftConnection().write(packet); player.getConnectedServer().getMinecraftConnection().write(packet);

Datei anzeigen

@ -6,8 +6,7 @@ import com.velocitypowered.proxy.protocol.packet.ClientSettings;
import java.util.Locale; import java.util.Locale;
public class ClientSettingsWrapper implements PlayerSettings { public class ClientSettingsWrapper implements PlayerSettings {
static PlayerSettings DEFAULT = new ClientSettingsWrapper(new ClientSettings("en_US", (byte) 10, 0, true, (short)127, 1));
public static PlayerSettings DEFAULT = new ClientSettingsWrapper(new ClientSettings("en_US", (byte) 10, 0, true, (short)127, 1));
private final ClientSettings settings; private final ClientSettings settings;
private final SkinParts parts; private final SkinParts parts;

Datei anzeigen

@ -58,8 +58,10 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
private VelocityServerConnection connectedServer; private VelocityServerConnection connectedServer;
private VelocityServerConnection connectionInFlight; private VelocityServerConnection connectionInFlight;
private PlayerSettings settings; 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.profile = profile;
this.connection = connection; this.connection = connection;
this.virtualHost = virtualHost; this.virtualHost = virtualHost;
@ -103,7 +105,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
public void setPlayerSettings(ClientSettings settings) { public void setPlayerSettings(ClientSettings settings) {
this.settings = new ClientSettingsWrapper(settings); this.settings = new ClientSettingsWrapper(settings);
VelocityServer.getServer().getEventManager().fireAndForget(new PlayerSettingsChangedEvent(this, this.settings)); server.getEventManager().fireAndForget(new PlayerSettingsChangedEvent(this, this.settings));
} }
@Override @Override
@ -230,14 +232,14 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
} }
Optional<ServerInfo> getNextServerToTry() { Optional<ServerInfo> getNextServerToTry() {
List<String> serversToTry = VelocityServer.getServer().getConfiguration().getAttemptConnectionOrder(); List<String> serversToTry = server.getConfiguration().getAttemptConnectionOrder();
if (tryIndex >= serversToTry.size()) { if (tryIndex >= serversToTry.size()) {
return Optional.empty(); return Optional.empty();
} }
String toTryName = serversToTry.get(tryIndex); String toTryName = serversToTry.get(tryIndex);
tryIndex++; tryIndex++;
return VelocityServer.getServer().getServers().getServer(toTryName); return server.getServers().getServer(toTryName);
} }
private CompletableFuture<ConnectionRequestBuilder.Result> connect(ConnectionRequestBuilderImpl request) { private CompletableFuture<ConnectionRequestBuilder.Result> connect(ConnectionRequestBuilderImpl request) {
@ -255,7 +257,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
// Otherwise, initiate the connection. // Otherwise, initiate the connection.
ServerPreConnectEvent event = new ServerPreConnectEvent(this, ServerPreConnectEvent.ServerResult.allowed(request.getServer())); ServerPreConnectEvent event = new ServerPreConnectEvent(this, ServerPreConnectEvent.ServerResult.allowed(request.getServer()));
return VelocityServer.getServer().getEventManager().fire(event) return server.getEventManager().fire(event)
.thenCompose((newEvent) -> { .thenCompose((newEvent) -> {
if (!newEvent.getResult().isAllowed()) { if (!newEvent.getResult().isAllowed()) {
return CompletableFuture.completedFuture( 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) { if (connectedServer != null) {
connectedServer.disconnect(); connectedServer.disconnect();
} }
VelocityServer.getServer().unregisterConnection(this); server.unregisterConnection(this);
} }
@Override @Override

Datei anzeigen

@ -31,7 +31,7 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler {
public HandshakeSessionHandler(MinecraftConnection connection, VelocityServer server) { public HandshakeSessionHandler(MinecraftConnection connection, VelocityServer server) {
this.connection = Preconditions.checkNotNull(connection, "connection"); this.connection = Preconditions.checkNotNull(connection, "connection");
this.server = server; this.server = Preconditions.checkNotNull(server, "server");
} }
@Override @Override
@ -53,7 +53,7 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler {
case StateRegistry.STATUS_ID: case StateRegistry.STATUS_ID:
connection.setState(StateRegistry.STATUS); connection.setState(StateRegistry.STATUS);
connection.setProtocolVersion(handshake.getProtocolVersion()); connection.setProtocolVersion(handshake.getProtocolVersion());
connection.setSessionHandler(new StatusSessionHandler(connection, ic)); connection.setSessionHandler(new StatusSessionHandler(server, connection, ic));
break; break;
case StateRegistry.LOGIN_ID: case StateRegistry.LOGIN_ID:
connection.setState(StateRegistry.LOGIN); connection.setState(StateRegistry.LOGIN);
@ -65,7 +65,7 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler {
} }
InetAddress address = ((InetSocketAddress) connection.getChannel().remoteAddress()).getAddress(); 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."))); connection.closeWith(Disconnect.create(TextComponent.of("You are logging in too fast, try again later.")));
return; return;
} }
@ -85,8 +85,8 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler {
return; return;
} }
VelocityServer.getServer().getEventManager().fireAndForget(new ConnectionHandshakeEvent(ic)); server.getEventManager().fireAndForget(new ConnectionHandshakeEvent(ic));
connection.setSessionHandler(new LoginSessionHandler(connection, ic)); connection.setSessionHandler(new LoginSessionHandler(server, connection, ic));
break; break;
default: default:
throw new IllegalArgumentException("Invalid state " + handshake.getNextStatus()); throw new IllegalArgumentException("Invalid state " + handshake.getNextStatus());
@ -100,15 +100,15 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler {
private void handleLegacy(MinecraftPacket packet) { private void handleLegacy(MinecraftPacket packet) {
if (packet instanceof LegacyPing) { if (packet instanceof LegacyPing) {
VelocityConfiguration configuration = VelocityServer.getServer().getConfiguration(); VelocityConfiguration configuration = server.getConfiguration();
ServerPing ping = new ServerPing( ServerPing ping = new ServerPing(
new ServerPing.Version(ProtocolConstants.MAXIMUM_GENERIC_VERSION, "Velocity " + ProtocolConstants.SUPPORTED_GENERIC_VERSION_STRING), 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(), configuration.getMotdComponent(),
null null
); );
ProxyPingEvent event = new ProxyPingEvent(new LegacyInboundConnection(connection), ping); ProxyPingEvent event = new ProxyPingEvent(new LegacyInboundConnection(connection), ping);
VelocityServer.getServer().getEventManager().fire(event) server.getEventManager().fire(event)
.thenRunAsync(() -> { .thenRunAsync(() -> {
// The disconnect packet is the same as the server response one. // The disconnect packet is the same as the server response one.
connection.closeWith(LegacyDisconnect.fromPingResponse(LegacyPingResponse.from(event.getPing()))); connection.closeWith(LegacyDisconnect.fromPingResponse(LegacyPingResponse.from(event.getPing())));

Datei anzeigen

@ -40,13 +40,15 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
private static final String MOJANG_SERVER_AUTH_URL = private static final String MOJANG_SERVER_AUTH_URL =
"https://sessionserver.mojang.com/session/minecraft/hasJoined?username=%s&serverId=%s&ip=%s"; "https://sessionserver.mojang.com/session/minecraft/hasJoined?username=%s&serverId=%s&ip=%s";
private final VelocityServer server;
private final MinecraftConnection inbound; private final MinecraftConnection inbound;
private final InboundConnection apiInbound; private final InboundConnection apiInbound;
private ServerLogin login; private ServerLogin login;
private byte[] verify; private byte[] verify;
private int playerInfoId; 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.inbound = Preconditions.checkNotNull(inbound, "inbound");
this.apiInbound = Preconditions.checkNotNull(apiInbound, "apiInbound"); this.apiInbound = Preconditions.checkNotNull(apiInbound, "apiInbound");
} }
@ -81,7 +83,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
} }
} else if (packet instanceof EncryptionResponse) { } else if (packet instanceof EncryptionResponse) {
try { try {
KeyPair serverKeyPair = VelocityServer.getServer().getServerKeyPair(); KeyPair serverKeyPair = server.getServerKeyPair();
EncryptionResponse response = (EncryptionResponse) packet; EncryptionResponse response = (EncryptionResponse) packet;
byte[] decryptedVerifyToken = EncryptionUtils.decryptRsa(serverKeyPair, response.getVerifyToken()); byte[] decryptedVerifyToken = EncryptionUtils.decryptRsa(serverKeyPair, response.getVerifyToken());
if (!Arrays.equals(verify, decryptedVerifyToken)) { if (!Arrays.equals(verify, decryptedVerifyToken)) {
@ -92,7 +94,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
String serverId = EncryptionUtils.generateServerId(decryptedSharedSecret, serverKeyPair.getPublic()); String serverId = EncryptionUtils.generateServerId(decryptedSharedSecret, serverKeyPair.getPublic());
String playerIp = ((InetSocketAddress) inbound.getChannel().remoteAddress()).getHostString(); 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))) .get(new URL(String.format(MOJANG_SERVER_AUTH_URL, login.getUsername(), serverId, playerIp)))
.thenAcceptAsync(profileResponse -> { .thenAcceptAsync(profileResponse -> {
if (inbound.isClosed()) { if (inbound.isClosed()) {
@ -124,7 +126,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
private void beginPreLogin() { private void beginPreLogin() {
PreLoginEvent event = new PreLoginEvent(apiInbound, login.getUsername()); PreLoginEvent event = new PreLoginEvent(apiInbound, login.getUsername());
VelocityServer.getServer().getEventManager().fire(event) server.getEventManager().fire(event)
.thenRunAsync(() -> { .thenRunAsync(() -> {
if (inbound.isClosed()) { if (inbound.isClosed()) {
// The player was disconnected // The player was disconnected
@ -137,7 +139,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
return; return;
} }
if (VelocityServer.getServer().getConfiguration().isOnlineMode() || result.isOnlineModeAllowed()) { if (server.getConfiguration().isOnlineMode() || result.isOnlineModeAllowed()) {
// Request encryption. // Request encryption.
EncryptionRequest request = generateRequest(); EncryptionRequest request = generateRequest();
this.verify = Arrays.copyOf(request.getVerifyToken(), 4); this.verify = Arrays.copyOf(request.getVerifyToken(), 4);
@ -153,7 +155,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
ThreadLocalRandom.current().nextBytes(verify); ThreadLocalRandom.current().nextBytes(verify);
EncryptionRequest request = new EncryptionRequest(); EncryptionRequest request = new EncryptionRequest();
request.setPublicKey(VelocityServer.getServer().getServerKeyPair().getPublic().getEncoded()); request.setPublicKey(server.getServerKeyPair().getPublic().getEncoded());
request.setVerifyToken(verify); request.setVerifyToken(verify);
return request; return request;
} }
@ -161,17 +163,17 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
private void initializePlayer(GameProfile profile, boolean onlineMode) { private void initializePlayer(GameProfile profile, boolean onlineMode) {
GameProfileRequestEvent profileRequestEvent = new GameProfileRequestEvent(apiInbound, profile, 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. // 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)); 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 -> { .thenCompose(event -> {
// wait for permissions to load, then set the players permission function // wait for permissions to load, then set the players permission function
player.setPermissionFunction(event.createFunction(player)); player.setPermissionFunction(event.createFunction(player));
// then call & wait for the login event // 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 // then complete the connection
.thenAcceptAsync(event -> { .thenAcceptAsync(event -> {
@ -198,7 +200,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
return; return;
} }
int threshold = VelocityServer.getServer().getConfiguration().getCompressionThreshold(); int threshold = server.getConfiguration().getCompressionThreshold();
if (threshold >= 0) { if (threshold >= 0) {
inbound.write(new SetCompression(threshold)); inbound.write(new SetCompression(threshold));
inbound.setCompressionThreshold(threshold); inbound.setCompressionThreshold(threshold);
@ -212,7 +214,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
inbound.setAssociation(player); inbound.setAssociation(player);
inbound.setState(StateRegistry.PLAY); 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))); inbound.closeWith(Disconnect.create(TextComponent.of("You are already on this proxy!", TextColor.RED)));
} }

Datei anzeigen

@ -18,10 +18,12 @@ import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil; import io.netty.buffer.ByteBufUtil;
public class StatusSessionHandler implements MinecraftSessionHandler { public class StatusSessionHandler implements MinecraftSessionHandler {
private final VelocityServer server;
private final MinecraftConnection connection; private final MinecraftConnection connection;
private final InboundConnection inboundWrapper; 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.connection = connection;
this.inboundWrapper = inboundWrapper; this.inboundWrapper = inboundWrapper;
} }
@ -37,20 +39,20 @@ public class StatusSessionHandler implements MinecraftSessionHandler {
return; return;
} }
VelocityConfiguration configuration = VelocityServer.getServer().getConfiguration(); VelocityConfiguration configuration = server.getConfiguration();
// Status request // Status request
int shownVersion = ProtocolConstants.isSupported(connection.getProtocolVersion()) ? connection.getProtocolVersion() : int shownVersion = ProtocolConstants.isSupported(connection.getProtocolVersion()) ? connection.getProtocolVersion() :
ProtocolConstants.MAXIMUM_GENERIC_VERSION; ProtocolConstants.MAXIMUM_GENERIC_VERSION;
ServerPing initialPing = new ServerPing( ServerPing initialPing = new ServerPing(
new ServerPing.Version(shownVersion, "Velocity " + ProtocolConstants.SUPPORTED_GENERIC_VERSION_STRING), 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.getMotdComponent(),
configuration.getFavicon() configuration.getFavicon()
); );
ProxyPingEvent event = new ProxyPingEvent(inboundWrapper, initialPing); ProxyPingEvent event = new ProxyPingEvent(inboundWrapper, initialPing);
VelocityServer.getServer().getEventManager().fire(event) server.getEventManager().fire(event)
.thenRunAsync(() -> { .thenRunAsync(() -> {
StatusResponse response = new StatusResponse(); StatusResponse response = new StatusResponse();
response.setStatus(VelocityServer.GSON.toJson(event.getPing())); response.setStatus(VelocityServer.GSON.toJson(event.getPing()));

Datei anzeigen

@ -84,7 +84,7 @@ public final class ConnectionManager {
.addLast(MINECRAFT_DECODER, new MinecraftDecoder(ProtocolConstants.Direction.SERVERBOUND)) .addLast(MINECRAFT_DECODER, new MinecraftDecoder(ProtocolConstants.Direction.SERVERBOUND))
.addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolConstants.Direction.CLIENTBOUND)); .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.setState(StateRegistry.HANDSHAKE);
connection.setSessionHandler(new HandshakeSessionHandler(connection, server)); connection.setSessionHandler(new HandshakeSessionHandler(connection, server));
ch.pipeline().addLast(Connections.HANDLER, connection); ch.pipeline().addLast(Connections.HANDLER, connection);
@ -109,7 +109,7 @@ public final class ConnectionManager {
Bootstrap bootstrap = new Bootstrap() Bootstrap bootstrap = new Bootstrap()
.channel(transportType.datagramChannelClass) .channel(transportType.datagramChannelClass)
.group(this.workerGroup) .group(this.workerGroup)
.handler(new GS4QueryHandler()) .handler(new GS4QueryHandler(server))
.localAddress(hostname, port); .localAddress(hostname, port);
bootstrap.bind() bootstrap.bind()
.addListener((ChannelFutureListener) future -> { .addListener((ChannelFutureListener) future -> {

Datei anzeigen

@ -42,10 +42,16 @@ public class GS4QueryHandler extends SimpleChannelInboundHandler<DatagramPacket>
"hostip" "hostip"
); );
private final static Cache<InetAddress, Integer> sessions = CacheBuilder.newBuilder() private final Cache<InetAddress, Integer> sessions = CacheBuilder.newBuilder()
.expireAfterWrite(30, TimeUnit.SECONDS) .expireAfterWrite(30, TimeUnit.SECONDS)
.build(); .build();
private final VelocityServer server;
public GS4QueryHandler(VelocityServer server) {
this.server = server;
}
@Override @Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
ByteBuf queryMessage = msg.content(); ByteBuf queryMessage = msg.content();
@ -96,7 +102,6 @@ public class GS4QueryHandler extends SimpleChannelInboundHandler<DatagramPacket>
queryResponse.writeInt(sessionId); queryResponse.writeInt(sessionId);
// Fetch information // Fetch information
VelocityServer server = VelocityServer.getServer();
Collection<Player> players = server.getAllPlayers(); Collection<Player> players = server.getAllPlayers();
// Start writing the response // Start writing the response