Skip to content

Commit

Permalink
skip invalid bytes in connection read (#653)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevmo314 authored Dec 10, 2024
1 parent db334b3 commit 51f00fa
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 13 deletions.
42 changes: 29 additions & 13 deletions pkg/conn/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,36 @@ func NewConn(rw io.ReadWriter) *Conn {

// Read reads a Request, a Response or an Interleaved frame.
func (c *Conn) Read() (interface{}, error) {
byts, err := c.br.Peek(2)
if err != nil {
return nil, err
for {
byts, err := c.br.Peek(2)
if err != nil {
return nil, err
}

if byts[0] == base.InterleavedFrameMagicByte {
return c.ReadInterleavedFrame()
}

if byts[0] == 'R' && byts[1] == 'T' {
return c.ReadResponse()
}

if (byts[0] == 'A' && byts[1] == 'N') ||
(byts[0] == 'D' && byts[1] == 'E') ||
(byts[0] == 'G' && byts[1] == 'E') ||
(byts[0] == 'O' && byts[1] == 'P') ||
(byts[0] == 'P' && byts[1] == 'A') ||
(byts[0] == 'P' && byts[1] == 'L') ||
(byts[0] == 'R' && byts[1] == 'E') ||
(byts[0] == 'S' && byts[1] == 'E') ||
(byts[0] == 'T' && byts[1] == 'E') {
return c.ReadRequest()
}

if _, err := c.br.Discard(1); err != nil {
return nil, err
}
}

if byts[0] == base.InterleavedFrameMagicByte {
return c.ReadInterleavedFrame()
}

if byts[0] == 'R' && byts[1] == 'T' {
return c.ReadResponse()
}

return c.ReadRequest()
}

// ReadRequest reads a Request.
Expand Down
26 changes: 26 additions & 0 deletions pkg/conn/conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,32 @@ func TestRead(t *testing.T) {
}
}

func TestReadConsecutiveFrameMagicBytes(t *testing.T) {
buf := bytes.NewBuffer([]byte{
// interleaved frame
0x24, 0x6, 0x0, 0x4, 0x1, 0x2, 0x3, 0x4,
// random bytes
0x00, 0x00, 0x00,
// another interleaved frame
0x24, 0x6, 0x0, 0x4, 0x1, 0x2, 0x3, 0x4,
})
conn := NewConn(buf)
dec1, err := conn.Read()
require.NoError(t, err)
require.Equal(t,
&base.InterleavedFrame{
Channel: 6,
Payload: []byte{0x01, 0x02, 0x03, 0x04},
}, dec1)
dec2, err := conn.Read()
require.NoError(t, err)
require.Equal(t,
&base.InterleavedFrame{
Channel: 6,
Payload: []byte{0x01, 0x02, 0x03, 0x04},
}, dec2)
}

func TestReadError(t *testing.T) {
var buf bytes.Buffer
conn := NewConn(&buf)
Expand Down

0 comments on commit 51f00fa

Please sign in to comment.