From a49cea8008b6fdffd611dc85fe5a34776d9ee4ef Mon Sep 17 00:00:00 2001 From: watjurk Date: Wed, 27 Apr 2022 12:54:24 +0200 Subject: [PATCH 1/2] fix race condition and nil pointer dereference in holepunch --- p2p/protocol/holepunch/svc.go | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/p2p/protocol/holepunch/svc.go b/p2p/protocol/holepunch/svc.go index 8fc9158f8e..1697afc35f 100644 --- a/p2p/protocol/holepunch/svc.go +++ b/p2p/protocol/holepunch/svc.go @@ -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{} @@ -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 } @@ -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() From 2d86af0195944427533b4cd624eaf43be047762d Mon Sep 17 00:00:00 2001 From: watjurk Date: Thu, 28 Apr 2022 16:25:55 +0200 Subject: [PATCH 2/2] add mutex guard to holepunch/srv.go DirectConnect --- p2p/protocol/holepunch/svc.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/p2p/protocol/holepunch/svc.go b/p2p/protocol/holepunch/svc.go index 1697afc35f..d3b52941df 100644 --- a/p2p/protocol/holepunch/svc.go +++ b/p2p/protocol/holepunch/svc.go @@ -266,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() return s.holePuncher.DirectConnect(p) }