From a3b4cc21f583e858955b459159f97e3a14333ecd Mon Sep 17 00:00:00 2001 From: booky10 Date: Tue, 17 Sep 2024 16:29:30 +0200 Subject: [PATCH] Synchronize packet encoding Resolves concurrency issues which may happen when sending the same packet wrapper to different players, concurrently This is not a perfect solution, but the alternative would be refactoring the packetwrapper to be based on buffers passed during encoding as parameters, which would be too much effort and would require breaking changes --- .../manager/protocol/ProtocolManager.java | 11 +++++++---- .../retrooper/packetevents/wrapper/PacketWrapper.java | 3 +++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/api/src/main/java/com/github/retrooper/packetevents/manager/protocol/ProtocolManager.java b/api/src/main/java/com/github/retrooper/packetevents/manager/protocol/ProtocolManager.java index 7b1d1fa3f7..5c0fce590b 100644 --- a/api/src/main/java/com/github/retrooper/packetevents/manager/protocol/ProtocolManager.java +++ b/api/src/main/java/com/github/retrooper/packetevents/manager/protocol/ProtocolManager.java @@ -104,10 +104,13 @@ default Object[] transformWrappers(PacketWrapper wrapper, Object channel, boo PacketWrapper[] wrappers = PacketTransformationUtil.transform(wrapper); Object[] buffers = new Object[wrappers.length]; for (int i = 0; i < wrappers.length; i++) { - wrappers[i].prepareForSend(channel, outgoing); - buffers[i] = wrappers[i].buffer; - // Fix race condition when sending packets to multiple people (due to when the buffer is freed) - wrappers[i].buffer = null; + PacketWrapper wrappper = wrappers[i]; + synchronized (wrappper.bufferLock) { + wrappper.prepareForSend(channel, outgoing); + buffers[i] = wrappper.buffer; + // Fix race condition when sending packets to multiple people (due to when the buffer is freed) + wrappper.buffer = null; + } } return buffers; } diff --git a/api/src/main/java/com/github/retrooper/packetevents/wrapper/PacketWrapper.java b/api/src/main/java/com/github/retrooper/packetevents/wrapper/PacketWrapper.java index 2a843f5f14..9d41698acc 100644 --- a/api/src/main/java/com/github/retrooper/packetevents/wrapper/PacketWrapper.java +++ b/api/src/main/java/com/github/retrooper/packetevents/wrapper/PacketWrapper.java @@ -128,6 +128,9 @@ public class PacketWrapper> { @Nullable public Object buffer; + @ApiStatus.Internal + public final Object bufferLock = new Object(); + protected ClientVersion clientVersion; protected ServerVersion serverVersion; private PacketTypeData packetTypeData;