diff --git a/common/socket/codec/SocketCodec_Tomee.go b/common/socket/codec/SocketCodec_Tomee.go index b53f8333..9f84e153 100644 --- a/common/socket/codec/SocketCodec_Tomee.go +++ b/common/socket/codec/SocketCodec_Tomee.go @@ -44,9 +44,9 @@ func (codec TomeeSocketCodec) Encode(buf []byte) ([]byte, error) { } func (codec TomeeSocketCodec) Decode(c gnet.Conn) ([]byte, error) { + const maxBodyLen = 10 * 1024 * 1024 // 业务最大包体长度,按需调整 - // handle(c) - // 先读取4字节的包长度 + // 1. 读取4字节长度头 lenBuf, err := c.Peek(4) if err != nil { if errors.Is(err, io.ErrShortBuffer) { @@ -55,11 +55,15 @@ func (codec TomeeSocketCodec) Decode(c gnet.Conn) ([]byte, error) { return nil, err } + // 2. 解析长度并校验上限 bodyLen := binary.BigEndian.Uint32(lenBuf) - totalLen := 4 + int(bodyLen) + if bodyLen > maxBodyLen { + return nil, errors.New("packet body exceeds max length") + } + totalLen := 4 + int(bodyLen) // 总包长=长度头(4)+包体 - // 检查整个包是否完整 - buf, err := c.Peek(int(bodyLen)) + // 3. 检查整个包是否完整(关键修复:用totalLen判断) + fullBuf, err := c.Peek(totalLen) if err != nil { if errors.Is(err, io.ErrShortBuffer) { return nil, ErrIncompletePacket @@ -67,12 +71,15 @@ func (codec TomeeSocketCodec) Decode(c gnet.Conn) ([]byte, error) { return nil, err } - // 提取包体 + // 4. 提取包体(关键修复:跳过前4字节长度头) body := make([]byte, bodyLen) - copy(body, buf) + copy(body, fullBuf[4:]) // 从fullBuf[4:]开始拷贝,仅取包体 - // 从缓冲区中丢弃已读取的数据 - _, _ = c.Discard(totalLen) + // 5. 丢弃已解析的完整数据 + _, err = c.Discard(totalLen) // 原代码用_忽略err,建议处理(可选) + if err != nil { + return nil, err + } return body, nil }