net/minecraft/network/

This commit is contained in:
Owen1212055 2024-12-14 15:47:45 -05:00
parent b0f627d7bb
commit 93c74cf2f4
No known key found for this signature in database
GPG key ID: 2133292072886A30
6 changed files with 149 additions and 237 deletions

View file

@ -1,23 +1,23 @@
--- a/net/minecraft/network/Connection.java --- a/net/minecraft/network/Connection.java
+++ b/net/minecraft/network/Connection.java +++ b/net/minecraft/network/Connection.java
@@ -82,13 +82,13 @@ @@ -74,13 +_,13 @@
marker.add(Connection.PACKET_MARKER); public static final Marker PACKET_RECEIVED_MARKER = Util.make(MarkerFactory.getMarker("PACKET_RECEIVED"), marker -> marker.add(PACKET_MARKER));
}); public static final Marker PACKET_SENT_MARKER = Util.make(MarkerFactory.getMarker("PACKET_SENT"), marker -> marker.add(PACKET_MARKER));
public static final Supplier<NioEventLoopGroup> NETWORK_WORKER_GROUP = Suppliers.memoize(() -> { public static final Supplier<NioEventLoopGroup> NETWORK_WORKER_GROUP = Suppliers.memoize(
- return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Client IO #%d").setDaemon(true).build()); - () -> new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("Netty Client IO #%d").setDaemon(true).build())
+ return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Client IO #%d").setDaemon(true).setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(LOGGER)).build()); // Paper + () -> new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("Netty Client IO #%d").setDaemon(true).setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(LOGGER)).build()) // Paper
}); );
public static final Supplier<EpollEventLoopGroup> NETWORK_EPOLL_WORKER_GROUP = Suppliers.memoize(() -> { public static final Supplier<EpollEventLoopGroup> NETWORK_EPOLL_WORKER_GROUP = Suppliers.memoize(
- return new EpollEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Epoll Client IO #%d").setDaemon(true).build()); - () -> new EpollEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("Netty Epoll Client IO #%d").setDaemon(true).build())
+ return new EpollEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Epoll Client IO #%d").setDaemon(true).setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(LOGGER)).build()); // Paper + () -> new EpollEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("Netty Epoll Client IO #%d").setDaemon(true).setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(LOGGER)).build()) // Paper
}); );
public static final Supplier<DefaultEventLoopGroup> LOCAL_WORKER_GROUP = Suppliers.memoize(() -> { public static final Supplier<DefaultEventLoopGroup> LOCAL_WORKER_GROUP = Suppliers.memoize(
- return new DefaultEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Local Client IO #%d").setDaemon(true).build()); - () -> new DefaultEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("Netty Local Client IO #%d").setDaemon(true).build())
+ return new DefaultEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Local Client IO #%d").setDaemon(true).setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(LOGGER)).build()); // Paper + () -> new DefaultEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("Netty Local Client IO #%d").setDaemon(true).setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(LOGGER)).build()) // Paper
}); );
private static final ProtocolInfo<ServerHandshakePacketListener> INITIAL_PROTOCOL = HandshakeProtocols.SERVERBOUND; private static final ProtocolInfo<ServerHandshakePacketListener> INITIAL_PROTOCOL = HandshakeProtocols.SERVERBOUND;
private final PacketFlow receiving; private final PacketFlow receiving;
@@ -96,6 +96,11 @@ @@ -88,6 +_,11 @@
private final Queue<Consumer<Connection>> pendingActions = Queues.newConcurrentLinkedQueue(); private final Queue<Consumer<Connection>> pendingActions = Queues.newConcurrentLinkedQueue();
public Channel channel; public Channel channel;
public SocketAddress address; public SocketAddress address;
@ -29,7 +29,7 @@
@Nullable @Nullable
private volatile PacketListener disconnectListener; private volatile PacketListener disconnectListener;
@Nullable @Nullable
@@ -114,7 +119,42 @@ @@ -106,6 +_,40 @@
private volatile DisconnectionDetails delayedDisconnect; private volatile DisconnectionDetails delayedDisconnect;
@Nullable @Nullable
BandwidthDebugMonitor bandwidthDebugMonitor; BandwidthDebugMonitor bandwidthDebugMonitor;
@ -39,7 +39,6 @@
+ public java.net.InetSocketAddress virtualHost; + public java.net.InetSocketAddress virtualHost;
+ private static boolean enableExplicitFlush = Boolean.getBoolean("paper.explicit-flush"); // Paper - Disable explicit network manager flushing + private static boolean enableExplicitFlush = Boolean.getBoolean("paper.explicit-flush"); // Paper - Disable explicit network manager flushing
+ // Paper end + // Paper end
+ // Paper start - add utility methods + // Paper start - add utility methods
+ public final net.minecraft.server.level.ServerPlayer getPlayer() { + public final net.minecraft.server.level.ServerPlayer getPlayer() {
+ if (this.packetListener instanceof net.minecraft.server.network.ServerGamePacketListenerImpl impl) { + if (this.packetListener instanceof net.minecraft.server.network.ServerGamePacketListenerImpl impl) {
@ -68,13 +67,12 @@
+ } + }
+ // Paper end - packet limiter + // Paper end - packet limiter
+ @Nullable public SocketAddress haProxyAddress; // Paper - Add API to get player's proxy address + @Nullable public SocketAddress haProxyAddress; // Paper - Add API to get player's proxy address
+
public Connection(PacketFlow side) { public Connection(PacketFlow receiving) {
this.receiving = side; this.receiving = receiving;
} @@ -116,6 +_,9 @@
@@ -123,6 +163,9 @@ super.channelActive(context);
super.channelActive(channelhandlercontext); this.channel = context.channel();
this.channel = channelhandlercontext.channel();
this.address = this.channel.remoteAddress(); this.address = this.channel.remoteAddress();
+ // Spigot Start + // Spigot Start
+ this.preparing = false; + this.preparing = false;
@ -82,62 +80,61 @@
if (this.delayedDisconnect != null) { if (this.delayedDisconnect != null) {
this.disconnect(this.delayedDisconnect); this.disconnect(this.delayedDisconnect);
} }
@@ -134,6 +177,21 @@ @@ -128,14 +_,31 @@
}
public void exceptionCaught(ChannelHandlerContext channelhandlercontext, Throwable throwable) { @Override
public void exceptionCaught(ChannelHandlerContext context, Throwable exception) {
+ // Paper start - Handle large packets disconnecting client + // Paper start - Handle large packets disconnecting client
+ if (throwable instanceof io.netty.handler.codec.EncoderException && throwable.getCause() instanceof PacketEncoder.PacketTooLargeException packetTooLargeException) { + if (exception instanceof io.netty.handler.codec.EncoderException && exception.getCause() instanceof PacketEncoder.PacketTooLargeException packetTooLargeException) {
+ final Packet<?> packet = packetTooLargeException.getPacket(); + final Packet<?> packet = packetTooLargeException.getPacket();
+ if (packet.packetTooLarge(this)) { + if (packet.packetTooLarge(this)) {
+ ProtocolSwapHandler.handleOutboundTerminalPacket(channelhandlercontext, packet); + ProtocolSwapHandler.handleOutboundTerminalPacket(context, packet);
+ return; + return;
+ } else if (packet.isSkippable()) { + } else if (packet.isSkippable()) {
+ Connection.LOGGER.debug("Skipping packet due to errors", throwable.getCause()); + Connection.LOGGER.debug("Skipping packet due to errors", exception.getCause());
+ ProtocolSwapHandler.handleOutboundTerminalPacket(channelhandlercontext, packet); + ProtocolSwapHandler.handleOutboundTerminalPacket(context, packet);
+ return; + return;
+ } else { + } else {
+ throwable = throwable.getCause(); + exception = exception.getCause();
+ } + }
+ } + }
+ // Paper end - Handle large packets disconnecting client + // Paper end - Handle large packets disconnecting client
if (throwable instanceof SkipPacketException) { if (exception instanceof SkipPacketException) {
Connection.LOGGER.debug("Skipping packet due to errors", throwable.getCause()); LOGGER.debug("Skipping packet due to errors", exception.getCause());
} else { } else {
@@ -141,8 +199,10 @@ boolean flag = !this.handlingFault;
this.handlingFault = true; this.handlingFault = true;
if (this.channel.isOpen()) { if (this.channel.isOpen()) {
+ net.minecraft.server.level.ServerPlayer player = this.getPlayer(); // Paper - Add API for quit reason + net.minecraft.server.level.ServerPlayer player = this.getPlayer(); // Paper - Add API for quit reason
if (throwable instanceof TimeoutException) { if (exception instanceof TimeoutException) {
Connection.LOGGER.debug("Timeout", throwable); LOGGER.debug("Timeout", exception);
+ if (player != null) player.quitReason = org.bukkit.event.player.PlayerQuitEvent.QuitReason.TIMED_OUT; // Paper - Add API for quit reason + if (player != null) player.quitReason = org.bukkit.event.player.PlayerQuitEvent.QuitReason.TIMED_OUT; // Paper - Add API for quit reason
this.disconnect((Component) Component.translatable("disconnect.timeout")); this.disconnect(Component.translatable("disconnect.timeout"));
} else { } else {
MutableComponent ichatmutablecomponent = Component.translatable("disconnect.genericReason", "Internal Exception: " + String.valueOf(throwable)); Component component = Component.translatable("disconnect.genericReason", "Internal Exception: " + exception);
@@ -155,9 +215,11 @@ @@ -147,9 +_,11 @@
disconnectiondetails = new DisconnectionDetails(ichatmutablecomponent); disconnectionDetails = new DisconnectionDetails(component);
} }
+ if (player != null) player.quitReason = org.bukkit.event.player.PlayerQuitEvent.QuitReason.ERRONEOUS_STATE; // Paper - Add API for quit reason + if (player != null) player.quitReason = org.bukkit.event.player.PlayerQuitEvent.QuitReason.ERRONEOUS_STATE; // Paper - Add API for quit reason
if (flag) { if (flag) {
Connection.LOGGER.debug("Failed to sent packet", throwable); LOGGER.debug("Failed to sent packet", exception);
- if (this.getSending() == PacketFlow.CLIENTBOUND) { - if (this.getSending() == PacketFlow.CLIENTBOUND) {
+ boolean doesDisconnectExist = this.packetListener.protocol() != ConnectionProtocol.STATUS && this.packetListener.protocol() != ConnectionProtocol.HANDSHAKING; // Paper + boolean doesDisconnectExist = this.packetListener.protocol() != ConnectionProtocol.STATUS && this.packetListener.protocol() != ConnectionProtocol.HANDSHAKING; // Paper
+ if (this.getSending() == PacketFlow.CLIENTBOUND && doesDisconnectExist) { // Paper + if (this.getSending() == PacketFlow.CLIENTBOUND && doesDisconnectExist) { // Paper
Packet<?> packet = this.sendLoginDisconnect ? new ClientboundLoginDisconnectPacket(ichatmutablecomponent) : new ClientboundDisconnectPacket(ichatmutablecomponent); Packet<?> packet = (Packet<?>)(this.sendLoginDisconnect
? new ClientboundLoginDisconnectPacket(component)
this.send((Packet) packet, PacketSendListener.thenRun(() -> { : new ClientboundDisconnectPacket(component));
@@ -176,6 +238,7 @@ @@ -166,6 +_,7 @@
} }
} }
+ if (net.minecraft.server.MinecraftServer.getServer().isDebugging()) io.papermc.paper.util.TraceUtil.printStackTrace(throwable); // Spigot // Paper }
+ if (net.minecraft.server.MinecraftServer.getServer().isDebugging()) io.papermc.paper.util.TraceUtil.printStackTrace(exception); // Spigot // Paper
} }
protected void channelRead0(ChannelHandlerContext channelhandlercontext, Packet<?> packet) { @Override
@@ -185,11 +248,61 @@ @@ -175,10 +_,60 @@
if (packetlistener == null) { if (packetListener == null) {
throw new IllegalStateException("Received a packet before the packet listener was initialized"); throw new IllegalStateException("Received a packet before the packet listener was initialized");
} else { } else {
+ // Paper start - packet limiter + // Paper start - packet limiter
@ -189,25 +186,15 @@
+ } + }
+ } + }
+ // Paper end - packet limiter + // Paper end - packet limiter
if (packetlistener.shouldHandleMessage(packet)) { if (packetListener.shouldHandleMessage(packet)) {
try { try {
Connection.genericsFtw(packet, packetlistener); genericsFtw(packet, packetListener);
} catch (RunningOnDifferentThreadException cancelledpackethandleexception) { } catch (RunningOnDifferentThreadException var5) {
;
+ } catch (io.papermc.paper.util.ServerStopRejectedExecutionException ignored) { // Paper - do not prematurely disconnect players on stop + } catch (io.papermc.paper.util.ServerStopRejectedExecutionException ignored) { // Paper - do not prematurely disconnect players on stop
} catch (RejectedExecutionException rejectedexecutionexception) { } catch (RejectedExecutionException var6) {
this.disconnect((Component) Component.translatable("multiplayer.disconnect.server_shutdown")); this.disconnect(Component.translatable("multiplayer.disconnect.server_shutdown"));
} catch (ClassCastException classcastexception) { } catch (ClassCastException var7) {
@@ -205,7 +318,7 @@ @@ -385,10 +_,24 @@
}
private static <T extends PacketListener> void genericsFtw(Packet<T> packet, PacketListener listener) {
- packet.handle(listener);
+ packet.handle((T) listener); // CraftBukkit - decompile error
}
private void validateListener(ProtocolInfo<?> state, PacketListener listener) {
@@ -418,12 +531,26 @@
} }
} }
@ -222,19 +209,17 @@
+ Connection.joinAttemptsThisTick = 0; + Connection.joinAttemptsThisTick = 0;
+ } + }
+ // Paper end - Buffer joins to world + // Paper end - Buffer joins to world
PacketListener packetlistener = this.packetListener; if (this.packetListener instanceof TickablePacketListener tickablePacketListener) {
if (packetlistener instanceof TickablePacketListener tickablepacketlistener) {
+ // Paper start - Buffer joins to world + // Paper start - Buffer joins to world
+ if (!(this.packetListener instanceof net.minecraft.server.network.ServerLoginPacketListenerImpl loginPacketListener) + if (!(this.packetListener instanceof net.minecraft.server.network.ServerLoginPacketListenerImpl loginPacketListener)
+ || loginPacketListener.state != net.minecraft.server.network.ServerLoginPacketListenerImpl.State.VERIFYING + || loginPacketListener.state != net.minecraft.server.network.ServerLoginPacketListenerImpl.State.VERIFYING
+ || Connection.joinAttemptsThisTick++ < MAX_PER_TICK) { + || Connection.joinAttemptsThisTick++ < MAX_PER_TICK) {
tickablepacketlistener.tick(); tickablePacketListener.tick();
+ } // Paper end - Buffer joins to world + } // Paper end - Buffer joins to world
} }
if (!this.isConnected() && !this.disconnectionHandled) { if (!this.isConnected() && !this.disconnectionHandled) {
@@ -431,7 +558,7 @@ @@ -396,7 +_,7 @@
} }
if (this.channel != null) { if (this.channel != null) {
@ -243,34 +228,25 @@
} }
if (this.tickCount++ % 20 == 0) { if (this.tickCount++ % 20 == 0) {
@@ -464,12 +591,15 @@ @@ -432,12 +_,15 @@
} }
public void disconnect(DisconnectionDetails disconnectionInfo) { public void disconnect(DisconnectionDetails disconnectionDetails) {
+ // Spigot Start + // Spigot Start
+ this.preparing = false; + this.preparing = false;
+ // Spigot End + // Spigot End
if (this.channel == null) { if (this.channel == null) {
this.delayedDisconnect = disconnectionInfo; this.delayedDisconnect = disconnectionDetails;
} }
if (this.isConnected()) { if (this.isConnected()) {
- this.channel.close().awaitUninterruptibly(); - this.channel.close().awaitUninterruptibly();
+ this.channel.close(); // We can't wait as this may be called from an event loop. + this.channel.close(); // We can't wait as this may be called from an event loop.
this.disconnectionDetails = disconnectionInfo; this.disconnectionDetails = disconnectionDetails;
} }
@@ -537,7 +667,7 @@
} }
@@ -584,6 +_,13 @@
public void configurePacketHandler(ChannelPipeline pipeline) {
- pipeline.addLast("hackfix", new ChannelOutboundHandlerAdapter(this) {
+ pipeline.addLast("hackfix", new ChannelOutboundHandlerAdapter() { // CraftBukkit - decompile error
public void write(ChannelHandlerContext channelhandlercontext, Object object, ChannelPromise channelpromise) throws Exception {
super.write(channelhandlercontext, object, channelpromise);
} }
@@ -613,6 +743,14 @@
} }
+ // Paper start - add proper async disconnect + // Paper start - add proper async disconnect
@ -280,33 +256,31 @@
+ } + }
+ } + }
+ // Paper end - add proper async disconnect + // Paper end - add proper async disconnect
+ public void setupCompression(int threshold, boolean validateDecompressed) {
public void setupCompression(int compressionThreshold, boolean rejectsBadPackets) { if (threshold >= 0) {
if (compressionThreshold >= 0) { if (this.channel.pipeline().get("decompress") instanceof CompressionDecoder compressionDecoder) {
ChannelHandler channelhandler = this.channel.pipeline().get("decompress"); @@ -597,6 +_,7 @@
@@ -633,6 +771,7 @@
} else { } else {
this.channel.pipeline().addAfter("prepender", "compress", new CompressionEncoder(compressionThreshold)); this.channel.pipeline().addAfter("prepender", "compress", new CompressionEncoder(threshold));
} }
+ this.channel.pipeline().fireUserEventTriggered(io.papermc.paper.network.ConnectionEvent.COMPRESSION_THRESHOLD_SET); // Paper - Add Channel initialization listeners + this.channel.pipeline().fireUserEventTriggered(io.papermc.paper.network.ConnectionEvent.COMPRESSION_THRESHOLD_SET); // Paper - Add Channel initialization listeners
} else { } else {
if (this.channel.pipeline().get("decompress") instanceof CompressionDecoder) { if (this.channel.pipeline().get("decompress") instanceof CompressionDecoder) {
this.channel.pipeline().remove("decompress"); this.channel.pipeline().remove("decompress");
@@ -641,6 +780,7 @@ @@ -605,6 +_,7 @@
if (this.channel.pipeline().get("compress") instanceof CompressionEncoder) { if (this.channel.pipeline().get("compress") instanceof CompressionEncoder) {
this.channel.pipeline().remove("compress"); this.channel.pipeline().remove("compress");
} }
+ this.channel.pipeline().fireUserEventTriggered(io.papermc.paper.network.ConnectionEvent.COMPRESSION_DISABLED); // Paper - Add Channel initialization listeners + this.channel.pipeline().fireUserEventTriggered(io.papermc.paper.network.ConnectionEvent.COMPRESSION_DISABLED); // Paper - Add Channel initialization listeners
} }
} }
@@ -661,6 +801,27 @@
packetlistener1.onDisconnect(disconnectiondetails); @@ -622,6 +_,26 @@
);
packetListener1.onDisconnect(disconnectionDetails);
} }
+ this.pendingActions.clear(); // Free up packet queue. + this.pendingActions.clear(); // Free up packet queue.
+ // Paper start - Add PlayerConnectionCloseEvent + // Paper start - Add PlayerConnectionCloseEvent
+ final PacketListener packetListener = this.getPacketListener();
+ if (packetListener instanceof net.minecraft.server.network.ServerCommonPacketListenerImpl commonPacketListener) { + if (packetListener instanceof net.minecraft.server.network.ServerCommonPacketListenerImpl commonPacketListener) {
+ /* Player was logged in, either game listener or configuration listener */ + /* Player was logged in, either game listener or configuration listener */
+ final com.mojang.authlib.GameProfile profile = commonPacketListener.getOwner(); + final com.mojang.authlib.GameProfile profile = commonPacketListener.getOwner();
@ -325,6 +299,6 @@
+ } + }
+ } + }
+ // Paper end - Add PlayerConnectionCloseEvent + // Paper end - Add PlayerConnectionCloseEvent
}
} }
} }

