Skip to content

Commit

Permalink
[fix #7] reading network packets
Browse files Browse the repository at this point in the history
  • Loading branch information
staskobzar committed Apr 12, 2024
1 parent b0baed7 commit 0ab9492
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 5 deletions.
5 changes: 1 addition & 4 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,9 @@ func readPack(conn net.Conn, buf []byte) (string, error) {
for {
n, err := conn.Read(buf)
if err != nil {
return "", fmt.Errorf("%w: failed read: %s", ErrConn, err)
return packet, fmt.Errorf("%w: failed read: %s", ErrConn, err)
}
packet += string(buf[:n])
if len(packet) > len(buf) {
return "", fmt.Errorf("%w: too long input: %d", ErrAMI, len(packet))
}

if strings.HasSuffix(packet, "\r\n\r\n") {
return packet, nil
Expand Down
39 changes: 39 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"context"
"net"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -258,3 +259,41 @@ func TestClientReadPartialNetworkInput(t *testing.T) {
})
}
}

func TestReadConn(t *testing.T) {
tests := map[string]struct {
input string
bufSize int
wantErr error
}{
`less then buffer`: {
"12345\r\n\r\n", 9, nil},
`bigger then buffer with full end`: {
"1234512345\r\n\r\n", 9, nil},
`invalid packet end`: {
"123456789", 5, ErrConn},
`split to multiple packets`: {
strings.Repeat("a", 120) + "\r\n\r\n", 5, nil},
`crln split on read`: {
"1234\r\n\r\n", 6, nil},
`incomplete ending crln`: {
"1234\r\n\r", 9, ErrConn},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
r, w := net.Pipe()
assert.Nil(t,
r.SetReadDeadline(time.Now().Add(10*time.Millisecond)))

go func(input string) {
_, _ = w.Write([]byte(input))
}(tc.input)

buf := make([]byte, tc.bufSize)
data, err := readPack(r, buf)
assert.ErrorIs(t, err, tc.wantErr)
assert.Equal(t, tc.input, data)
})
}
}
2 changes: 1 addition & 1 deletion goami2.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
const (
bufSize = 1 << 12
promptPrefix = "Asterisk Call Manager/"
netTimeout = 2 * time.Second // default timeout for network read/write
netTimeout = 1 * time.Second // default timeout for network read/write
chanGiveup = 10 * time.Millisecond // timeout to giveup sending to a channel
)

Expand Down

0 comments on commit 0ab9492

Please sign in to comment.