Skip to content

Commit f5330da

Browse files
fix race condition in holepunch service (#1473)
Co-authored-by: watjurk <[email protected]>
1 parent e8d7283 commit f5330da

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

p2p/protocol/holepunch/svc.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,11 @@ type Service struct {
4545
ctx context.Context
4646
ctxCancel context.CancelFunc
4747

48-
host host.Host
49-
ids identify.IDService
50-
holePuncher *holePuncher
48+
host host.Host
49+
ids identify.IDService
50+
51+
holePuncherMx sync.Mutex
52+
holePuncher *holePuncher
5153

5254
hasPublicAddrsChan chan struct{}
5355

@@ -138,7 +140,9 @@ func (s *Service) watchForPublicAddr() {
138140
if e.(event.EvtLocalReachabilityChanged).Reachability != network.ReachabilityPrivate {
139141
continue
140142
}
143+
s.holePuncherMx.Lock()
141144
s.holePuncher = newHolePuncher(s.host, s.ids, s.tracer)
145+
s.holePuncherMx.Unlock()
142146
close(s.hasPublicAddrsChan)
143147
return
144148
}
@@ -147,7 +151,12 @@ func (s *Service) watchForPublicAddr() {
147151

148152
// Close closes the Hole Punch Service.
149153
func (s *Service) Close() error {
150-
err := s.holePuncher.Close()
154+
var err error
155+
s.holePuncherMx.Lock()
156+
if s.holePuncher != nil {
157+
err = s.holePuncher.Close()
158+
}
159+
s.holePuncherMx.Unlock()
151160
s.tracer.Close()
152161
s.host.RemoveStreamHandler(Protocol)
153162
s.ctxCancel()
@@ -257,5 +266,8 @@ func (s *Service) handleNewStream(str network.Stream) {
257266
// TODO: find a solution for this.
258267
func (s *Service) DirectConnect(p peer.ID) error {
259268
<-s.hasPublicAddrsChan
260-
return s.holePuncher.DirectConnect(p)
269+
s.holePuncherMx.Lock()
270+
holePuncher := s.holePuncher
271+
s.holePuncherMx.Unlock()
272+
return holePuncher.DirectConnect(p)
261273
}

0 commit comments

Comments
 (0)