From a4364828f5dc6307363f74c3f472249d3d2a812f Mon Sep 17 00:00:00 2001 From: 37Sir <827412104@qq.com> Date: Tue, 8 Jun 2021 10:18:33 +0800 Subject: [PATCH] =?UTF-8?q?pref[net]:=E8=A7=A3=E7=A0=81=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../codec/tcp/TcpPacketCodecHandler.java | 31 ++++++++----------- 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/net/src/main/java/com/zfoo/net/handler/codec/tcp/TcpPacketCodecHandler.java b/net/src/main/java/com/zfoo/net/handler/codec/tcp/TcpPacketCodecHandler.java index ae0d3b05..347e0437 100644 --- a/net/src/main/java/com/zfoo/net/handler/codec/tcp/TcpPacketCodecHandler.java +++ b/net/src/main/java/com/zfoo/net/handler/codec/tcp/TcpPacketCodecHandler.java @@ -23,6 +23,7 @@ import com.zfoo.protocol.util.StringUtils; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageCodec; +import io.netty.util.ReferenceCountUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,40 +40,34 @@ public class TcpPacketCodecHandler extends ByteToMessageCodec private static final Logger logger = LoggerFactory.getLogger(TcpPacketCodecHandler.class); - // 数据包的最大长度限制,防止恶意的攻击 - private static final int MAX_LENGTH = 1 * IOUtils.BITS_PER_MB; - private int length; - private boolean remain = false; @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) { try { - if (!remain) { - // 不够读一个int - if (in.readableBytes() <= ProtocolManager.PROTOCOL_HEAD_LENGTH) { - return; - } - length = in.readInt(); - remain = true; + // 不够读一个int + if (in.readableBytes() <= ProtocolManager.PROTOCOL_HEAD_LENGTH) { + return; } + in.markReaderIndex(); + length = in.readInt(); // 如果长度超过限制,则抛出异常断开连接 - if (length > MAX_LENGTH) { + if (length < 0) { throw new IllegalArgumentException(StringUtils - .format("[session:{}]的包头长度[length:{}]超过最大长度[maxLength:{}]限制" - , SessionUtils.sessionInfo(ctx), length, MAX_LENGTH)); + .format("[session:{}]的包头长度[length:{}]非法[maxLength:{}]" + , SessionUtils.sessionInfo(ctx), length)); } // ByteBuf里的数据太小 if (in.readableBytes() < length) { + in.resetReaderIndex(); return; } - remain = false; - - DecodedPacketInfo packetInfo = NetContext.getPacketService().read(in); - + var tmpByteBuf = in.readRetainedSlice(length); + DecodedPacketInfo packetInfo = NetContext.getPacketService().read(tmpByteBuf); + ReferenceCountUtil.release(tmpByteBuf); out.add(packetInfo); } catch (Exception e) { logger.error("[session:{}]解码exception异常", SessionUtils.sessionInfo(ctx), e);