Fix potential packet corruption

Signed-off-by: TheMode <themode@outlook.fr>
This commit is contained in:
TheMode 2021-09-03 13:43:00 +02:00
parent 4b2bda15f5
commit 400109df0a

View File

@ -259,23 +259,31 @@ public class PlayerSocketConnection extends PlayerConnection {
if (!channel.isOpen()) return; if (!channel.isOpen()) return;
if (tickBuffer.readableBytes() == 0 && waitingBuffers.isEmpty()) return; if (tickBuffer.readableBytes() == 0 && waitingBuffers.isEmpty()) return;
synchronized (bufferLock) { synchronized (bufferLock) {
if (tickBuffer.readableBytes() == 0 && waitingBuffers.isEmpty()) return; final BinaryBuffer localBuffer = this.tickBuffer;
if (localBuffer.readableBytes() == 0 && waitingBuffers.isEmpty()) return;
// Update tick buffer
BinaryBuffer newBuffer = POOLED_BUFFERS.poll();
if (newBuffer == null) newBuffer = BinaryBuffer.ofSize(BUFFER_SIZE);
newBuffer.clear();
this.tickBuffer = newBuffer;
if (encrypted) { if (encrypted) {
final Cipher cipher = encryptCipher; final Cipher cipher = encryptCipher;
// Encrypt data first // Encrypt data first
final int remainingBytes = tickBuffer.readableBytes(); final int remainingBytes = localBuffer.readableBytes();
final byte[] bytes = tickBuffer.readRemainingBytes(); final byte[] bytes = localBuffer.readRemainingBytes();
byte[] outTempArray = new byte[cipher.getOutputSize(remainingBytes)]; byte[] outTempArray = new byte[cipher.getOutputSize(remainingBytes)];
try { try {
cipher.update(bytes, 0, remainingBytes, outTempArray); cipher.update(bytes, 0, remainingBytes, outTempArray);
} catch (ShortBufferException e) { } catch (ShortBufferException e) {
MinecraftServer.getExceptionManager().handleException(e); MinecraftServer.getExceptionManager().handleException(e);
} }
this.tickBuffer.clear(); localBuffer.clear();
this.tickBuffer.writeBytes(outTempArray); localBuffer.writeBytes(outTempArray);
} }
this.waitingBuffers.add(tickBuffer); this.waitingBuffers.add(localBuffer);
Iterator<BinaryBuffer> iterator = waitingBuffers.iterator(); Iterator<BinaryBuffer> iterator = waitingBuffers.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
BinaryBuffer waitingBuffer = iterator.next(); BinaryBuffer waitingBuffer = iterator.next();
@ -289,13 +297,9 @@ public class PlayerSocketConnection extends PlayerConnection {
if (message == null || if (message == null ||
(!message.equals("Broken pipe") && !message.equals("Connection reset by peer"))) { (!message.equals("Broken pipe") && !message.equals("Connection reset by peer"))) {
MinecraftServer.getExceptionManager().handleException(e); MinecraftServer.getExceptionManager().handleException(e);
} } }
}
} }
// Update tick buffer
BinaryBuffer newBuffer = POOLED_BUFFERS.poll();
if (newBuffer == null) newBuffer = BinaryBuffer.ofSize(BUFFER_SIZE);
newBuffer.clear();
this.tickBuffer = newBuffer;
} }
} }