Skip to content

Commit

Permalink
fix: prevent data corruption in multiPacketListener by avoiding buf…
Browse files Browse the repository at this point in the history
…fer resizing (#213)

* Add regression test that covers the issue.

* Fix the test.

* Use consistent comments.
  • Loading branch information
sbruens authored Sep 20, 2024
1 parent 8ee3b79 commit e8ec4d0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
4 changes: 2 additions & 2 deletions service/listeners.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,10 +288,10 @@ func (m *multiPacketListener) Acquire() (net.PacketConn, error) {
buffer := make([]byte, serverUDPBufferSize)
for {
n, addr, err := m.pc.ReadFrom(buffer)
buffer = buffer[:n]
pkt := buffer[:n]
select {
case req := <-m.readCh:
n := copy(req.buffer, buffer)
n := copy(req.buffer, pkt)
req.respCh <- struct {
n int
addr net.Addr
Expand Down
27 changes: 27 additions & 0 deletions service/listeners_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,33 @@ func TestListenerManagerPacketListenerCreatesListenerOnDemand(t *testing.T) {
<-done
}

func TestMultiPacketListener_SequentialReads(t *testing.T) {
m := NewListenerManager()
conn, err := m.ListenPacket("127.0.0.1:0")
require.NoError(t, err)
udpConn, err := net.Dial("udp", conn.LocalAddr().String())
require.NoError(t, err)

// Send and receive the first packet.
data1 := []byte("hello")
_, err = udpConn.Write(data1)
require.NoError(t, err)
received1 := make([]byte, serverUDPBufferSize)
n1, _, err := conn.ReadFrom(received1)
require.NoError(t, err)

// Send and receive a second larger packet.
data2 := []byte("a longer message than the first one")
_, err = udpConn.Write(data2)
require.NoError(t, err)
received2 := make([]byte, serverUDPBufferSize)
n2, _, err := conn.ReadFrom(received2)
require.NoError(t, err)

require.Equal(t, string(data1), string(received1[:n1]))
require.Equal(t, string(data2), string(received2[:n2]))
}

func BenchmarkMultiStreamListener_Acquire(b *testing.B) {
lm := NewListenerManager()

Expand Down

0 comments on commit e8ec4d0

Please sign in to comment.