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

listeners: Use net.UDPConn instead #3999

Closed
wants to merge 1 commit into from
Closed
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
23 changes: 14 additions & 9 deletions listeners.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,20 +76,25 @@ func ListenPacket(network, addr string) (net.PacketConn, error) {
if lnGlobal, ok := listeners[lnKey]; ok {
atomic.AddInt32(&lnGlobal.usage, 1)
log.Printf("[DEBUG] %s: Usage counter should not go above 2 or maybe 3, is now: %d", lnKey, atomic.LoadInt32(&lnGlobal.usage)) // TODO: remove
return &fakeClosePacketConn{usage: &lnGlobal.usage, key: lnKey, PacketConn: lnGlobal.pc}, nil
return &fakeCloseUDPConn{usage: &lnGlobal.usage, key: lnKey, UDPConn: &lnGlobal.udpc}, nil
}

udpaddr, err := net.ResolveUDPAddr(network, addr)
if err != nil {
return nil, err
}

// or, create new one and save it
pc, err := net.ListenPacket(network, addr)
udpc, err := net.ListenUDP(network, udpaddr)
if err != nil {
return nil, err
}

// make sure to start its usage counter at 1
lnGlobal := &globalListener{usage: 1, pc: pc}
lnGlobal := &globalListener{usage: 1, udpc: *udpc}
listeners[lnKey] = lnGlobal

return &fakeClosePacketConn{usage: &lnGlobal.usage, key: lnKey, PacketConn: pc}, nil
return &fakeCloseUDPConn{usage: &lnGlobal.usage, key: lnKey, UDPConn: udpc}, nil
}

// fakeCloseListener's Close() method is a no-op. This allows
Expand Down Expand Up @@ -202,14 +207,14 @@ func (fcl *fakeCloseListener) fakeClosedErr() error {
}
}

type fakeClosePacketConn struct {
type fakeCloseUDPConn struct {
closed int32 // accessed atomically
usage *int32 // accessed atomically
key string
net.PacketConn
*net.UDPConn
}

func (fcpc *fakeClosePacketConn) Close() error {
func (fcpc *fakeCloseUDPConn) Close() error {
log.Println("[DEBUG] Fake-closing underlying packet conn") // TODO: remove this

if atomic.CompareAndSwapInt32(&fcpc.closed, 0, 1) {
Expand All @@ -220,7 +225,7 @@ func (fcpc *fakeClosePacketConn) Close() error {
listenersMu.Lock()
delete(listeners, fcpc.key)
listenersMu.Unlock()
err := fcpc.PacketConn.Close()
err := fcpc.UDPConn.Close()
if err != nil {
return err
}
Expand Down Expand Up @@ -251,7 +256,7 @@ type globalListener struct {
deadline bool
deadlineMu sync.Mutex
ln net.Listener
pc net.PacketConn
udpc net.UDPConn
}

// NetworkAddress contains the individual components
Expand Down