@@ -45,9 +45,11 @@ type Service struct {
45
45
ctx context.Context
46
46
ctxCancel context.CancelFunc
47
47
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
51
53
52
54
hasPublicAddrsChan chan struct {}
53
55
@@ -138,7 +140,9 @@ func (s *Service) watchForPublicAddr() {
138
140
if e .(event.EvtLocalReachabilityChanged ).Reachability != network .ReachabilityPrivate {
139
141
continue
140
142
}
143
+ s .holePuncherMx .Lock ()
141
144
s .holePuncher = newHolePuncher (s .host , s .ids , s .tracer )
145
+ s .holePuncherMx .Unlock ()
142
146
close (s .hasPublicAddrsChan )
143
147
return
144
148
}
@@ -147,7 +151,12 @@ func (s *Service) watchForPublicAddr() {
147
151
148
152
// Close closes the Hole Punch Service.
149
153
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 ()
151
160
s .tracer .Close ()
152
161
s .host .RemoveStreamHandler (Protocol )
153
162
s .ctxCancel ()
@@ -257,5 +266,8 @@ func (s *Service) handleNewStream(str network.Stream) {
257
266
// TODO: find a solution for this.
258
267
func (s * Service ) DirectConnect (p peer.ID ) error {
259
268
<- 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 )
261
273
}
0 commit comments