``fix(socket): 修复Tomee解码器包体解析逻辑,添加最大包长限制``

This commit is contained in:
1
2025-10-16 23:43:20 +00:00
parent 3e00cdce8c
commit c9c58a4087

View File

@@ -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
}