Skip to content

Commit

Permalink
pkg spec: fix concurrent issue
Browse files Browse the repository at this point in the history
since multiple goroutines may invoke methods on a PacketConn simultaneously
we should make spec.PacketConnWrapper thread safe
  • Loading branch information
rkonfj committed May 26, 2023
1 parent 4e521e5 commit 44e7ed2
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions spec/spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"net"
"strings"
"sync"
"time"
)

Expand Down Expand Up @@ -159,16 +160,21 @@ func (c *WSStreamConn) SetWriteDeadline(t time.Time) error {
// PacketConnWrapper wrap UDP conn
type PacketConnWrapper struct {
net.Conn
l sync.RWMutex
}

func (c *PacketConnWrapper) WriteTo(b []byte, addr net.Addr) (int, error) {
if c.RemoteAddr().String() != addr.String() {
return 0, errors.New("connection-oriented UDP does not allow write to another address")
}
c.l.Lock()
defer c.l.Unlock()
return c.Conn.Write(b)
}

func (c *PacketConnWrapper) ReadFrom(b []byte) (int, net.Addr, error) {
c.l.Lock()
defer c.l.Unlock()
n, err := c.Conn.Read(b)
return n, c.RemoteAddr(), err
}

0 comments on commit 44e7ed2

Please sign in to comment.