Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix race condition and nil pointer dereference in holepunch #1467

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions p2p/protocol/holepunch/svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,11 @@ type Service struct {
ctx context.Context
ctxCancel context.CancelFunc

host host.Host
ids identify.IDService
holePuncher *holePuncher
host host.Host
ids identify.IDService

holePuncherMx sync.Mutex
holePuncher *holePuncher

hasPublicAddrsChan chan struct{}

Expand Down Expand Up @@ -138,7 +140,9 @@ func (s *Service) watchForPublicAddr() {
if e.(event.EvtLocalReachabilityChanged).Reachability != network.ReachabilityPrivate {
continue
}
s.holePuncherMx.Lock()
s.holePuncher = newHolePuncher(s.host, s.ids, s.tracer)
s.holePuncherMx.Unlock()
close(s.hasPublicAddrsChan)
return
}
Expand All @@ -147,7 +151,12 @@ func (s *Service) watchForPublicAddr() {

// Close closes the Hole Punch Service.
func (s *Service) Close() error {
err := s.holePuncher.Close()
var err error
s.holePuncherMx.Lock()
if s.holePuncher != nil {
err = s.holePuncher.Close()
}
s.holePuncherMx.Unlock()
s.tracer.Close()
s.host.RemoveStreamHandler(Protocol)
s.ctxCancel()
Expand Down Expand Up @@ -257,5 +266,7 @@ func (s *Service) handleNewStream(str network.Stream) {
// TODO: find a solution for this.
func (s *Service) DirectConnect(p peer.ID) error {
<-s.hasPublicAddrsChan
s.holePuncherMx.Lock()
defer s.holePuncherMx.Unlock()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This locks the mutex for a very long time (on the order of 10s or so). Save s.holePuncher to a local variable instead.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or maybe just use RMutex? And call RLock?

return s.holePuncher.DirectConnect(p)
}