Skip to content

Commit

Permalink
fix natManager to close natManager.nat (#1468)
Browse files Browse the repository at this point in the history
* rename natManager.natnatmu to follow the standard

* fix natManager to close natManager.nat

* natmgr: move close to defer in background
  • Loading branch information
watjurk authored Jun 15, 2022
1 parent 5a06093 commit 8840285
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions p2p/host/basic/natmgr.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func NewNATManager(net network.Network) NATManager {
// * closing the natManager closes the nat and its mappings.
type natManager struct {
net network.Network
natmu sync.RWMutex
natMx sync.RWMutex
nat *inat.NAT

ready chan struct{} // closed once the nat is ready to process port mappings
Expand Down Expand Up @@ -79,6 +79,14 @@ func (nmgr *natManager) Ready() <-chan struct{} {
func (nmgr *natManager) background(ctx context.Context) {
defer nmgr.refCount.Done()

defer func() {
nmgr.natMx.Lock()
if nmgr.nat != nil {
nmgr.nat.Close()
}
nmgr.natMx.Unlock()
}()

discoverCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
natInstance, err := inat.DiscoverNAT(discoverCtx)
Expand All @@ -88,9 +96,9 @@ func (nmgr *natManager) background(ctx context.Context) {
return
}

nmgr.natmu.Lock()
nmgr.natMx.Lock()
nmgr.nat = natInstance
nmgr.natmu.Unlock()
nmgr.natMx.Unlock()
close(nmgr.ready)

// sign natManager up for network notifications
Expand Down Expand Up @@ -209,8 +217,8 @@ func (nmgr *natManager) doSync() {
// (a) the search process is still ongoing, or (b) the search process
// found no nat. Clients must check whether the return value is nil.
func (nmgr *natManager) NAT() *inat.NAT {
nmgr.natmu.Lock()
defer nmgr.natmu.Unlock()
nmgr.natMx.Lock()
defer nmgr.natMx.Unlock()
return nmgr.nat
}

Expand Down

0 comments on commit 8840285

Please sign in to comment.