Skip to content

Commit

Permalink
Protect udpConnMap with mutex
Browse files Browse the repository at this point in the history
Resolves #23
  • Loading branch information
enobufs committed Jul 14, 2019
1 parent b5efffc commit a583f52
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
26 changes: 14 additions & 12 deletions vnet/conn_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ package vnet
import (
"fmt"
"net"
"sync"
)

type udpConnMap struct {
portMap map[int][]*UDPConn
mutex sync.RWMutex
}

func newUDPConnMap() *udpConnMap {
Expand All @@ -16,6 +18,9 @@ func newUDPConnMap() *udpConnMap {
}

func (m *udpConnMap) insert(conn *UDPConn) error {
m.mutex.Lock()
defer m.mutex.Unlock()

udpAddr := conn.LocalAddr().(*net.UDPAddr)

// check if the port has a listener
Expand All @@ -42,6 +47,9 @@ func (m *udpConnMap) insert(conn *UDPConn) error {
}

func (m *udpConnMap) find(addr net.Addr) (*UDPConn, bool) {
m.mutex.Lock() // could be RLock, but we have delete() op
defer m.mutex.Unlock()

udpAddr := addr.(*net.UDPAddr)

if conns, ok := m.portMap[udpAddr.Port]; ok {
Expand All @@ -67,6 +75,9 @@ func (m *udpConnMap) find(addr net.Addr) (*UDPConn, bool) {
}

func (m *udpConnMap) delete(addr net.Addr) error {
m.mutex.Lock()
defer m.mutex.Unlock()

udpAddr := addr.(*net.UDPAddr)

conns, ok := m.portMap[udpAddr.Port]
Expand Down Expand Up @@ -107,22 +118,13 @@ func (m *udpConnMap) delete(addr net.Addr) error {

// size returns the number of UDPConns (UDP listeners)
func (m *udpConnMap) size() int {
m.mutex.RLock()
defer m.mutex.RUnlock()

n := 0
for _, conns := range m.portMap {
n += len(conns)
}

return n
}

// patterns
// * insert 0.0.0.0:1234
// * find 0.0.0.0:1234
// * find 192.168.0.1:1234
// - find 192.168.0.1:1234
// - find 0.0.0.0
// * delete 0.0.0.0:1234
// * delete 192.168.0.1:1234
// question
// * insert 192.168.0.1:1234 when 0.0.0.0 already exists => error
// * insert 0.0.0.0 when 192.168.0.1 already exists => error
2 changes: 1 addition & 1 deletion vnet/net.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ func (v *vNet) listenPacket(network string, address string) (UDPPacketConn, erro
v.mutex.Lock()
defer v.mutex.Unlock()

locAddr, err := net.ResolveUDPAddr(network, address)
locAddr, err := v.resolveUDPAddr(network, address)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit a583f52

Please sign in to comment.