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: ignore mapping if external port is 0 #3094

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
6 changes: 5 additions & 1 deletion p2p/net/nat/nat.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ func (nat *NAT) GetMapping(protocol string, port int) (addr netip.AddrPort, foun
return netip.AddrPort{}, false
}
extPort, found := nat.mappings[entry{protocol: protocol, port: port}]
if !found {
// The mapping may have an invalid port.
if !found || extPort == 0 {
return netip.AddrPort{}, false
}
return netip.AddrPortFrom(nat.extAddr, uint16(extPort)), true
Expand Down Expand Up @@ -135,6 +136,9 @@ func (nat *NAT) AddMapping(ctx context.Context, protocol string, port int) error
// do it once synchronously, so first mapping is done right away, and before exiting,
// allowing users -- in the optimistic case -- to use results right after.
extPort := nat.establishMapping(ctx, protocol, port)
// Don't validate the mapping here, we refresh the mappings based on this map.
// We can try getting a port again in case it succeeds. In the worst case,
// this is one extra LAN request every few minutes.
nat.mappings[entry{protocol: protocol, port: port}] = extPort
return nil
}
Expand Down
15 changes: 15 additions & 0 deletions p2p/net/nat/nat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,18 @@ func TestRemoveMapping(t *testing.T) {
_, found = nat.GetMapping("tcp", 10000)
require.False(t, found, "didn't expect port mapping for deleted mapping")
}

func TestAddMappingInvalidPort(t *testing.T) {
mockNAT, reset := setupMockNAT(t)
defer reset()

mockNAT.EXPECT().GetExternalAddress().Return(net.IPv4(1, 2, 3, 4), nil)
nat, err := DiscoverNAT(context.Background())
require.NoError(t, err)

mockNAT.EXPECT().AddPortMapping(gomock.Any(), "tcp", 10000, gomock.Any(), MappingDuration).Return(0, nil)
require.NoError(t, nat.AddMapping(context.Background(), "tcp", 10000))

_, found := nat.GetMapping("tcp", 10000)
require.False(t, found, "didn't expect a port mapping for invalid nat-ed port")
}
Loading