Move CraftBukkit per-file patches

By: Initial <noreply+automated@papermc.io>
This commit is contained in:
CraftBukkit/Spigot
2024-12-11 22:26:36 +01:00
parent a4de181b77
commit a265d64138
583 changed files with 71 additions and 857 deletions

View File

@@ -0,0 +1,69 @@
--- a/net/minecraft/server/network/HandshakeListener.java
+++ b/net/minecraft/server/network/HandshakeListener.java
@@ -13,8 +13,17 @@
import net.minecraft.network.protocol.status.StatusProtocols;
import net.minecraft.server.MinecraftServer;
+// CraftBukkit start
+import java.net.InetAddress;
+import java.util.HashMap;
+// CraftBukkit end
+
public class HandshakeListener implements PacketHandshakingInListener {
+ // CraftBukkit start - add fields
+ private static final HashMap<InetAddress, Long> throttleTracker = new HashMap<InetAddress, Long>();
+ private static int throttleCounter = 0;
+ // CraftBukkit end
private static final IChatBaseComponent IGNORE_STATUS_REASON = IChatBaseComponent.translatable("disconnect.ignoring_status_request");
private final MinecraftServer server;
private final NetworkManager connection;
@@ -26,6 +35,7 @@
@Override
public void handleIntention(PacketHandshakingInSetProtocol packethandshakinginsetprotocol) {
+ this.connection.hostname = packethandshakinginsetprotocol.hostName() + ":" + packethandshakinginsetprotocol.port(); // CraftBukkit - set hostname
switch (packethandshakinginsetprotocol.intention()) {
case LOGIN:
this.beginLogin(packethandshakinginsetprotocol, false);
@@ -59,6 +69,40 @@
private void beginLogin(PacketHandshakingInSetProtocol packethandshakinginsetprotocol, boolean flag) {
this.connection.setupOutboundProtocol(LoginProtocols.CLIENTBOUND);
+ // CraftBukkit start - Connection throttle
+ try {
+ long currentTime = System.currentTimeMillis();
+ long connectionThrottle = this.server.server.getConnectionThrottle();
+ InetAddress address = ((java.net.InetSocketAddress) this.connection.getRemoteAddress()).getAddress();
+
+ synchronized (throttleTracker) {
+ if (throttleTracker.containsKey(address) && !"127.0.0.1".equals(address.getHostAddress()) && currentTime - throttleTracker.get(address) < connectionThrottle) {
+ throttleTracker.put(address, currentTime);
+ IChatMutableComponent chatmessage = IChatBaseComponent.literal("Connection throttled! Please wait before reconnecting.");
+ this.connection.send(new PacketLoginOutDisconnect(chatmessage));
+ this.connection.disconnect(chatmessage);
+ return;
+ }
+
+ throttleTracker.put(address, currentTime);
+ throttleCounter++;
+ if (throttleCounter > 200) {
+ throttleCounter = 0;
+
+ // Cleanup stale entries
+ java.util.Iterator iter = throttleTracker.entrySet().iterator();
+ while (iter.hasNext()) {
+ java.util.Map.Entry<InetAddress, Long> entry = (java.util.Map.Entry) iter.next();
+ if (entry.getValue() > connectionThrottle) {
+ iter.remove();
+ }
+ }
+ }
+ }
+ } catch (Throwable t) {
+ org.apache.logging.log4j.LogManager.getLogger().debug("Failed to check connection throttle", t);
+ }
+ // CraftBukkit end
if (packethandshakinginsetprotocol.protocolVersion() != SharedConstants.getCurrentVersion().getProtocolVersion()) {
IChatMutableComponent ichatmutablecomponent;

View File

@@ -0,0 +1,45 @@
--- a/net/minecraft/server/network/LegacyPingHandler.java
+++ b/net/minecraft/server/network/LegacyPingHandler.java
@@ -35,10 +35,11 @@
SocketAddress socketaddress = channelhandlercontext.channel().remoteAddress();
int i = bytebuf.readableBytes();
String s;
+ org.bukkit.event.server.ServerListPingEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callServerListPingEvent(socketaddress, server.getMotd(), server.getPlayerCount(), server.getMaxPlayers()); // CraftBukkit
if (i == 0) {
LegacyPingHandler.LOGGER.debug("Ping: (<1.3.x) from {}", socketaddress);
- s = createVersion0Response(this.server);
+ s = createVersion0Response(this.server, event); // CraftBukkit
sendFlushAndClose(channelhandlercontext, createLegacyDisconnectPacket(channelhandlercontext.alloc(), s));
} else {
if (bytebuf.readUnsignedByte() != 1) {
@@ -55,7 +56,7 @@
LegacyPingHandler.LOGGER.debug("Ping: (1.4-1.5.x) from {}", socketaddress);
}
- s = createVersion1Response(this.server);
+ s = createVersion1Response(this.server, event); // CraftBukkit
sendFlushAndClose(channelhandlercontext, createLegacyDisconnectPacket(channelhandlercontext.alloc(), s));
}
@@ -106,12 +107,16 @@
}
}
- private static String createVersion0Response(ServerInfo serverinfo) {
- return String.format(Locale.ROOT, "%s\u00a7%d\u00a7%d", serverinfo.getMotd(), serverinfo.getPlayerCount(), serverinfo.getMaxPlayers());
+ // CraftBukkit start
+ private static String createVersion0Response(ServerInfo serverinfo, org.bukkit.event.server.ServerListPingEvent event) {
+ return String.format(Locale.ROOT, "%s\u00a7%d\u00a7%d", event.getMotd(), event.getNumPlayers(), event.getMaxPlayers());
+ // CraftBukkit end
}
- private static String createVersion1Response(ServerInfo serverinfo) {
- return String.format(Locale.ROOT, "\u00a71\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", 127, serverinfo.getServerVersion(), serverinfo.getMotd(), serverinfo.getPlayerCount(), serverinfo.getMaxPlayers());
+ // CraftBukkit start
+ private static String createVersion1Response(ServerInfo serverinfo, org.bukkit.event.server.ServerListPingEvent event) {
+ return String.format(Locale.ROOT, "\u00a71\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", 127, serverinfo.getServerVersion(), event.getMotd(), event.getNumPlayers(), event.getMaxPlayers());
+ // CraftBukkit end
}
private static void sendFlushAndClose(ChannelHandlerContext channelhandlercontext, ByteBuf bytebuf) {

View File

@@ -0,0 +1,245 @@
--- a/net/minecraft/server/network/LoginListener.java
+++ b/net/minecraft/server/network/LoginListener.java
@@ -44,8 +44,38 @@
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
-public class LoginListener implements PacketLoginInListener, TickablePacketListener {
+// CraftBukkit start
+import net.minecraft.network.EnumProtocol;
+import net.minecraft.network.protocol.Packet;
+import net.minecraft.network.protocol.PlayerConnectionUtils;
+import net.minecraft.server.level.EntityPlayer;
+import org.bukkit.craftbukkit.entity.CraftPlayer;
+import org.bukkit.craftbukkit.util.Waitable;
+import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
+import org.bukkit.event.player.PlayerPreLoginEvent;
+
+public class LoginListener implements PacketLoginInListener, TickablePacketListener, CraftPlayer.TransferCookieConnection {
+
+ @Override
+ public boolean isTransferred() {
+ return this.transferred;
+ }
+
+ @Override
+ public EnumProtocol getProtocol() {
+ return EnumProtocol.LOGIN;
+ }
+
+ @Override
+ public void sendPacket(Packet<?> packet) {
+ this.connection.send(packet);
+ }
+ @Override
+ public void kickPlayer(IChatBaseComponent reason) {
+ disconnect(reason);
+ }
+ // CraftBukkit end
private static final AtomicInteger UNIQUE_THREAD_ID = new AtomicInteger(0);
static final Logger LOGGER = LogUtils.getLogger();
private static final int MAX_TICKS_BEFORE_LOGIN = 600;
@@ -60,6 +90,7 @@
private GameProfile authenticatedProfile;
private final String serverId;
private final boolean transferred;
+ private EntityPlayer player; // CraftBukkit
public LoginListener(MinecraftServer minecraftserver, NetworkManager networkmanager, boolean flag) {
this.state = LoginListener.EnumProtocolState.HELLO;
@@ -76,6 +107,12 @@
this.verifyLoginAndFinishConnectionSetup((GameProfile) Objects.requireNonNull(this.authenticatedProfile));
}
+ // CraftBukkit start
+ if (this.state == LoginListener.EnumProtocolState.WAITING_FOR_COOKIES && !this.player.getBukkitEntity().isAwaitingCookies()) {
+ this.postCookies(this.authenticatedProfile);
+ }
+ // CraftBukkit end
+
if (this.state == LoginListener.EnumProtocolState.WAITING_FOR_DUPE_DISCONNECT && !this.isPlayerAlreadyInWorld((GameProfile) Objects.requireNonNull(this.authenticatedProfile))) {
this.finishLoginAndWaitForClient(this.authenticatedProfile);
}
@@ -86,6 +123,13 @@
}
+ // CraftBukkit start
+ @Deprecated
+ public void disconnect(String s) {
+ disconnect(IChatBaseComponent.literal(s));
+ }
+ // CraftBukkit end
+
@Override
public boolean isAcceptingMessages() {
return this.connection.isConnected();
@@ -131,7 +175,27 @@
this.state = LoginListener.EnumProtocolState.KEY;
this.connection.send(new PacketLoginOutEncryptionBegin("", this.server.getKeyPair().getPublic().getEncoded(), this.challenge, true));
} else {
- this.startClientVerification(UUIDUtil.createOfflineProfile(this.requestedUsername));
+ // CraftBukkit start
+ Thread thread = new Thread("User Authenticator #" + LoginListener.UNIQUE_THREAD_ID.incrementAndGet()) {
+
+ @Override
+ public void run() {
+ try {
+ GameProfile gameprofile = UUIDUtil.createOfflineProfile(LoginListener.this.requestedUsername);
+
+ LoginListener.this.callPlayerPreLoginEvents(gameprofile);
+ LoginListener.LOGGER.info("UUID of player {} is {}", gameprofile.getName(), gameprofile.getId());
+ LoginListener.this.startClientVerification(gameprofile);
+ } catch (Exception ex) {
+ disconnect("Failed to verify username!");
+ server.server.getLogger().log(java.util.logging.Level.WARNING, "Exception verifying " + LoginListener.this.requestedUsername, ex);
+ }
+ }
+ };
+
+ thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LoginListener.LOGGER));
+ thread.start();
+ // CraftBukkit end
}
}
@@ -144,10 +208,24 @@
private void verifyLoginAndFinishConnectionSetup(GameProfile gameprofile) {
PlayerList playerlist = this.server.getPlayerList();
- IChatBaseComponent ichatbasecomponent = playerlist.canPlayerLogin(this.connection.getRemoteAddress(), gameprofile);
+ // CraftBukkit start - fire PlayerLoginEvent
+ this.player = playerlist.canPlayerLogin(this, gameprofile); // CraftBukkit
- if (ichatbasecomponent != null) {
- this.disconnect(ichatbasecomponent);
+ if (this.player != null) {
+ if (this.player.getBukkitEntity().isAwaitingCookies()) {
+ this.state = LoginListener.EnumProtocolState.WAITING_FOR_COOKIES;
+ } else {
+ this.postCookies(gameprofile);
+ }
+ }
+ }
+
+ private void postCookies(GameProfile gameprofile) {
+ PlayerList playerlist = this.server.getPlayerList();
+
+ if (this.player == null) {
+ // this.disconnect(ichatbasecomponent);
+ // CraftBukkit end
} else {
if (this.server.getCompressionThreshold() >= 0 && !this.connection.isMemoryConnection()) {
this.connection.send(new PacketLoginOutSetCompression(this.server.getCompressionThreshold()), PacketSendListener.thenRun(() -> {
@@ -155,7 +233,7 @@
}));
}
- boolean flag = playerlist.disconnectAllPlayersWithProfile(gameprofile);
+ boolean flag = playerlist.disconnectAllPlayersWithProfile(gameprofile, this.player); // CraftBukkit - add player reference
if (flag) {
this.state = LoginListener.EnumProtocolState.WAITING_FOR_DUPE_DISCONNECT;
@@ -205,6 +283,12 @@
if (profileresult != null) {
GameProfile gameprofile = profileresult.profile();
+ // CraftBukkit start - fire PlayerPreLoginEvent
+ if (!connection.isConnected()) {
+ return;
+ }
+ LoginListener.this.callPlayerPreLoginEvents(gameprofile);
+ // CraftBukkit end
LoginListener.LOGGER.info("UUID of player {} is {}", gameprofile.getName(), gameprofile.getId());
LoginListener.this.startClientVerification(gameprofile);
} else if (LoginListener.this.server.isSingleplayer()) {
@@ -222,6 +306,11 @@
LoginListener.this.disconnect(IChatBaseComponent.translatable("multiplayer.disconnect.authservers_down"));
LoginListener.LOGGER.error("Couldn't verify username because servers are unavailable");
}
+ // CraftBukkit start - catch all exceptions
+ } catch (Exception exception) {
+ disconnect("Failed to verify username!");
+ server.server.getLogger().log(java.util.logging.Level.WARNING, "Exception verifying " + s1, exception);
+ // CraftBukkit end
}
}
@@ -238,6 +327,43 @@
thread.start();
}
+ // CraftBukkit start
+ private void callPlayerPreLoginEvents(GameProfile gameprofile) throws Exception {
+ String playerName = gameprofile.getName();
+ java.net.InetAddress address = ((java.net.InetSocketAddress) connection.getRemoteAddress()).getAddress();
+ java.util.UUID uniqueId = gameprofile.getId();
+ final org.bukkit.craftbukkit.CraftServer server = LoginListener.this.server.server;
+
+ AsyncPlayerPreLoginEvent asyncEvent = new AsyncPlayerPreLoginEvent(playerName, address, uniqueId, this.transferred);
+ server.getPluginManager().callEvent(asyncEvent);
+
+ if (PlayerPreLoginEvent.getHandlerList().getRegisteredListeners().length != 0) {
+ final PlayerPreLoginEvent event = new PlayerPreLoginEvent(playerName, address, uniqueId);
+ if (asyncEvent.getResult() != PlayerPreLoginEvent.Result.ALLOWED) {
+ event.disallow(asyncEvent.getResult(), asyncEvent.getKickMessage());
+ }
+ Waitable<PlayerPreLoginEvent.Result> waitable = new Waitable<PlayerPreLoginEvent.Result>() {
+ @Override
+ protected PlayerPreLoginEvent.Result evaluate() {
+ server.getPluginManager().callEvent(event);
+ return event.getResult();
+ }
+ };
+
+ LoginListener.this.server.processQueue.add(waitable);
+ if (waitable.get() != PlayerPreLoginEvent.Result.ALLOWED) {
+ disconnect(event.getKickMessage());
+ return;
+ }
+ } else {
+ if (asyncEvent.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) {
+ disconnect(asyncEvent.getKickMessage());
+ return;
+ }
+ }
+ }
+ // CraftBukkit end
+
@Override
public void handleCustomQueryPacket(ServerboundCustomQueryAnswerPacket serverboundcustomqueryanswerpacket) {
this.disconnect(ServerCommonPacketListenerImpl.DISCONNECT_UNEXPECTED_QUERY);
@@ -245,10 +371,11 @@
@Override
public void handleLoginAcknowledgement(ServerboundLoginAcknowledgedPacket serverboundloginacknowledgedpacket) {
+ PlayerConnectionUtils.ensureRunningOnSameThread(serverboundloginacknowledgedpacket, this, this.server); // CraftBukkit
Validate.validState(this.state == LoginListener.EnumProtocolState.PROTOCOL_SWITCHING, "Unexpected login acknowledgement packet", new Object[0]);
this.connection.setupOutboundProtocol(ConfigurationProtocols.CLIENTBOUND);
CommonListenerCookie commonlistenercookie = CommonListenerCookie.createInitial((GameProfile) Objects.requireNonNull(this.authenticatedProfile), this.transferred);
- ServerConfigurationPacketListenerImpl serverconfigurationpacketlistenerimpl = new ServerConfigurationPacketListenerImpl(this.server, this.connection, commonlistenercookie);
+ ServerConfigurationPacketListenerImpl serverconfigurationpacketlistenerimpl = new ServerConfigurationPacketListenerImpl(this.server, this.connection, commonlistenercookie, this.player); // CraftBukkit
this.connection.setupInboundProtocol(ConfigurationProtocols.SERVERBOUND, serverconfigurationpacketlistenerimpl);
serverconfigurationpacketlistenerimpl.startConfiguration();
@@ -264,12 +391,18 @@
@Override
public void handleCookieResponse(ServerboundCookieResponsePacket serverboundcookieresponsepacket) {
+ // CraftBukkit start
+ PlayerConnectionUtils.ensureRunningOnSameThread(serverboundcookieresponsepacket, this, this.server);
+ if (this.player != null && this.player.getBukkitEntity().handleCookieResponse(serverboundcookieresponsepacket)) {
+ return;
+ }
+ // CraftBukkit end
this.disconnect(ServerCommonPacketListenerImpl.DISCONNECT_UNEXPECTED_QUERY);
}
private static enum EnumProtocolState {
- HELLO, KEY, AUTHENTICATING, NEGOTIATING, VERIFYING, WAITING_FOR_DUPE_DISCONNECT, PROTOCOL_SWITCHING, ACCEPTED;
+ HELLO, KEY, AUTHENTICATING, NEGOTIATING, VERIFYING, WAITING_FOR_COOKIES, WAITING_FOR_DUPE_DISCONNECT, PROTOCOL_SWITCHING, ACCEPTED; // CraftBukkit
private EnumProtocolState() {}
}

View File

@@ -0,0 +1,127 @@
--- a/net/minecraft/server/network/PacketStatusListener.java
+++ b/net/minecraft/server/network/PacketStatusListener.java
@@ -10,6 +10,21 @@
import net.minecraft.network.protocol.status.PacketStatusOutServerInfo;
import net.minecraft.network.protocol.status.ServerPing;
+// CraftBukkit start
+import com.mojang.authlib.GameProfile;
+import java.net.InetSocketAddress;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.Optional;
+import net.minecraft.SharedConstants;
+import net.minecraft.network.protocol.status.ServerPing;
+import net.minecraft.server.MinecraftServer;
+import net.minecraft.server.level.EntityPlayer;
+import org.bukkit.craftbukkit.util.CraftChatMessage;
+import org.bukkit.craftbukkit.util.CraftIconCache;
+import org.bukkit.entity.Player;
+// CraftBukkit end
+
public class PacketStatusListener implements PacketStatusInListener {
private static final IChatBaseComponent DISCONNECT_REASON = IChatBaseComponent.translatable("multiplayer.status.request_handled");
@@ -36,7 +51,101 @@
this.connection.disconnect(PacketStatusListener.DISCONNECT_REASON);
} else {
this.hasRequestedStatus = true;
- this.connection.send(new PacketStatusOutServerInfo(this.status));
+ // CraftBukkit start
+ // this.connection.send(new PacketStatusOutServerInfo(this.status));
+ MinecraftServer server = MinecraftServer.getServer();
+ final Object[] players = server.getPlayerList().players.toArray();
+ class ServerListPingEvent extends org.bukkit.event.server.ServerListPingEvent {
+
+ CraftIconCache icon = server.server.getServerIcon();
+
+ ServerListPingEvent() {
+ super(connection.hostname, ((InetSocketAddress) connection.getRemoteAddress()).getAddress(), server.getMotd(), server.getPlayerList().getMaxPlayers());
+ }
+
+ @Override
+ public void setServerIcon(org.bukkit.util.CachedServerIcon icon) {
+ if (!(icon instanceof CraftIconCache)) {
+ throw new IllegalArgumentException(icon + " was not created by " + org.bukkit.craftbukkit.CraftServer.class);
+ }
+ this.icon = (CraftIconCache) icon;
+ }
+
+ @Override
+ public Iterator<Player> iterator() throws UnsupportedOperationException {
+ return new Iterator<Player>() {
+ int i;
+ int ret = Integer.MIN_VALUE;
+ EntityPlayer player;
+
+ @Override
+ public boolean hasNext() {
+ if (player != null) {
+ return true;
+ }
+ final Object[] currentPlayers = players;
+ for (int length = currentPlayers.length, i = this.i; i < length; i++) {
+ final EntityPlayer player = (EntityPlayer) currentPlayers[i];
+ if (player != null) {
+ this.i = i + 1;
+ this.player = player;
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public Player next() {
+ if (!hasNext()) {
+ throw new java.util.NoSuchElementException();
+ }
+ final EntityPlayer player = this.player;
+ this.player = null;
+ this.ret = this.i - 1;
+ return player.getBukkitEntity();
+ }
+
+ @Override
+ public void remove() {
+ final Object[] currentPlayers = players;
+ final int i = this.ret;
+ if (i < 0 || currentPlayers[i] == null) {
+ throw new IllegalStateException();
+ }
+ currentPlayers[i] = null;
+ }
+ };
+ }
+ }
+
+ ServerListPingEvent event = new ServerListPingEvent();
+ server.server.getPluginManager().callEvent(event);
+
+ java.util.List<GameProfile> profiles = new java.util.ArrayList<GameProfile>(players.length);
+ for (Object player : players) {
+ if (player != null) {
+ EntityPlayer entityPlayer = ((EntityPlayer) player);
+ if (entityPlayer.allowsListing()) {
+ profiles.add(entityPlayer.getGameProfile());
+ } else {
+ profiles.add(MinecraftServer.ANONYMOUS_PLAYER_PROFILE);
+ }
+ }
+ }
+
+ ServerPing.ServerPingPlayerSample playerSample = new ServerPing.ServerPingPlayerSample(event.getMaxPlayers(), event.getNumPlayers(), (server.hidesOnlinePlayers()) ? Collections.emptyList() : profiles);
+
+ ServerPing ping = new ServerPing(
+ CraftChatMessage.fromString(event.getMotd(), true)[0],
+ Optional.of(playerSample),
+ Optional.of(new ServerPing.ServerData(server.getServerModName() + " " + server.getServerVersion(), SharedConstants.getCurrentVersion().getProtocolVersion())),
+ (event.icon.value != null) ? Optional.of(new ServerPing.a(event.icon.value)) : Optional.empty(),
+ server.enforceSecureProfile()
+ );
+
+ this.connection.send(new PacketStatusOutServerInfo(ping));
+ // CraftBukkit end
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,246 @@
--- a/net/minecraft/server/network/ServerCommonPacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerCommonPacketListenerImpl.java
@@ -29,8 +29,44 @@
import net.minecraft.util.thread.IAsyncTaskHandler;
import org.slf4j.Logger;
-public abstract class ServerCommonPacketListenerImpl implements ServerCommonPacketListener {
+// CraftBukkit start
+import io.netty.buffer.ByteBuf;
+import java.util.concurrent.ExecutionException;
+import net.minecraft.EnumChatFormat;
+import net.minecraft.network.EnumProtocol;
+import net.minecraft.network.protocol.common.custom.DiscardedPayload;
+import net.minecraft.network.protocol.game.PacketPlayOutSpawnPosition;
+import net.minecraft.resources.MinecraftKey;
+import net.minecraft.server.level.EntityPlayer;
+import org.bukkit.craftbukkit.entity.CraftPlayer;
+import org.bukkit.craftbukkit.util.CraftChatMessage;
+import org.bukkit.craftbukkit.util.CraftLocation;
+import org.bukkit.craftbukkit.util.Waitable;
+import org.bukkit.event.player.PlayerKickEvent;
+import org.bukkit.event.player.PlayerResourcePackStatusEvent;
+
+public abstract class ServerCommonPacketListenerImpl implements ServerCommonPacketListener, CraftPlayer.TransferCookieConnection {
+
+ @Override
+ public boolean isTransferred() {
+ return this.transferred;
+ }
+ @Override
+ public EnumProtocol getProtocol() {
+ return protocol();
+ }
+
+ @Override
+ public void sendPacket(Packet<?> packet) {
+ send(packet);
+ }
+
+ @Override
+ public void kickPlayer(IChatBaseComponent reason) {
+ disconnect(reason);
+ }
+ // CraftBukkit end
private static final Logger LOGGER = LogUtils.getLogger();
public static final int LATENCY_CHECK_INTERVAL = 15000;
private static final int CLOSED_LISTENER_TIMEOUT = 15000;
@@ -47,12 +83,24 @@
private int latency;
private volatile boolean suspendFlushingOnServerThread = false;
- public ServerCommonPacketListenerImpl(MinecraftServer minecraftserver, NetworkManager networkmanager, CommonListenerCookie commonlistenercookie) {
+ public ServerCommonPacketListenerImpl(MinecraftServer minecraftserver, NetworkManager networkmanager, CommonListenerCookie commonlistenercookie, EntityPlayer player) { // CraftBukkit
this.server = minecraftserver;
this.connection = networkmanager;
this.keepAliveTime = SystemUtils.getMillis();
this.latency = commonlistenercookie.latency();
this.transferred = commonlistenercookie.transferred();
+ // CraftBukkit start - add fields and methods
+ this.player = player;
+ this.player.transferCookieConnection = this;
+ this.cserver = minecraftserver.server;
+ }
+ protected final EntityPlayer player;
+ protected final org.bukkit.craftbukkit.CraftServer cserver;
+ public boolean processedDisconnect;
+
+ public CraftPlayer getCraftPlayer() {
+ return (this.player == null) ? null : (CraftPlayer) this.player.getBukkitEntity();
+ // CraftBukkit end
}
private void close() {
@@ -80,6 +128,7 @@
@Override
public void handleKeepAlive(ServerboundKeepAlivePacket serverboundkeepalivepacket) {
+ PlayerConnectionUtils.ensureRunningOnSameThread(serverboundkeepalivepacket, this, this.player.serverLevel()); // CraftBukkit
if (this.keepAlivePending && serverboundkeepalivepacket.getId() == this.keepAliveChallenge) {
int i = (int) (SystemUtils.getMillis() - this.keepAliveTime);
@@ -94,8 +143,56 @@
@Override
public void handlePong(ServerboundPongPacket serverboundpongpacket) {}
+ // CraftBukkit start
+ private static final MinecraftKey CUSTOM_REGISTER = MinecraftKey.withDefaultNamespace("register");
+ private static final MinecraftKey CUSTOM_UNREGISTER = MinecraftKey.withDefaultNamespace("unregister");
+
@Override
- public void handleCustomPayload(ServerboundCustomPayloadPacket serverboundcustompayloadpacket) {}
+ public void handleCustomPayload(ServerboundCustomPayloadPacket serverboundcustompayloadpacket) {
+ if (!(serverboundcustompayloadpacket.payload() instanceof DiscardedPayload)) {
+ return;
+ }
+ PlayerConnectionUtils.ensureRunningOnSameThread(serverboundcustompayloadpacket, this, this.player.serverLevel());
+ MinecraftKey identifier = serverboundcustompayloadpacket.payload().type().id();
+ ByteBuf payload = ((DiscardedPayload)serverboundcustompayloadpacket.payload()).data();
+
+ if (identifier.equals(CUSTOM_REGISTER)) {
+ try {
+ String channels = payload.toString(com.google.common.base.Charsets.UTF_8);
+ for (String channel : channels.split("\0")) {
+ getCraftPlayer().addChannel(channel);
+ }
+ } catch (Exception ex) {
+ PlayerConnection.LOGGER.error("Couldn\'t register custom payload", ex);
+ this.disconnect(IChatBaseComponent.literal("Invalid payload REGISTER!"));
+ }
+ } else if (identifier.equals(CUSTOM_UNREGISTER)) {
+ try {
+ String channels = payload.toString(com.google.common.base.Charsets.UTF_8);
+ for (String channel : channels.split("\0")) {
+ getCraftPlayer().removeChannel(channel);
+ }
+ } catch (Exception ex) {
+ PlayerConnection.LOGGER.error("Couldn\'t unregister custom payload", ex);
+ this.disconnect(IChatBaseComponent.literal("Invalid payload UNREGISTER!"));
+ }
+ } else {
+ try {
+ byte[] data = new byte[payload.readableBytes()];
+ payload.readBytes(data);
+ cserver.getMessenger().dispatchIncomingMessage(player.getBukkitEntity(), identifier.toString(), data);
+ } catch (Exception ex) {
+ PlayerConnection.LOGGER.error("Couldn\'t dispatch custom payload", ex);
+ this.disconnect(IChatBaseComponent.literal("Invalid custom payload!"));
+ }
+ }
+
+ }
+
+ public final boolean isDisconnected() {
+ return !this.player.joining && !this.connection.isConnected();
+ }
+ // CraftBukkit end
@Override
public void handleResourcePackResponse(ServerboundResourcePackPacket serverboundresourcepackpacket) {
@@ -104,11 +201,18 @@
ServerCommonPacketListenerImpl.LOGGER.info("Disconnecting {} due to resource pack {} rejection", this.playerProfile().getName(), serverboundresourcepackpacket.id());
this.disconnect((IChatBaseComponent) IChatBaseComponent.translatable("multiplayer.requiredTexturePrompt.disconnect"));
}
+ this.cserver.getPluginManager().callEvent(new PlayerResourcePackStatusEvent(getCraftPlayer(), serverboundresourcepackpacket.id(), PlayerResourcePackStatusEvent.Status.values()[serverboundresourcepackpacket.action().ordinal()])); // CraftBukkit
}
@Override
public void handleCookieResponse(ServerboundCookieResponsePacket serverboundcookieresponsepacket) {
+ // CraftBukkit start
+ PlayerConnectionUtils.ensureRunningOnSameThread(serverboundcookieresponsepacket, this, (IAsyncTaskHandler) this.server);
+ if (this.player.getBukkitEntity().handleCookieResponse(serverboundcookieresponsepacket)) {
+ return;
+ }
+ // CraftBukkit end
this.disconnect(ServerCommonPacketListenerImpl.DISCONNECT_UNEXPECTED_QUERY);
}
@@ -116,7 +220,7 @@
Profiler.get().push("keepAlive");
long i = SystemUtils.getMillis();
- if (!this.isSingleplayerOwner() && i - this.keepAliveTime >= 15000L) {
+ if (!this.isSingleplayerOwner() && i - this.keepAliveTime >= 25000L) { // CraftBukkit
if (this.keepAlivePending) {
this.disconnect(ServerCommonPacketListenerImpl.TIMEOUT_DISCONNECTION_MESSAGE);
} else if (this.checkIfClosed(i)) {
@@ -156,6 +260,14 @@
}
public void send(Packet<?> packet, @Nullable PacketSendListener packetsendlistener) {
+ // CraftBukkit start
+ if (packet == null) {
+ return;
+ } else if (packet instanceof PacketPlayOutSpawnPosition) {
+ PacketPlayOutSpawnPosition packet6 = (PacketPlayOutSpawnPosition) packet;
+ this.player.compassTarget = CraftLocation.toBukkit(packet6.pos, this.getCraftPlayer().getWorld());
+ }
+ // CraftBukkit end
if (packet.isTerminal()) {
this.close();
}
@@ -180,15 +292,61 @@
}
public void disconnect(DisconnectionDetails disconnectiondetails) {
+ // CraftBukkit start - fire PlayerKickEvent
+ if (this.processedDisconnect) {
+ return;
+ }
+ if (!this.cserver.isPrimaryThread()) {
+ Waitable waitable = new Waitable() {
+ @Override
+ protected Object evaluate() {
+ ServerCommonPacketListenerImpl.this.disconnect(disconnectiondetails);
+ return null;
+ }
+ };
+
+ this.server.processQueue.add(waitable);
+
+ try {
+ waitable.get();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } catch (ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ return;
+ }
+
+ String leaveMessage = EnumChatFormat.YELLOW + this.player.getScoreboardName() + " left the game.";
+
+ PlayerKickEvent event = new PlayerKickEvent(this.player.getBukkitEntity(), CraftChatMessage.fromComponent(disconnectiondetails.reason()), leaveMessage);
+
+ if (this.cserver.getServer().isRunning()) {
+ this.cserver.getPluginManager().callEvent(event);
+ }
+
+ if (event.isCancelled()) {
+ // Do not kick the player
+ return;
+ }
+ this.player.kickLeaveMessage = event.getLeaveMessage(); // CraftBukkit - SPIGOT-3034: Forward leave message to PlayerQuitEvent
+ // Send the possibly modified leave message
+ disconnect0(new DisconnectionDetails(CraftChatMessage.fromString(event.getReason(), true)[0], disconnectiondetails.report(), disconnectiondetails.bugReportLink()));
+ }
+
+ private void disconnect0(DisconnectionDetails disconnectiondetails) {
+ // CraftBukkit end
this.connection.send(new ClientboundDisconnectPacket(disconnectiondetails.reason()), PacketSendListener.thenRun(() -> {
this.connection.disconnect(disconnectiondetails);
}));
+ this.onDisconnect(disconnectiondetails); // CraftBukkit - fire quit instantly
this.connection.setReadOnly();
MinecraftServer minecraftserver = this.server;
NetworkManager networkmanager = this.connection;
Objects.requireNonNull(this.connection);
- minecraftserver.executeBlocking(networkmanager::handleDisconnection);
+ // CraftBukkit - Don't wait
+ minecraftserver.wrapRunnable(networkmanager::handleDisconnection);
}
protected boolean isSingleplayerOwner() {

View File

@@ -0,0 +1,57 @@
--- a/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
@@ -38,6 +38,11 @@
import net.minecraft.world.flag.FeatureFlags;
import org.slf4j.Logger;
+// CraftBukkit start
+import org.bukkit.craftbukkit.CraftServerLinks;
+import org.bukkit.event.player.PlayerLinksSendEvent;
+// CraftBukkit end
+
public class ServerConfigurationPacketListenerImpl extends ServerCommonPacketListenerImpl implements ServerConfigurationPacketListener, TickablePacketListener {
private static final Logger LOGGER = LogUtils.getLogger();
@@ -50,8 +55,10 @@
@Nullable
private SynchronizeRegistriesTask synchronizeRegistriesTask;
- public ServerConfigurationPacketListenerImpl(MinecraftServer minecraftserver, NetworkManager networkmanager, CommonListenerCookie commonlistenercookie) {
- super(minecraftserver, networkmanager, commonlistenercookie);
+ // CraftBukkit start
+ public ServerConfigurationPacketListenerImpl(MinecraftServer minecraftserver, NetworkManager networkmanager, CommonListenerCookie commonlistenercookie, EntityPlayer player) {
+ super(minecraftserver, networkmanager, commonlistenercookie, player);
+ // CraftBukkit end
this.gameProfile = commonlistenercookie.gameProfile();
this.clientInformation = commonlistenercookie.clientInformation();
}
@@ -75,6 +82,12 @@
public void startConfiguration() {
this.send(new ClientboundCustomPayloadPacket(new BrandPayload(this.server.getServerModName())));
ServerLinks serverlinks = this.server.serverLinks();
+ // CraftBukkit start
+ CraftServerLinks wrapper = new CraftServerLinks(serverlinks);
+ PlayerLinksSendEvent event = new PlayerLinksSendEvent(player.getBukkitEntity(), wrapper);
+ player.getBukkitEntity().getServer().getPluginManager().callEvent(event);
+ serverlinks = wrapper.getServerLinks();
+ // CraftBukkit end
if (!serverlinks.isEmpty()) {
this.send(new ClientboundServerLinksPacket(serverlinks.untrust()));
@@ -143,14 +156,14 @@
return;
}
- IChatBaseComponent ichatbasecomponent = playerlist.canPlayerLogin(this.connection.getRemoteAddress(), this.gameProfile);
+ IChatBaseComponent ichatbasecomponent = null; // CraftBukkit - login checks already completed
if (ichatbasecomponent != null) {
this.disconnect(ichatbasecomponent);
return;
}
- EntityPlayer entityplayer = playerlist.getPlayerForLogin(this.gameProfile, this.clientInformation);
+ EntityPlayer entityplayer = playerlist.getPlayerForLogin(this.gameProfile, this.clientInformation, this.player); // CraftBukkit
playerlist.placeNewPlayer(this.connection, entityplayer, this.createCookie(this.clientInformation));
} catch (Exception exception) {

View File

@@ -0,0 +1,30 @@
--- a/net/minecraft/server/network/ServerConnection.java
+++ b/net/minecraft/server/network/ServerConnection.java
@@ -100,15 +100,25 @@
NetworkManager.configureSerialization(channelpipeline, EnumProtocolDirection.SERVERBOUND, false, (BandwidthDebugMonitor) null);
int j = ServerConnection.this.server.getRateLimitPacketsPerSecond();
- Object object = j > 0 ? new NetworkManagerServer(j) : new NetworkManager(EnumProtocolDirection.SERVERBOUND);
+ NetworkManager object = j > 0 ? new NetworkManagerServer(j) : new NetworkManager(EnumProtocolDirection.SERVERBOUND); // CraftBukkit - decompile error
ServerConnection.this.connections.add(object);
((NetworkManager) object).configurePacketHandler(channelpipeline);
((NetworkManager) object).setListenerForServerboundHandshake(new HandshakeListener(ServerConnection.this.server, (NetworkManager) object));
}
- }).group(eventloopgroup).localAddress(inetaddress, i)).bind().syncUninterruptibly());
+ }).group(eventloopgroup).localAddress(inetaddress, i)).option(ChannelOption.AUTO_READ, false).bind().syncUninterruptibly()); // CraftBukkit
+ }
+ }
+
+ // CraftBukkit start
+ public void acceptConnections() {
+ synchronized (this.channels) {
+ for (ChannelFuture future : this.channels) {
+ future.channel().config().setAutoRead(true);
+ }
}
}
+ // CraftBukkit end
public SocketAddress startMemoryChannel() {
List list = this.channels;