View file

@ -0,0 +1,42 @@
--- a/net/minecraft/network/FriendlyByteBuf.java
+++ b/net/minecraft/network/FriendlyByteBuf.java
@@ -70,6 +_,7 @@
public class FriendlyByteBuf extends ByteBuf {
public static final int DEFAULT_NBT_QUOTA = 2097152;
private final ByteBuf source;
+ @Nullable public final java.util.Locale adventure$locale; // Paper - track player's locale for server-side translations
public static final short MAX_STRING_LENGTH = 32767;
public static final int MAX_COMPONENT_STRING_LENGTH = 262144;
private static final int PUBLIC_KEY_SIZE = 256;
@@ -78,6 +_,7 @@
private static final Gson GSON = new Gson();
public FriendlyByteBuf(ByteBuf source) {
+ this.adventure$locale = PacketEncoder.ADVENTURE_LOCALE.get(); // Paper - track player's locale for server-side translations
this.source = source;
}
@@ -106,8 +_,13 @@
}
public <T> void writeJsonWithCodec(Codec<T> codec, T value) {
+ // Paper start - Adventure; add max length parameter
+ this.writeJsonWithCodec(codec, value, MAX_STRING_LENGTH);
+ }
+ public <T> void writeJsonWithCodec(Codec<T> codec, T value, int maxLength) {
+ // Paper end - Adventure; add max length parameter
DataResult<JsonElement> dataResult = codec.encodeStart(JsonOps.INSTANCE, value);
- this.writeUtf(GSON.toJson(dataResult.getOrThrow(exception -> new EncoderException("Failed to encode: " + exception + " " + value))));
+ this.writeUtf(GSON.toJson(dataResult.getOrThrow(exception -> new EncoderException("Failed to encode: " + exception + " " + value))), maxLength); // Paper - Adventure; add max length parameter
}
public static <T> IntFunction<T> limitValue(IntFunction<T> function, int limit) {
@@ -527,7 +_,7 @@
try {
NbtIo.writeAnyTag(nbt, new ByteBufOutputStream(buffer));
- } catch (IOException var3) {
+ } catch (Exception var3) { // CraftBukkit - IOException -> Exception
throw new EncoderException(var3);
}
}

