Rename netty to socket wherever possible

This commit is contained in:
TheMode 2021-08-08 19:11:47 +02:00
parent b56509718c
commit 1591df16aa
18 changed files with 120 additions and 150 deletions

View File

@ -7,7 +7,7 @@ import net.minestom.server.instance.Instance;
import net.minestom.server.instance.InstanceManager; import net.minestom.server.instance.InstanceManager;
import net.minestom.server.monitoring.TickMonitor; import net.minestom.server.monitoring.TickMonitor;
import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.ConnectionManager;
import net.minestom.server.network.player.NettyPlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.thread.SingleThreadProvider; import net.minestom.server.thread.SingleThreadProvider;
import net.minestom.server.thread.ThreadProvider; import net.minestom.server.thread.ThreadProvider;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -84,8 +84,8 @@ public final class UpdateManager {
// Flush all waiting packets // Flush all waiting packets
for (Player player : connectionManager.getOnlinePlayers()) { for (Player player : connectionManager.getOnlinePlayers()) {
final var connection = player.getPlayerConnection(); final var connection = player.getPlayerConnection();
if (connection instanceof NettyPlayerConnection) { if (connection instanceof PlayerSocketConnection) {
((NettyPlayerConnection) connection).flush(); ((PlayerSocketConnection) connection).flush();
} }
} }

View File

@ -491,14 +491,14 @@ public class Entity implements Viewable, Tickable, TagHandler, PermissionHandler
} }
private void velocityTick() { private void velocityTick() {
final boolean isNettyClient = PlayerUtils.isNettyClient(this); final boolean isSocketClient = PlayerUtils.isSocketClient(this);
final boolean noGravity = hasNoGravity(); final boolean noGravity = hasNoGravity();
final boolean hasVelocity = hasVelocity(); final boolean hasVelocity = hasVelocity();
boolean applyVelocity; boolean applyVelocity;
// Non-player entities with either velocity or gravity enabled // Non-player entities with either velocity or gravity enabled
applyVelocity = !isNettyClient && (hasVelocity || !noGravity); applyVelocity = !isSocketClient && (hasVelocity || !noGravity);
// Players with a velocity applied (client is responsible for gravity) // Players with a velocity applied (client is responsible for gravity)
applyVelocity |= isNettyClient && hasVelocity; applyVelocity |= isSocketClient && hasVelocity;
if (!applyVelocity) { if (!applyVelocity) {
return; return;
} }
@ -537,13 +537,13 @@ public class Entity implements Viewable, Tickable, TagHandler, PermissionHandler
return; return;
} }
refreshPosition(finalVelocityPosition, true); refreshPosition(finalVelocityPosition, true);
if (!isNettyClient) { if (!isSocketClient) {
synchronizePosition(true); synchronizePosition(true);
} }
// Update velocity // Update velocity
if (hasVelocity || !newVelocity.isZero()) { if (hasVelocity || !newVelocity.isZero()) {
if (onGround && isNettyClient) { if (onGround && isSocketClient) {
// Stop player velocity // Stop player velocity
this.velocity = Vec.ZERO; this.velocity = Vec.ZERO;
} else { } else {

View File

@ -55,8 +55,8 @@ import net.minestom.server.network.packet.client.play.ClientChatMessagePacket;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.login.LoginDisconnectPacket; import net.minestom.server.network.packet.server.login.LoginDisconnectPacket;
import net.minestom.server.network.packet.server.play.*; import net.minestom.server.network.packet.server.play.*;
import net.minestom.server.network.player.NettyPlayerConnection;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.recipe.Recipe; import net.minestom.server.recipe.Recipe;
import net.minestom.server.recipe.RecipeManager; import net.minestom.server.recipe.RecipeManager;
import net.minestom.server.resourcepack.ResourcePack; import net.minestom.server.resourcepack.ResourcePack;
@ -92,7 +92,7 @@ import java.util.function.UnaryOperator;
/** /**
* Those are the major actors of the server, * Those are the major actors of the server,
* they are not necessary backed by a {@link NettyPlayerConnection} as shown by {@link FakePlayer}. * they are not necessary backed by a {@link PlayerSocketConnection} as shown by {@link FakePlayer}.
* <p> * <p>
* You can easily create your own implementation of this and use it with {@link ConnectionManager#setPlayerProvider(PlayerProvider)}. * You can easily create your own implementation of this and use it with {@link ConnectionManager#setPlayerProvider(PlayerProvider)}.
*/ */
@ -212,7 +212,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
* Init the player and spawn him. * Init the player and spawn him.
* <p> * <p>
* WARNING: executed in the main update thread * WARNING: executed in the main update thread
* UNSAFE: Only meant to be used when a netty player connects through the server. * UNSAFE: Only meant to be used when a socket player connects through the server.
* *
* @param spawnInstance the player spawn instance (defined in {@link PlayerLoginEvent}) * @param spawnInstance the player spawn instance (defined in {@link PlayerLoginEvent})
*/ */
@ -1366,8 +1366,8 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
} else { } else {
disconnectPacket = new DisconnectPacket(component); disconnectPacket = new DisconnectPacket(component);
} }
if (playerConnection instanceof NettyPlayerConnection) { if (playerConnection instanceof PlayerSocketConnection) {
((NettyPlayerConnection) playerConnection).writeAndFlush(disconnectPacket); ((PlayerSocketConnection) playerConnection).writeAndFlush(disconnectPacket);
playerConnection.disconnect(); playerConnection.disconnect();
} else { } else {
playerConnection.sendPacket(disconnectPacket); playerConnection.sendPacket(disconnectPacket);

View File

@ -22,7 +22,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer; import java.util.function.Consumer;
/** /**
* A fake player will behave exactly the same way as would do a {@link Player} backed by a netty connection * A fake player will behave exactly the same way as would do a {@link Player} backed by a socket connection
* (events, velocity, gravity, player list, etc...) with the exception that you need to control it server-side * (events, velocity, gravity, player list, etc...) with the exception that you need to control it server-side
* using a {@link FakePlayerController} (see {@link #getController()}). * using a {@link FakePlayerController} (see {@link #getController()}).
* <p> * <p>

View File

@ -8,10 +8,8 @@ import org.jetbrains.annotations.Nullable;
import java.security.KeyPair; import java.security.KeyPair;
public final class MojangAuth { public final class MojangAuth {
private static volatile boolean enabled = false; private static volatile boolean enabled = false;
private static volatile KeyPair keyPair;
private static KeyPair keyPair;
/** /**
* Enables mojang authentication on the server. * Enables mojang authentication on the server.
@ -21,19 +19,16 @@ public final class MojangAuth {
public static void init() { public static void init() {
Check.stateCondition(enabled, "Mojang auth is already enabled!"); Check.stateCondition(enabled, "Mojang auth is already enabled!");
Check.stateCondition(MinecraftServer.isStarted(), "The server has already been started!"); Check.stateCondition(MinecraftServer.isStarted(), "The server has already been started!");
MojangAuth.enabled = true;
enabled = true;
// Generate necessary fields... // Generate necessary fields...
keyPair = MojangCrypt.generateKeyPair(); MojangAuth.keyPair = MojangCrypt.generateKeyPair();
} }
public static boolean isEnabled() { public static boolean isEnabled() {
return enabled; return enabled;
} }
@Nullable public static @Nullable KeyPair getKeyPair() {
public static KeyPair getKeyPair() {
return keyPair; return keyPair;
} }
} }

View File

@ -10,7 +10,7 @@ import net.minestom.server.instance.block.Block;
import net.minestom.server.instance.block.BlockHandler; import net.minestom.server.instance.block.BlockHandler;
import net.minestom.server.network.packet.server.play.ChunkDataPacket; import net.minestom.server.network.packet.server.play.ChunkDataPacket;
import net.minestom.server.network.packet.server.play.UpdateLightPacket; import net.minestom.server.network.packet.server.play.UpdateLightPacket;
import net.minestom.server.network.player.NettyPlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.ArrayUtils; import net.minestom.server.utils.ArrayUtils;
import net.minestom.server.utils.PacketUtils; import net.minestom.server.utils.PacketUtils;
@ -130,7 +130,7 @@ public class DynamicChunk extends Chunk {
public synchronized void sendChunk(@NotNull Player player) { public synchronized void sendChunk(@NotNull Player player) {
if (!isLoaded()) return; if (!isLoaded()) return;
final PlayerConnection connection = player.getPlayerConnection(); final PlayerConnection connection = player.getPlayerConnection();
if (connection instanceof NettyPlayerConnection) { if (connection instanceof PlayerSocketConnection) {
final long lastChange = getLastChangeTime(); final long lastChange = getLastChangeTime();
ByteBuffer chunkPacket = cachedChunkBuffer; ByteBuffer chunkPacket = cachedChunkBuffer;
ByteBuffer lightPacket = cachedLightBuffer; ByteBuffer lightPacket = cachedLightBuffer;
@ -141,9 +141,9 @@ public class DynamicChunk extends Chunk {
this.cachedLightBuffer = lightPacket; this.cachedLightBuffer = lightPacket;
this.cachedPacketTime = lastChange; this.cachedPacketTime = lastChange;
} }
NettyPlayerConnection nettyPlayerConnection = (NettyPlayerConnection) connection; PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection;
nettyPlayerConnection.write(lightPacket); socketConnection.write(lightPacket);
nettyPlayerConnection.write(chunkPacket); socketConnection.write(chunkPacket);
} else { } else {
connection.sendPacket(createLightPacket()); connection.sendPacket(createLightPacket());
connection.sendPacket(createChunkPacket()); connection.sendPacket(createChunkPacket());

View File

@ -15,7 +15,7 @@ import net.minestom.server.network.packet.client.login.LoginStartPacket;
import net.minestom.server.network.packet.server.login.LoginSuccessPacket; import net.minestom.server.network.packet.server.login.LoginSuccessPacket;
import net.minestom.server.network.packet.server.play.DisconnectPacket; import net.minestom.server.network.packet.server.play.DisconnectPacket;
import net.minestom.server.network.packet.server.play.KeepAlivePacket; import net.minestom.server.network.packet.server.play.KeepAlivePacket;
import net.minestom.server.network.player.NettyPlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.StringUtils; import net.minestom.server.utils.StringUtils;
import net.minestom.server.utils.async.AsyncUtils; import net.minestom.server.utils.async.AsyncUtils;
@ -293,8 +293,8 @@ public final class ConnectionManager {
EventDispatcher.call(asyncPlayerPreLoginEvent); EventDispatcher.call(asyncPlayerPreLoginEvent);
// Close the player channel if he has been disconnected (kick) // Close the player channel if he has been disconnected (kick)
if (!player.isOnline()) { if (!player.isOnline()) {
if (playerConnection instanceof NettyPlayerConnection) { if (playerConnection instanceof PlayerSocketConnection) {
((NettyPlayerConnection) playerConnection).flush(); ((PlayerSocketConnection) playerConnection).flush();
} }
//playerConnection.disconnect(); //playerConnection.disconnect();
return; return;
@ -312,8 +312,8 @@ public final class ConnectionManager {
} }
// Send login success packet // Send login success packet
LoginSuccessPacket loginSuccessPacket = new LoginSuccessPacket(player.getUuid(), player.getUsername()); LoginSuccessPacket loginSuccessPacket = new LoginSuccessPacket(player.getUuid(), player.getUsername());
if (playerConnection instanceof NettyPlayerConnection) { if (playerConnection instanceof PlayerSocketConnection) {
((NettyPlayerConnection) playerConnection).writeAndFlush(loginSuccessPacket); ((PlayerSocketConnection) playerConnection).writeAndFlush(loginSuccessPacket);
} else { } else {
playerConnection.sendPacket(loginSuccessPacket); playerConnection.sendPacket(loginSuccessPacket);
} }
@ -348,11 +348,11 @@ public final class ConnectionManager {
DisconnectPacket disconnectPacket = new DisconnectPacket(shutdownText); DisconnectPacket disconnectPacket = new DisconnectPacket(shutdownText);
for (Player player : getOnlinePlayers()) { for (Player player : getOnlinePlayers()) {
final PlayerConnection playerConnection = player.getPlayerConnection(); final PlayerConnection playerConnection = player.getPlayerConnection();
if (playerConnection instanceof NettyPlayerConnection) { if (playerConnection instanceof PlayerSocketConnection) {
final NettyPlayerConnection nettyPlayerConnection = (NettyPlayerConnection) playerConnection; final PlayerSocketConnection socketConnection = (PlayerSocketConnection) playerConnection;
nettyPlayerConnection.writeAndFlush(disconnectPacket); socketConnection.writeAndFlush(disconnectPacket);
try { try {
nettyPlayerConnection.getChannel().close(); socketConnection.getChannel().close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -8,7 +8,7 @@ import net.minestom.server.network.packet.client.handler.ClientLoginPacketsHandl
import net.minestom.server.network.packet.client.handler.ClientPlayPacketsHandler; import net.minestom.server.network.packet.client.handler.ClientPlayPacketsHandler;
import net.minestom.server.network.packet.client.handler.ClientStatusPacketsHandler; import net.minestom.server.network.packet.client.handler.ClientStatusPacketsHandler;
import net.minestom.server.network.packet.client.handshake.HandshakePacket; import net.minestom.server.network.packet.client.handshake.HandshakePacket;
import net.minestom.server.network.player.NettyPlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.Readable; import net.minestom.server.utils.binary.Readable;
@ -42,7 +42,7 @@ public final class PacketProcessor {
this.playPacketsHandler = new ClientPlayPacketsHandler(); this.playPacketsHandler = new ClientPlayPacketsHandler();
} }
public void process(@NotNull NettyPlayerConnection playerConnection, int packetId, ByteBuffer body) { public void process(@NotNull PlayerSocketConnection playerConnection, int packetId, ByteBuffer body) {
if (MinecraftServer.getRateLimit() > 0) { if (MinecraftServer.getRateLimit() > 0) {
// Increment packet count (checked in PlayerConnection#update) // Increment packet count (checked in PlayerConnection#update)
playerConnection.getPacketCounter().incrementAndGet(); playerConnection.getPacketCounter().incrementAndGet();

View File

@ -8,7 +8,7 @@ import net.minestom.server.extras.bungee.BungeeCordProxy;
import net.minestom.server.network.ConnectionState; import net.minestom.server.network.ConnectionState;
import net.minestom.server.network.packet.client.ClientPreplayPacket; import net.minestom.server.network.packet.client.ClientPreplayPacket;
import net.minestom.server.network.packet.server.login.LoginDisconnectPacket; import net.minestom.server.network.packet.server.login.LoginDisconnectPacket;
import net.minestom.server.network.player.NettyPlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.BinaryWriter;
@ -54,8 +54,8 @@ public class HandshakePacket implements ClientPreplayPacket {
public void process(@NotNull PlayerConnection connection) { public void process(@NotNull PlayerConnection connection) {
// Bungee support (IP forwarding) // Bungee support (IP forwarding)
if (BungeeCordProxy.isEnabled() && connection instanceof NettyPlayerConnection) { if (BungeeCordProxy.isEnabled() && connection instanceof PlayerSocketConnection) {
NettyPlayerConnection nettyPlayerConnection = (NettyPlayerConnection) connection; PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection;
if (serverAddress != null) { if (serverAddress != null) {
final String[] split = serverAddress.split("\00"); final String[] split = serverAddress.split("\00");
@ -65,7 +65,7 @@ public class HandshakePacket implements ClientPreplayPacket {
final SocketAddress socketAddress = new java.net.InetSocketAddress(split[1], final SocketAddress socketAddress = new java.net.InetSocketAddress(split[1],
((java.net.InetSocketAddress) connection.getRemoteAddress()).getPort()); ((java.net.InetSocketAddress) connection.getRemoteAddress()).getPort());
nettyPlayerConnection.setRemoteAddress(socketAddress); socketConnection.setRemoteAddress(socketAddress);
UUID playerUuid = UUID.fromString( UUID playerUuid = UUID.fromString(
split[2] split[2]
@ -79,11 +79,11 @@ public class HandshakePacket implements ClientPreplayPacket {
playerSkin = BungeeCordProxy.readSkin(split[3]); playerSkin = BungeeCordProxy.readSkin(split[3]);
} }
nettyPlayerConnection.UNSAFE_setBungeeUuid(playerUuid); socketConnection.UNSAFE_setBungeeUuid(playerUuid);
nettyPlayerConnection.UNSAFE_setBungeeSkin(playerSkin); socketConnection.UNSAFE_setBungeeSkin(playerSkin);
} else { } else {
nettyPlayerConnection.sendPacket(new LoginDisconnectPacket(INVALID_BUNGEE_FORWARDING)); socketConnection.sendPacket(new LoginDisconnectPacket(INVALID_BUNGEE_FORWARDING));
nettyPlayerConnection.disconnect(); socketConnection.disconnect();
return; return;
} }
} else { } else {
@ -92,9 +92,9 @@ public class HandshakePacket implements ClientPreplayPacket {
} }
} }
if (connection instanceof NettyPlayerConnection) { if (connection instanceof PlayerSocketConnection) {
// Give to the connection the server info that the client used // Give to the connection the server info that the client used
((NettyPlayerConnection) connection).refreshServerInformation(serverAddress, serverPort, protocolVersion); ((PlayerSocketConnection) connection).refreshServerInformation(serverAddress, serverPort, protocolVersion);
} }
switch (nextState) { switch (nextState) {

View File

@ -7,8 +7,8 @@ import net.minestom.server.data.type.array.ByteArrayData;
import net.minestom.server.extras.MojangAuth; import net.minestom.server.extras.MojangAuth;
import net.minestom.server.extras.mojangAuth.MojangCrypt; import net.minestom.server.extras.mojangAuth.MojangCrypt;
import net.minestom.server.network.packet.client.ClientPreplayPacket; import net.minestom.server.network.packet.client.ClientPreplayPacket;
import net.minestom.server.network.player.NettyPlayerConnection;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.utils.async.AsyncUtils; import net.minestom.server.utils.async.AsyncUtils;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.BinaryWriter;
@ -35,31 +35,26 @@ public class EncryptionResponsePacket implements ClientPreplayPacket {
@Override @Override
public void process(@NotNull PlayerConnection connection) { public void process(@NotNull PlayerConnection connection) {
// Encryption is only support for socket connection
// Encryption is only support for netty connection if (!(connection instanceof PlayerSocketConnection)) {
if (!(connection instanceof NettyPlayerConnection)) {
return; return;
} }
final NettyPlayerConnection nettyConnection = (NettyPlayerConnection) connection; final PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection;
AsyncUtils.runAsync(() -> { AsyncUtils.runAsync(() -> {
try { try {
final String loginUsername = nettyConnection.getLoginUsername(); final String loginUsername = socketConnection.getLoginUsername();
if (!Arrays.equals(nettyConnection.getNonce(), getNonce())) { if (!Arrays.equals(socketConnection.getNonce(), getNonce())) {
MinecraftServer.LOGGER.error("{} tried to login with an invalid nonce!", loginUsername); MinecraftServer.LOGGER.error("{} tried to login with an invalid nonce!", loginUsername);
return; return;
} }
if (loginUsername != null && !loginUsername.isEmpty()) { if (loginUsername != null && !loginUsername.isEmpty()) {
final byte[] digestedData = MojangCrypt.digestData("", MojangAuth.getKeyPair().getPublic(), getSecretKey()); final byte[] digestedData = MojangCrypt.digestData("", MojangAuth.getKeyPair().getPublic(), getSecretKey());
if (digestedData == null) { if (digestedData == null) {
// Incorrect key, probably because of the client // Incorrect key, probably because of the client
MinecraftServer.LOGGER.error("Connection {} failed initializing encryption.", nettyConnection.getRemoteAddress()); MinecraftServer.LOGGER.error("Connection {} failed initializing encryption.", socketConnection.getRemoteAddress());
connection.disconnect(); connection.disconnect();
return; return;
} }
// Query Mojang's sessionserver. // Query Mojang's sessionserver.
final String serverId = new BigInteger(digestedData).toString(16); final String serverId = new BigInteger(digestedData).toString(16);
InputStream gameProfileStream = new URL( InputStream gameProfileStream = new URL(
@ -70,7 +65,7 @@ public class EncryptionResponsePacket implements ClientPreplayPacket {
).openStream(); ).openStream();
final JsonObject gameProfile = GSON.fromJson(new InputStreamReader(gameProfileStream), JsonObject.class); final JsonObject gameProfile = GSON.fromJson(new InputStreamReader(gameProfileStream), JsonObject.class);
nettyConnection.setEncryptionKey(getSecretKey()); socketConnection.setEncryptionKey(getSecretKey());
UUID profileUUID = UUID.fromString(gameProfile.get("id").getAsString().replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); UUID profileUUID = UUID.fromString(gameProfile.get("id").getAsString().replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5"));
String profileName = gameProfile.get("name").getAsString(); String profileName = gameProfile.get("name").getAsString();
@ -85,8 +80,8 @@ public class EncryptionResponsePacket implements ClientPreplayPacket {
@Override @Override
public void read(@NotNull BinaryReader reader) { public void read(@NotNull BinaryReader reader) {
sharedSecret = ByteArrayData.decodeByteArray(reader); this.sharedSecret = ByteArrayData.decodeByteArray(reader);
verifyToken = ByteArrayData.decodeByteArray(reader); this.verifyToken = ByteArrayData.decodeByteArray(reader);
} }
@Override @Override

View File

@ -9,7 +9,7 @@ import net.minestom.server.extras.velocity.VelocityProxy;
import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.ConnectionManager;
import net.minestom.server.network.packet.client.ClientPreplayPacket; import net.minestom.server.network.packet.client.ClientPreplayPacket;
import net.minestom.server.network.packet.server.login.LoginDisconnectPacket; import net.minestom.server.network.packet.server.login.LoginDisconnectPacket;
import net.minestom.server.network.player.NettyPlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.BinaryWriter;
@ -34,9 +34,9 @@ public class LoginPluginResponsePacket implements ClientPreplayPacket {
public void process(@NotNull PlayerConnection connection) { public void process(@NotNull PlayerConnection connection) {
// Proxy support // Proxy support
if (connection instanceof NettyPlayerConnection) { if (connection instanceof PlayerSocketConnection) {
final NettyPlayerConnection nettyPlayerConnection = (NettyPlayerConnection) connection; final PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection;
final String channel = nettyPlayerConnection.getPluginRequestChannel(messageId); final String channel = socketConnection.getPluginRequestChannel(messageId);
if (channel != null) { if (channel != null) {
boolean success = false; boolean success = false;
@ -68,13 +68,13 @@ public class LoginPluginResponsePacket implements ClientPreplayPacket {
if (success) { if (success) {
if (socketAddress != null) { if (socketAddress != null) {
nettyPlayerConnection.setRemoteAddress(socketAddress); socketConnection.setRemoteAddress(socketAddress);
} }
if (playerUsername != null) { if (playerUsername != null) {
nettyPlayerConnection.UNSAFE_setLoginUsername(playerUsername); socketConnection.UNSAFE_setLoginUsername(playerUsername);
} }
final String username = nettyPlayerConnection.getLoginUsername(); final String username = socketConnection.getLoginUsername();
final UUID uuid = playerUuid != null ? final UUID uuid = playerUuid != null ?
playerUuid : CONNECTION_MANAGER.getPlayerConnectionUuid(connection, username); playerUuid : CONNECTION_MANAGER.getPlayerConnectionUuid(connection, username);
@ -82,7 +82,7 @@ public class LoginPluginResponsePacket implements ClientPreplayPacket {
player.setSkin(playerSkin); player.setSkin(playerSkin);
} else { } else {
LoginDisconnectPacket disconnectPacket = new LoginDisconnectPacket(INVALID_PROXY_RESPONSE); LoginDisconnectPacket disconnectPacket = new LoginDisconnectPacket(INVALID_PROXY_RESPONSE);
nettyPlayerConnection.sendPacket(disconnectPacket); socketConnection.sendPacket(disconnectPacket);
} }
} }

View File

@ -12,8 +12,8 @@ import net.minestom.server.network.packet.client.ClientPreplayPacket;
import net.minestom.server.network.packet.server.login.EncryptionRequestPacket; import net.minestom.server.network.packet.server.login.EncryptionRequestPacket;
import net.minestom.server.network.packet.server.login.LoginDisconnectPacket; import net.minestom.server.network.packet.server.login.LoginDisconnectPacket;
import net.minestom.server.network.packet.server.login.LoginPluginRequestPacket; import net.minestom.server.network.packet.server.login.LoginPluginRequestPacket;
import net.minestom.server.network.player.NettyPlayerConnection;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -29,70 +29,58 @@ public class LoginStartPacket implements ClientPreplayPacket {
@Override @Override
public void process(@NotNull PlayerConnection connection) { public void process(@NotNull PlayerConnection connection) {
final boolean isSocketConnection = connection instanceof PlayerSocketConnection;
final boolean isNettyClient = connection instanceof NettyPlayerConnection;
// Cache the login username and start compression if enabled // Cache the login username and start compression if enabled
if (isNettyClient) { if (isSocketConnection) {
NettyPlayerConnection nettyPlayerConnection = (NettyPlayerConnection) connection; PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection;
nettyPlayerConnection.UNSAFE_setLoginUsername(username); socketConnection.UNSAFE_setLoginUsername(username);
// Compression // Compression
final int threshold = MinecraftServer.getCompressionThreshold(); final int threshold = MinecraftServer.getCompressionThreshold();
if (threshold > 0) { if (threshold > 0) {
nettyPlayerConnection.startCompression(); socketConnection.startCompression();
} }
} }
// Proxy support (only for socket clients)
// Proxy support (only for netty clients) if (isSocketConnection) {
if (isNettyClient) { final PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection;
final NettyPlayerConnection nettyPlayerConnection = (NettyPlayerConnection) connection;
{
// Velocity support // Velocity support
if (VelocityProxy.isEnabled()) { if (VelocityProxy.isEnabled()) {
final int messageId = ThreadLocalRandom.current().nextInt(); final int messageId = ThreadLocalRandom.current().nextInt();
final String channel = VelocityProxy.PLAYER_INFO_CHANNEL; final String channel = VelocityProxy.PLAYER_INFO_CHANNEL;
// Important in order to retrieve the channel in the response packet // Important in order to retrieve the channel in the response packet
nettyPlayerConnection.addPluginRequestEntry(messageId, channel); socketConnection.addPluginRequestEntry(messageId, channel);
LoginPluginRequestPacket loginPluginRequestPacket = new LoginPluginRequestPacket(); LoginPluginRequestPacket loginPluginRequestPacket = new LoginPluginRequestPacket();
loginPluginRequestPacket.messageId = messageId; loginPluginRequestPacket.messageId = messageId;
loginPluginRequestPacket.channel = channel; loginPluginRequestPacket.channel = channel;
loginPluginRequestPacket.data = null; loginPluginRequestPacket.data = null;
connection.sendPacket(loginPluginRequestPacket); connection.sendPacket(loginPluginRequestPacket);
return; return;
} }
} }
} if (MojangAuth.isEnabled() && isSocketConnection) {
if (MojangAuth.isEnabled() && isNettyClient) {
// Mojang auth // Mojang auth
if (CONNECTION_MANAGER.getPlayer(username) != null) { if (CONNECTION_MANAGER.getPlayer(username) != null) {
connection.sendPacket(new LoginDisconnectPacket(ALREADY_CONNECTED)); connection.sendPacket(new LoginDisconnectPacket(ALREADY_CONNECTED));
connection.disconnect(); connection.disconnect();
return; return;
} }
final PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection;
final NettyPlayerConnection nettyPlayerConnection = (NettyPlayerConnection) connection; socketConnection.setConnectionState(ConnectionState.LOGIN);
EncryptionRequestPacket encryptionRequestPacket = new EncryptionRequestPacket(socketConnection);
nettyPlayerConnection.setConnectionState(ConnectionState.LOGIN); socketConnection.sendPacket(encryptionRequestPacket);
EncryptionRequestPacket encryptionRequestPacket = new EncryptionRequestPacket(nettyPlayerConnection);
nettyPlayerConnection.sendPacket(encryptionRequestPacket);
} else { } else {
final boolean bungee = BungeeCordProxy.isEnabled(); final boolean bungee = BungeeCordProxy.isEnabled();
// Offline // Offline
final UUID playerUuid = bungee && isNettyClient ? final UUID playerUuid = bungee && isSocketConnection ?
((NettyPlayerConnection) connection).getBungeeUuid() : ((PlayerSocketConnection) connection).getBungeeUuid() :
CONNECTION_MANAGER.getPlayerConnectionUuid(connection, username); CONNECTION_MANAGER.getPlayerConnectionUuid(connection, username);
Player player = CONNECTION_MANAGER.startPlayState(connection, playerUuid, username, true); Player player = CONNECTION_MANAGER.startPlayState(connection, playerUuid, username, true);
if (bungee && isNettyClient) { if (bungee && isSocketConnection) {
player.setSkin(((NettyPlayerConnection) connection).getBungeeSkin()); player.setSkin(((PlayerSocketConnection) connection).getBungeeSkin());
} }
} }
} }
@ -104,7 +92,7 @@ public class LoginStartPacket implements ClientPreplayPacket {
@Override @Override
public void write(@NotNull BinaryWriter writer) { public void write(@NotNull BinaryWriter writer) {
if(username.length() > 16) if (username.length() > 16)
throw new IllegalArgumentException("Username is not allowed to be longer than 16 characters"); throw new IllegalArgumentException("Username is not allowed to be longer than 16 characters");
writer.writeSizedString(username); writer.writeSizedString(username);
} }

View File

@ -4,7 +4,7 @@ import net.minestom.server.data.type.array.ByteArrayData;
import net.minestom.server.extras.MojangAuth; import net.minestom.server.extras.MojangAuth;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.network.packet.server.ServerPacketIdentifier;
import net.minestom.server.network.player.NettyPlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.utils.binary.BinaryReader; import net.minestom.server.utils.binary.BinaryReader;
import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.BinaryWriter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -16,7 +16,7 @@ public class EncryptionRequestPacket implements ServerPacket {
public byte[] publicKey; public byte[] publicKey;
public byte[] nonce = new byte[4]; public byte[] nonce = new byte[4];
public EncryptionRequestPacket(NettyPlayerConnection connection) { public EncryptionRequestPacket(PlayerSocketConnection connection) {
ThreadLocalRandom.current().nextBytes(nonce); ThreadLocalRandom.current().nextBytes(nonce);
connection.setNonce(nonce); connection.setNonce(nonce);
} }

View File

@ -21,7 +21,6 @@ import java.util.concurrent.atomic.AtomicInteger;
* It can be extended to create a new kind of player (NPC for instance). * It can be extended to create a new kind of player (NPC for instance).
*/ */
public abstract class PlayerConnection { public abstract class PlayerConnection {
protected static final PacketListenerManager PACKET_LISTENER_MANAGER = MinecraftServer.getPacketListenerManager(); protected static final PacketListenerManager PACKET_LISTENER_MANAGER = MinecraftServer.getPacketListenerManager();
private Player player; private Player player;
@ -63,8 +62,7 @@ public abstract class PlayerConnection {
} }
} }
@NotNull public @NotNull AtomicInteger getPacketCounter() {
public AtomicInteger getPacketCounter() {
return packetCounter; return packetCounter;
} }
@ -74,8 +72,7 @@ public abstract class PlayerConnection {
* *
* @return this connection identifier * @return this connection identifier
*/ */
@NotNull public @NotNull String getIdentifier() {
public String getIdentifier() {
final Player player = getPlayer(); final Player player = getPlayer();
return player != null ? return player != null ?
player.getUsername() : player.getUsername() :
@ -114,9 +111,7 @@ public abstract class PlayerConnection {
* *
* @return the remote address * @return the remote address
*/ */
@NotNull public abstract @NotNull SocketAddress getRemoteAddress();
public abstract SocketAddress getRemoteAddress();
/** /**
* Gets protocol version of client. * Gets protocol version of client.
@ -197,8 +192,7 @@ public abstract class PlayerConnection {
* *
* @return the client connection state * @return the client connection state
*/ */
@NotNull public @NotNull ConnectionState getConnectionState() {
public ConnectionState getConnectionState() {
return connectionState; return connectionState;
} }

View File

@ -36,11 +36,12 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.DataFormatException; import java.util.zip.DataFormatException;
/** /**
* Represents a networking connection with Netty. * Represents a socket connection.
* <p> * <p>
* It is the implementation used for all network client. * It is the implementation used for all network client.
*/ */
public class NettyPlayerConnection extends PlayerConnection { @ApiStatus.Internal
public class PlayerSocketConnection extends PlayerConnection {
private final Worker worker; private final Worker worker;
private final SocketChannel channel; private final SocketChannel channel;
private SocketAddress remoteAddress; private SocketAddress remoteAddress;
@ -70,7 +71,7 @@ public class NettyPlayerConnection extends PlayerConnection {
private final BinaryBuffer tickBuffer = BinaryBuffer.ofSize(Server.SOCKET_BUFFER_SIZE); private final BinaryBuffer tickBuffer = BinaryBuffer.ofSize(Server.SOCKET_BUFFER_SIZE);
private volatile BinaryBuffer cacheBuffer; private volatile BinaryBuffer cacheBuffer;
public NettyPlayerConnection(@NotNull Worker worker, @NotNull SocketChannel channel, SocketAddress remoteAddress) { public PlayerSocketConnection(@NotNull Worker worker, @NotNull SocketChannel channel, SocketAddress remoteAddress) {
super(); super();
this.worker = worker; this.worker = worker;
this.channel = channel; this.channel = channel;
@ -279,7 +280,6 @@ public class NettyPlayerConnection extends PlayerConnection {
this.remoteAddress = remoteAddress; this.remoteAddress = remoteAddress;
} }
@Override @Override
public void disconnect() { public void disconnect() {
this.worker.disconnect(this, channel); this.worker.disconnect(this, channel);

View File

@ -3,7 +3,7 @@ package net.minestom.server.network.socket;
import net.minestom.server.MinecraftServer; import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.Player; import net.minestom.server.entity.Player;
import net.minestom.server.network.PacketProcessor; import net.minestom.server.network.PacketProcessor;
import net.minestom.server.network.player.NettyPlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.utils.binary.BinaryBuffer; import net.minestom.server.utils.binary.BinaryBuffer;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
@ -21,7 +21,7 @@ import java.util.zip.Inflater;
@ApiStatus.Internal @ApiStatus.Internal
public final class Worker { public final class Worker {
final Selector selector = Selector.open(); final Selector selector = Selector.open();
private final Map<SocketChannel, NettyPlayerConnection> connectionMap = new ConcurrentHashMap<>(); private final Map<SocketChannel, PlayerSocketConnection> connectionMap = new ConcurrentHashMap<>();
private final PacketProcessor packetProcessor; private final PacketProcessor packetProcessor;
public Worker(Server server, PacketProcessor packetProcessor) throws IOException { public Worker(Server server, PacketProcessor packetProcessor) throws IOException {
@ -65,7 +65,7 @@ public final class Worker {
} }
public void receiveConnection(SocketChannel channel) throws IOException { public void receiveConnection(SocketChannel channel) throws IOException {
this.connectionMap.put(channel, new NettyPlayerConnection(this, channel, channel.getRemoteAddress())); this.connectionMap.put(channel, new PlayerSocketConnection(this, channel, channel.getRemoteAddress()));
channel.configureBlocking(false); channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ); channel.register(selector, SelectionKey.OP_READ);
var socket = channel.socket(); var socket = channel.socket();
@ -75,7 +75,7 @@ public final class Worker {
this.selector.wakeup(); this.selector.wakeup();
} }
public void disconnect(NettyPlayerConnection connection, SocketChannel channel) { public void disconnect(PlayerSocketConnection connection, SocketChannel channel) {
try { try {
channel.close(); channel.close();
this.connectionMap.remove(channel); this.connectionMap.remove(channel);

View File

@ -10,7 +10,7 @@ import net.minestom.server.listener.manager.PacketListenerManager;
import net.minestom.server.network.packet.FramedPacket; import net.minestom.server.network.packet.FramedPacket;
import net.minestom.server.network.packet.server.ComponentHoldingServerPacket; import net.minestom.server.network.packet.server.ComponentHoldingServerPacket;
import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.player.NettyPlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.network.socket.Server; import net.minestom.server.network.socket.Server;
import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.BinaryWriter;
@ -96,8 +96,8 @@ public final class PacketUtils {
if (!player.isOnline() || !playerValidator.isValid(player)) if (!player.isOnline() || !playerValidator.isValid(player))
continue; continue;
final PlayerConnection connection = player.getPlayerConnection(); final PlayerConnection connection = player.getPlayerConnection();
if (connection instanceof NettyPlayerConnection) { if (connection instanceof PlayerSocketConnection) {
((NettyPlayerConnection) connection).write(framedPacket); ((PlayerSocketConnection) connection).write(framedPacket);
} else { } else {
connection.sendPacket(packet); connection.sendPacket(packet);
} }

View File

@ -2,25 +2,23 @@ package net.minestom.server.utils.player;
import net.minestom.server.entity.Entity; import net.minestom.server.entity.Entity;
import net.minestom.server.entity.Player; import net.minestom.server.entity.Player;
import net.minestom.server.network.player.NettyPlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection;
import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerConnection;
public final class PlayerUtils { public final class PlayerUtils {
private PlayerUtils() { private PlayerUtils() {
} }
public static boolean isNettyClient(PlayerConnection playerConnection) { public static boolean isSocketClient(PlayerConnection playerConnection) {
return playerConnection instanceof NettyPlayerConnection; return playerConnection instanceof PlayerSocketConnection;
} }
public static boolean isNettyClient(Player player) { public static boolean isSocketClient(Player player) {
return isNettyClient(player.getPlayerConnection()); return isSocketClient(player.getPlayerConnection());
} }
public static boolean isNettyClient(Entity entity) { public static boolean isSocketClient(Entity entity) {
return (entity instanceof Player) && isNettyClient((Player) entity); return (entity instanceof Player) && isSocketClient((Player) entity);
} }
} }