Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevent data corruption in multiPacketListener by avoiding buffer resizing #213

Merged
merged 3 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading