Skip to content

Commit

Permalink
dev: add maxBodySize and recover read loop
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangxu19830126 committed Oct 8, 2018
1 parent e6119a3 commit fbef9f6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
17 changes: 15 additions & 2 deletions codec_length_field.go
@@ -1,8 +1,15 @@
package goetty

import (
"fmt"
)

const (
// FieldLength field length bytes
FieldLength = 4

// DefaultMaxBodySize max default body size, 10M
DefaultMaxBodySize = 1024 * 1024 * 10
)

// IntLengthFieldBasedDecoder decoder based on length filed + data
Expand All @@ -11,11 +18,12 @@ type IntLengthFieldBasedDecoder struct {
lengthFieldOffset int
lengthAdjustment int
initialBytesToStrip int
maxBodySize int
}

// NewIntLengthFieldBasedDecoder create a IntLengthFieldBasedDecoder
func NewIntLengthFieldBasedDecoder(base Decoder) Decoder {
return NewIntLengthFieldBasedDecoderSize(base, 0, 0, 0)
return NewIntLengthFieldBasedDecoderSize(base, 0, 0, 0, DefaultMaxBodySize)
}

// NewIntLengthFieldBasedDecoderSize create a IntLengthFieldBasedDecoder
Expand All @@ -25,12 +33,13 @@ func NewIntLengthFieldBasedDecoder(base Decoder) Decoder {
// 2. -4: base decoder received: 4(length) + body
// 3. -(4 + lengthFieldOffset): base decoder received: lengthFieldOffset + 4(length) + body
// 4. -(4 + lengthFieldOffset + initialBytesToStrip): base decoder received: initialBytesToStrip + lengthFieldOffset + 4(length)
func NewIntLengthFieldBasedDecoderSize(base Decoder, lengthFieldOffset, lengthAdjustment, initialBytesToStrip int) Decoder {
func NewIntLengthFieldBasedDecoderSize(base Decoder, lengthFieldOffset, lengthAdjustment, initialBytesToStrip, maxBodySize int) Decoder {
return &IntLengthFieldBasedDecoder{
base: base,
lengthFieldOffset: lengthFieldOffset,
lengthAdjustment: lengthAdjustment,
initialBytesToStrip: initialBytesToStrip,
maxBodySize: maxBodySize,
}
}

Expand All @@ -48,6 +57,10 @@ func (decoder IntLengthFieldBasedDecoder) Decode(in *ByteBuf) (bool, interface{}
return true, nil, err
}

if length > decoder.maxBodySize {
return false, nil, fmt.Errorf("too big body size %d, max is %d", length, decoder.maxBodySize)
}

skip := minFrameLength + decoder.lengthAdjustment
minFrameLength += length
if readable < minFrameLength {
Expand Down
7 changes: 7 additions & 0 deletions server.go
@@ -1,6 +1,7 @@
package goetty

import (
"log"
"net"
"sync"
"sync/atomic"
Expand Down Expand Up @@ -164,6 +165,12 @@ func (s *Server) Start(loopFn func(IOSession) error) error {
s.addSession(session)

go func() {
defer func() {
if err := recover(); err != nil {
log.Printf("goetty: connection painc %+v", err)
}
}()

loopFn(session)
session.Close()
s.deleteSession(session)
Expand Down

0 comments on commit fbef9f6

Please sign in to comment.