View file

@ -1,10 +1,11 @@
--- a/net/minecraft/network/PacketEncoder.java --- a/net/minecraft/network/PacketEncoder.java
+++ b/net/minecraft/network/PacketEncoder.java +++ b/net/minecraft/network/PacketEncoder.java
@@ -17,10 +17,12 @@ @@ -17,11 +_,13 @@
this.protocolInfo = state; this.protocolInfo = protocolInfo;
} }
+ static final ThreadLocal<java.util.Locale> ADVENTURE_LOCALE = ThreadLocal.withInitial(() -> null); // Paper - adventure; set player's locale + static final ThreadLocal<java.util.Locale> ADVENTURE_LOCALE = ThreadLocal.withInitial(() -> null); // Paper - adventure; set player's locale
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, Packet<T> packet, ByteBuf byteBuf) throws Exception { protected void encode(ChannelHandlerContext channelHandlerContext, Packet<T> packet, ByteBuf byteBuf) throws Exception {
PacketType<? extends Packet<? super T>> packetType = packet.type(); PacketType<? extends Packet<? super T>> packetType = packet.type();
@ -13,7 +14,7 @@
this.protocolInfo.codec().encode(byteBuf, packet); this.protocolInfo.codec().encode(byteBuf, packet);
int i = byteBuf.readableBytes(); int i = byteBuf.readableBytes();
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
@@ -31,14 +33,40 @@ @@ -32,14 +_,40 @@
JvmProfiler.INSTANCE.onPacketSent(this.protocolInfo.id(), packetType, channelHandlerContext.channel().remoteAddress(), i); JvmProfiler.INSTANCE.onPacketSent(this.protocolInfo.id(), packetType, channelHandlerContext.channel().remoteAddress(), i);
} catch (Throwable var9) { } catch (Throwable var9) {

View file

@ -1,11 +1,11 @@
--- a/net/minecraft/network/VarInt.java --- a/net/minecraft/network/VarInt.java
+++ b/net/minecraft/network/VarInt.java +++ b/net/minecraft/network/VarInt.java
@@ -9,6 +9,18 @@ @@ -9,6 +_,18 @@
private static final int DATA_BITS_PER_BYTE = 7; private static final int DATA_BITS_PER_BYTE = 7;
public static int getByteSize(int i) { public static int getByteSize(int data) {
+ // Paper start - Optimize VarInts + // Paper start - Optimize VarInts
+ return VARINT_EXACT_BYTE_LENGTHS[Integer.numberOfLeadingZeros(i)]; + return VARINT_EXACT_BYTE_LENGTHS[Integer.numberOfLeadingZeros(data)];
+ } + }
+ private static final int[] VARINT_EXACT_BYTE_LENGTHS = new int[33]; + private static final int[] VARINT_EXACT_BYTE_LENGTHS = new int[33];
+ static { + static {
@ -14,30 +14,30 @@
+ } + }
+ VARINT_EXACT_BYTE_LENGTHS[32] = 1; // Special case for the number 0. + VARINT_EXACT_BYTE_LENGTHS[32] = 1; // Special case for the number 0.
+ } + }
+ public static int getByteSizeOld(int i) { + public static int getByteSizeOld(int data) {
+ // Paper end - Optimize VarInts + // Paper end - Optimize VarInts
for (int j = 1; j < 5; j++) { for (int i = 1; i < 5; i++) {
if ((i & -1 << j * 7) == 0) { if ((data & -1 << i * 7) == 0) {
return j; return i;
@@ -39,6 +51,21 @@ @@ -39,6 +_,21 @@
} }
public static ByteBuf write(ByteBuf buf, int i) { public static ByteBuf write(ByteBuf buffer, int value) {
+ // Paper start - Optimize VarInts + // Paper start - Optimize VarInts
+ // Peel the one and two byte count cases explicitly as they are the most common VarInt sizes + // Peel the one and two byte count cases explicitly as they are the most common VarInt sizes
+ // that the proxy will write, to improve inlining. + // that the proxy will write, to improve inlining.
+ if ((i & (0xFFFFFFFF << 7)) == 0) { + if ((value & (0xFFFFFFFF << 7)) == 0) {
+ buf.writeByte(i); + buffer.writeByte(value);
+ } else if ((i & (0xFFFFFFFF << 14)) == 0) { + } else if ((value & (0xFFFFFFFF << 14)) == 0) {
+ int w = (i & 0x7F | 0x80) << 8 | (i >>> 7); + int w = (value & 0x7F | 0x80) << 8 | (value >>> 7);
+ buf.writeShort(w); + buffer.writeShort(w);
+ } else { + } else {
+ writeOld(buf, i); + writeOld(buffer, value);
+ } + }
+ return buf; + return buffer;
+ } + }
+ public static ByteBuf writeOld(ByteBuf buf, int i) { + public static ByteBuf writeOld(ByteBuf buffer, int value) {
+ // Paper end - Optimize VarInts + // Paper end - Optimize VarInts
while ((i & -128) != 0) { while ((value & -128) != 0) {
buf.writeByte(i & 127 | 128); buffer.writeByte(value & 127 | 128);
i >>>= 7; value >>>= 7;

View file

@ -1,15 +1,15 @@
--- a/net/minecraft/network/Varint21FrameDecoder.java --- a/net/minecraft/network/Varint21FrameDecoder.java
+++ b/net/minecraft/network/Varint21FrameDecoder.java +++ b/net/minecraft/network/Varint21FrameDecoder.java
@@ -39,6 +39,12 @@ @@ -41,6 +_,12 @@
}
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) { @Override
protected void decode(ChannelHandlerContext context, ByteBuf in, List<Object> out) {
+ // Paper start - Perf: Optimize exception handling; if channel is not active just discard the packet + // Paper start - Perf: Optimize exception handling; if channel is not active just discard the packet
+ if (!channelHandlerContext.channel().isActive()) { + if (!context.channel().isActive()) {
+ byteBuf.skipBytes(byteBuf.readableBytes()); + in.skipBytes(in.readableBytes());
+ return; + return;
+ } + }
+ // Paper end - Perf: Optimize exception handling + // Paper end - Perf: Optimize exception handling
byteBuf.markReaderIndex(); in.markReaderIndex();
this.helperBuf.clear(); this.helperBuf.clear();
if (!copyVarint(byteBuf, this.helperBuf)) { if (!copyVarint(in, this.helperBuf)) {

View file

@ -1,105 +0,0 @@
--- a/net/minecraft/network/FriendlyByteBuf.java
+++ b/net/minecraft/network/FriendlyByteBuf.java
@@ -72,6 +72,7 @@
public static final int DEFAULT_NBT_QUOTA = 2097152;
private final ByteBuf source;
+ @Nullable public final java.util.Locale adventure$locale; // Paper - track player's locale for server-side translations
public static final short MAX_STRING_LENGTH = Short.MAX_VALUE;
public static final int MAX_COMPONENT_STRING_LENGTH = 262144;
private static final int PUBLIC_KEY_SIZE = 256;
@@ -80,6 +81,7 @@
private static final Gson GSON = new Gson();
public FriendlyByteBuf(ByteBuf parent) {
+ this.adventure$locale = PacketEncoder.ADVENTURE_LOCALE.get(); // Paper - track player's locale for server-side translations
this.source = parent;
}
@@ -120,11 +122,16 @@
}
public <T> void writeJsonWithCodec(Codec<T> codec, T value) {
+ // Paper start - Adventure; add max length parameter
+ this.writeJsonWithCodec(codec, value, MAX_STRING_LENGTH);
+ }
+ public <T> void writeJsonWithCodec(Codec<T> codec, T value, int maxLength) {
+ // Paper end - Adventure; add max length parameter
DataResult<JsonElement> dataresult = codec.encodeStart(JsonOps.INSTANCE, value);
this.writeUtf(FriendlyByteBuf.GSON.toJson((JsonElement) dataresult.getOrThrow((s) -> {
return new EncoderException("Failed to encode: " + s + " " + String.valueOf(value));
- })));
+ })), maxLength); // Paper - Adventure; add max length parameter
}
public static <T> IntFunction<T> limitValue(IntFunction<T> applier, int max) {
@@ -139,7 +146,7 @@
public <T, C extends Collection<T>> C readCollection(IntFunction<C> collectionFactory, StreamDecoder<? super FriendlyByteBuf, T> reader) {
int i = this.readVarInt();
- C c0 = (Collection) collectionFactory.apply(i);
+ C c0 = collectionFactory.apply(i); // CraftBukkit - decompile error
for (int j = 0; j < i; ++j) {
c0.add(reader.decode(this));
@@ -150,7 +157,7 @@
public <T> void writeCollection(Collection<T> collection, StreamEncoder<? super FriendlyByteBuf, T> writer) {
this.writeVarInt(collection.size());
- Iterator iterator = collection.iterator();
+ Iterator<T> iterator = collection.iterator(); // CraftBukkit - decompile error
while (iterator.hasNext()) {
T t0 = iterator.next();
@@ -177,12 +184,12 @@
public void writeIntIdList(IntList list) {
this.writeVarInt(list.size());
- list.forEach(this::writeVarInt);
+ list.forEach((java.util.function.IntConsumer) this::writeVarInt); // CraftBukkit - decompile error
}
public <K, V, M extends Map<K, V>> M readMap(IntFunction<M> mapFactory, StreamDecoder<? super FriendlyByteBuf, K> keyReader, StreamDecoder<? super FriendlyByteBuf, V> valueReader) {
int i = this.readVarInt();
- M m0 = (Map) mapFactory.apply(i);
+ M m0 = mapFactory.apply(i); // CraftBukkit - decompile error
for (int j = 0; j < i; ++j) {
K k0 = keyReader.decode(this);
@@ -216,7 +223,7 @@
}
public <E extends Enum<E>> void writeEnumSet(EnumSet<E> enumSet, Class<E> type) {
- E[] ae = (Enum[]) type.getEnumConstants();
+ E[] ae = type.getEnumConstants(); // CraftBukkit - decompile error
BitSet bitset = new BitSet(ae.length);
for (int i = 0; i < ae.length; ++i) {
@@ -227,7 +234,7 @@
}
public <E extends Enum<E>> EnumSet<E> readEnumSet(Class<E> type) {
- E[] ae = (Enum[]) type.getEnumConstants();
+ E[] ae = type.getEnumConstants(); // CraftBukkit - decompile error
BitSet bitset = this.readFixedBitSet(ae.length);
EnumSet<E> enumset = EnumSet.noneOf(type);
@@ -498,7 +505,7 @@
}
public <T extends Enum<T>> T readEnum(Class<T> enumClass) {
- return ((Enum[]) enumClass.getEnumConstants())[this.readVarInt()];
+ return ((T[]) enumClass.getEnumConstants())[this.readVarInt()]; // CraftBukkit - fix decompile error
}
public FriendlyByteBuf writeEnum(Enum<?> instance) {
@@ -565,7 +572,7 @@
try {
NbtIo.writeAnyTag((Tag) nbt, new ByteBufOutputStream(buf));
- } catch (IOException ioexception) {
+ } catch (Exception ioexception) { // CraftBukkit - IOException -> Exception
throw new EncoderException(ioexception);
}
}