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

nat: add HasNAT method for checking NAT environments #2346

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
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
37 changes: 25 additions & 12 deletions p2p/host/basic/basic_host.go
Original file line number Diff line number Diff line change
Expand Up @@ -843,16 +843,14 @@ func (h *BasicHost) AllAddrs() []ma.Multiaddr {

finalAddrs = network.DedupAddrs(finalAddrs)

// natmgr is nil if we do not use nat option;
if h.natmgr != nil {
// We have successfully mapped ports on our NAT. Use those
// instead of observed addresses (mostly).

// Next, apply this mapping to our addresses.
// use nat mappings if we have them
if h.natmgr != nil && h.natmgr.HasNAT() {
// Use nat mappings for our addresses, if we have them.
var unmapped []ma.Multiaddr
for _, listen := range listenAddrs {
extMaddr := h.natmgr.GetMapping(listen)
if extMaddr == nil {
// not mapped
unmapped = append(unmapped, listen)
continue
}

Expand All @@ -871,16 +869,18 @@ func (h *BasicHost) AllAddrs() []ma.Multiaddr {
}

// No.
// in case the router gives us a wrong address or we're behind a double-NAT.
// also add observed addresses
resolved, err := manet.ResolveUnspecifiedAddress(listen, allIfaceAddrs)
// In case the router gives us a wrong address or we're behind a double-NAT,
// also add observed addresses. Check for both the listen address
// and the resolved addresses. It is important to check for the listen address
// as the local address on connections for some transports is unspecified.
addrs, err := manet.ResolveUnspecifiedAddress(listen, allIfaceAddrs)
if err != nil {
// This can happen if we try to resolve /ip6/::/...
// without any IPv6 interface addresses.
continue
}

for _, addr := range resolved {
addrs = append(addrs, listen)
for _, addr := range addrs {
Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm a little suspicious about this code in general. Why do we trust the NAT device to give us the correct external port, but not the IP address? Or, in other words, how likely is it that the NAT device gives us the correct port mapping but the incorrect public IP address?

Copy link
Member Author

Choose a reason for hiding this comment

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

This is not about the NAT giving the IP address, this is about this line returning the correct addresses for the listen address.
#2346

// Now, check if we have any observed addresses that
// differ from the one reported by the router. Routers
// don't always give the most accurate information.
Expand All @@ -904,6 +904,19 @@ func (h *BasicHost) AllAddrs() []ma.Multiaddr {
}
}
}
// Add observed addresses for umapped addresses
for _, listen := range unmapped {
Copy link
Collaborator

Choose a reason for hiding this comment

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

This didn't exist before. What did this fix for you? This codepath gets hit in the case we discover a NAT device, but fail to register a mapping, is that correct?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes. If you are unable to do a nat mapping after discovering a NAT device this code path fixes it.

addrs, err := manet.ResolveUnspecifiedAddress(listen, allIfaceAddrs)
if err != nil {
// This can happen if we try to resolve /ip6/::/...
// without any IPv6 interface addresses.
continue
}
addrs = append(addrs, listen)
for _, addr := range addrs {
finalAddrs = append(finalAddrs, h.ids.ObservedAddrsFor(addr)...)
}
}
} else {
var observedAddrs []ma.Multiaddr
if h.ids != nil {
Expand Down
91 changes: 91 additions & 0 deletions p2p/host/basic/basic_host_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@ import (
"github.com/libp2p/go-libp2p/core/protocol"
"github.com/libp2p/go-libp2p/core/record"
"github.com/libp2p/go-libp2p/p2p/host/autonat"
blhost "github.com/libp2p/go-libp2p/p2p/host/blank"
"github.com/libp2p/go-libp2p/p2p/host/eventbus"
swarmt "github.com/libp2p/go-libp2p/p2p/net/swarm/testing"
"github.com/libp2p/go-libp2p/p2p/protocol/identify"
"github.com/libp2p/go-libp2p/p2p/protocol/identify/pb"
"github.com/libp2p/go-msgio/pbio"

ma "github.com/multiformats/go-multiaddr"

Expand Down Expand Up @@ -241,6 +244,94 @@ func TestAllAddrs(t *testing.T) {
require.True(t, ma.Contains(h.AllAddrs(), firstAddr), "should still contain the original addr")
}

func TestAllAddrsIdentify(t *testing.T) {
oldThreshold := identify.ActivationThresh
identify.ActivationThresh = 1
defer func() { identify.ActivationThresh = oldThreshold }()

h1, err := NewHost(swarmt.GenSwarm(t, swarmt.OptDialOnly), nil)
require.NoError(t, err)
defer h1.Close()
laddr := ma.StringCast("/ip4/0.0.0.0/udp/0/quic-v1")
require.NoError(t, h1.Network().Listen(laddr))

h1.IDService().Start()
defer h1.IDService().Close()

var wg sync.WaitGroup
wg.Add(1)
// inform the host that its address is 1.2.3.4:1234
obsAddr := ma.StringCast("/ip4/1.2.3.4/udp/1234/quic-v1")
idHandler := func(s network.Stream) {
msg := &pb.Identify{}
msg.ObservedAddr = obsAddr.Bytes()
writer := pbio.NewDelimitedWriter(s)
if err := writer.WriteMsg(msg); err != nil {
t.Fatal(err)
}
s.Close()
wg.Done()
}
h2 := blhost.NewBlankHost(swarmt.GenSwarm(t))
h2.SetStreamHandler(identify.ID, idHandler)

err = h2.Connect(context.Background(), peer.AddrInfo{ID: h1.ID(), Addrs: h1.Addrs()})
require.NoError(t, err)
wg.Wait()

require.Eventually(t,
func() bool { return ma.Contains(h1.AllAddrs(), obsAddr) },
5*time.Second,
100*time.Millisecond,
)
}

func TestAllAddrsNAT(t *testing.T) {
oldThreshold := identify.ActivationThresh
identify.ActivationThresh = 1
defer func() { identify.ActivationThresh = oldThreshold }()

h1, err := NewHost(swarmt.GenSwarm(t, swarmt.OptDialOnly), &HostOpts{
NATManager: func(net network.Network) NATManager { return NewNATManager(net) },
})
require.NoError(t, err)
defer h1.Close()

h1.IDService().Start()
defer h1.IDService().Close()

laddr := ma.StringCast("/ip4/0.0.0.0/udp/0/quic-v1")
require.NoError(t, h1.Network().Listen(laddr))

var wg sync.WaitGroup
wg.Add(1)

// inform the host that its address is 1.2.3.4:1234
obsAddr := ma.StringCast("/ip4/1.2.3.4/udp/1234/quic-v1")
idHandler := func(s network.Stream) {
msg := &pb.Identify{}
msg.ObservedAddr = obsAddr.Bytes()
writer := pbio.NewDelimitedWriter(s)
if err := writer.WriteMsg(msg); err != nil {
t.Fatal(err)
}
s.Close()
wg.Done()
}
h2 := blhost.NewBlankHost(swarmt.GenSwarm(t))
h2.SetStreamHandler(identify.ID, idHandler)
err = h2.Connect(context.Background(), peer.AddrInfo{ID: h1.ID(), Addrs: h1.Addrs()})
require.NoError(t, err)

wg.Wait()

require.Eventually(t,
func() bool { return ma.Contains(h1.AllAddrs(), obsAddr) },
5*time.Second,
100*time.Millisecond,
)
}

// getHostPair gets a new pair of hosts.
// The first host initiates the connection to the second host.
func getHostPair(t *testing.T) (host.Host, host.Host) {
Expand Down
7 changes: 7 additions & 0 deletions p2p/host/basic/natmgr.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
// and tries to obtain port mappings for those.
type NATManager interface {
GetMapping(ma.Multiaddr) ma.Multiaddr
HasNAT() bool
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't think we should call this HasNAT because this checks if we can communicate with a NAT device. If we have a NAT, but are unable to communicate with it (e.g. via upnp) then, this would return false.

Maybe call it HasDiscoveredNAT instead?

io.Closer
}

Expand Down Expand Up @@ -86,6 +87,12 @@ func (nmgr *natManager) Close() error {
return nil
}

func (nmgr *natManager) HasNAT() bool {
nmgr.natMx.RLock()
defer nmgr.natMx.RUnlock()
return nmgr.nat != nil
}

func (nmgr *natManager) background(ctx context.Context) {
defer nmgr.refCount.Done()

Expand Down