From 8dbe3d081c2a4ea608577b97f3ec64f7efb19ea3 Mon Sep 17 00:00:00 2001 From: Steveice10 Date: Sun, 31 May 2020 17:23:22 -0700 Subject: [PATCH] Make sure bad packet data is skipped when errors are suppressed. --- .../steveice10/packetlib/tcp/TcpPacketCodec.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/steveice10/packetlib/tcp/TcpPacketCodec.java b/src/main/java/com/github/steveice10/packetlib/tcp/TcpPacketCodec.java index 43425c48..0a710016 100644 --- a/src/main/java/com/github/steveice10/packetlib/tcp/TcpPacketCodec.java +++ b/src/main/java/com/github/steveice10/packetlib/tcp/TcpPacketCodec.java @@ -23,12 +23,17 @@ public class TcpPacketCodec extends ByteToMessageCodec { @Override public void encode(ChannelHandlerContext ctx, Packet packet, ByteBuf buf) throws Exception { + int initial = buf.writerIndex(); + try { NetOutput out = new ByteBufNetOutput(buf); this.session.getPacketProtocol().getPacketHeader().writePacketId(out, this.session.getPacketProtocol().getOutgoingId(packet)); packet.write(out); } catch(Throwable t) { + // Reset writer index to make sure incomplete data is not written out. + buf.writerIndex(initial); + PacketErrorEvent e = new PacketErrorEvent(this.session, t); this.session.callEvent(e); if(!e.shouldSuppress()) { @@ -39,11 +44,12 @@ public class TcpPacketCodec extends ByteToMessageCodec { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List out) throws Exception { + int initial = buf.readerIndex(); + Packet packet; try { NetInput in = new ByteBufNetInput(buf); - int initial = buf.readerIndex(); int id = this.session.getPacketProtocol().getPacketHeader().readPacketId(in); if(id == -1) { buf.readerIndex(initial); @@ -57,6 +63,9 @@ public class TcpPacketCodec extends ByteToMessageCodec { throw new IllegalStateException("Packet \"" + packet.getClass().getSimpleName() + "\" not fully read."); } } catch(Throwable t) { + // Advance buffer to end to make sure remaining data in this packet is skipped. + buf.readerIndex(buf.readerIndex() + buf.readableBytes()); + PacketErrorEvent e = new PacketErrorEvent(this.session, t); this.session.callEvent(e); if(!e.shouldSuppress()) {