Skip to content

Commit

Permalink
fixed the issue with closing channel twice
Browse files Browse the repository at this point in the history
  • Loading branch information
ameshkov committed Feb 2, 2024
1 parent 869234a commit 739e790
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion internal/udp/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ type Listener struct {

chanAccept chan *udpConn
chanClosed chan struct{}

closed bool
closedMu sync.Mutex
}

// Listen creates a new *Listener and is supposed to be a function similar
Expand Down Expand Up @@ -56,6 +59,10 @@ var _ net.Listener = (*Listener)(nil)

// Accept implements the net.Listener interface for *Listener.
func (l *Listener) Accept() (conn net.Conn, err error) {
if l.isClosed() {
return nil, net.ErrClosed
}

select {
case conn = <-l.chanAccept:
return conn, nil
Expand All @@ -66,6 +73,14 @@ func (l *Listener) Accept() (conn net.Conn, err error) {

// Close implements the net.Listener interface for *Listener.
func (l *Listener) Close() (err error) {
if l.isClosed() {
return nil
}

l.closedMu.Lock()
l.closed = true
l.closedMu.Unlock()

close(l.chanClosed)

l.natTableMu.Lock()
Expand All @@ -82,13 +97,21 @@ func (l *Listener) Addr() (addr net.Addr) {
return l.conn.LocalAddr()
}

// isClosed returns true if the listener is already closed.
func (l *Listener) isClosed() (ok bool) {
l.closedMu.Lock()
defer l.closedMu.Unlock()

return l.closed
}

// readLoop implements the listener logic, it reads incoming data and passes it
// to the corresponding udpConn. When a new udpConn is created, it is written
// to the chanAccept channel.
func (l *Listener) readLoop() {
buf := make([]byte, 65536)

for {
for !l.isClosed() {
n, addr, err := l.conn.ReadFromUDP(buf)

if err != nil || n == 0 {
Expand Down Expand Up @@ -215,6 +238,10 @@ func (c *udpConn) Close() (err error) {
c.closedMu.Lock()
defer c.closedMu.Unlock()

if c.closed {
return nil
}

c.closed = true
close(c.chanClosed)

Expand Down

0 comments on commit 739e790

Please sign in to comment.