Skip to content
This repository has been archived by the owner on May 26, 2022. It is now read-only.

Commit

Permalink
fix race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
marten-seemann committed Jun 30, 2021
1 parent e14c3ed commit afc0382
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
7 changes: 6 additions & 1 deletion listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,13 @@ func (l *listener) Accept() (tpt.CapableConn, error) {
if ok {
select {
case holePunch.connCh <- conn:
// We need to delete the entry from the map here,
// in case we accept two connections from the same address.
l.transport.holePunchingMx.Lock()
delete(l.transport.holePunching, key)
l.transport.holePunchingMx.Unlock()
continue
case <-holePunch.ctx.Done():
default:
}
}

Expand Down
12 changes: 4 additions & 8 deletions transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,12 +241,6 @@ func (t *transport) holePunch(ctx context.Context, network string, addr *net.UDP
t.holePunching[key] = activeHolePunch{connCh: connCh, ctx: ctx}
t.holePunchingMx.Unlock()

defer func() {
t.holePunchingMx.Lock()
delete(t.holePunching, key)
t.holePunchingMx.Unlock()
}()

payload := make([]byte, 64)
for i := 0; ; i++ {
if _, err := rand.Read(payload); err != nil {
Expand All @@ -260,12 +254,14 @@ func (t *transport) holePunch(ctx context.Context, network string, addr *net.UDP
if maxSleep > 200 {
maxSleep = 200
}
sleep := 10*time.Millisecond + time.Duration(rand.Intn(maxSleep))*time.Millisecond
select {
case c := <-connCh:
return c, nil
case <-time.After(sleep):
case <-time.After(10*time.Millisecond + time.Duration(rand.Intn(maxSleep))*time.Millisecond):
case <-ctx.Done():
t.holePunchingMx.Lock()
delete(t.holePunching, key)
t.holePunchingMx.Unlock()
return nil, ErrHolePunching
}
}
Expand Down

0 comments on commit afc0382

Please sign in to comment.