Skip to content

Commit

Permalink
only start the hole puncher if the node is behind a NAT / firewall
Browse files Browse the repository at this point in the history
  • Loading branch information
marten-seemann committed Mar 10, 2022
1 parent 9b26695 commit 85651ee
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
5 changes: 4 additions & 1 deletion p2p/protocol/holepunch/holepunch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,10 @@ func addHolePunchService(t *testing.T, h host.Host, opt holepunch.Option) *holep

func mkHostWithHolePunchSvc(t *testing.T, opts ...holepunch.Option) (host.Host, *holepunch.Service) {
t.Helper()
h, err := libp2p.New(libp2p.ListenAddrs(ma.StringCast("/ip4/127.0.0.1/tcp/0"), ma.StringCast("/ip6/::1/tcp/0")))
h, err := libp2p.New(
libp2p.ListenAddrs(ma.StringCast("/ip4/127.0.0.1/tcp/0"), ma.StringCast("/ip6/::1/tcp/0")),
libp2p.ForceReachabilityPrivate(),
)
require.NoError(t, err)
hps, err := holepunch.NewService(h, newMockIDService(t, h), opts...)
require.NoError(t, err)
Expand Down
34 changes: 29 additions & 5 deletions p2p/protocol/holepunch/svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import (
"sync"
"time"

pb "github.com/libp2p/go-libp2p/p2p/protocol/holepunch/pb"
"github.com/libp2p/go-libp2p/p2p/protocol/identify"

"github.com/libp2p/go-libp2p-core/event"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/protocol"
pb "github.com/libp2p/go-libp2p/p2p/protocol/holepunch/pb"
"github.com/libp2p/go-libp2p/p2p/protocol/identify"

logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-msgio/protoio"
Expand Down Expand Up @@ -103,9 +105,7 @@ func (s *Service) watchForPublicAddr() {
if containsPublicAddr(s.ids.OwnObservedAddrs()) {
log.Debug("Host now has a public address. Starting holepunch protocol.")
s.host.SetStreamHandler(Protocol, s.handleNewStream)
s.holePuncher = newHolePuncher(s.host, s.ids, s.tracer)
close(s.hasPublicAddrsChan)
return
break
}

select {
Expand All @@ -119,6 +119,30 @@ func (s *Service) watchForPublicAddr() {
t.Reset(duration)
}
}

// Only start the holePuncher if we're behind a NAT / firewall.
sub, err := s.host.EventBus().Subscribe(&event.EvtLocalReachabilityChanged{})
if err != nil {
log.Debugf("failed to subscripe to Reachability event: %s", err)
return
}
defer sub.Close()
for {
select {
case <-s.ctx.Done():
return
case e, ok := <-sub.Out():
if !ok {
return
}
if e.(event.EvtLocalReachabilityChanged).Reachability != network.ReachabilityPrivate {
continue
}
s.holePuncher = newHolePuncher(s.host, s.ids, s.tracer)
close(s.hasPublicAddrsChan)
return
}
}
}

// Close closes the Hole Punch Service.
Expand Down

0 comments on commit 85651ee

Please sign in to comment.