chore: move go-nat to internal package

This commit is contained in:
Marco Munizaga
2025-02-21 20:59:52 -08:00
committed by GitHub
12 changed files with 781 additions and 15 deletions

7
go.mod
View File

@@ -15,19 +15,21 @@ require (
github.com/gorilla/websocket v1.5.3
github.com/hashicorp/golang-lru/arc/v2 v2.0.7
github.com/hashicorp/golang-lru/v2 v2.0.7
github.com/huin/goupnp v1.3.0
github.com/ipfs/go-cid v0.5.0
github.com/ipfs/go-datastore v0.6.0
github.com/ipfs/go-ds-badger v0.3.0
github.com/ipfs/go-ds-leveldb v0.5.0
github.com/ipfs/go-log/v2 v2.5.1
github.com/jackpal/go-nat-pmp v1.0.2
github.com/jbenet/go-temp-err-catcher v0.1.0
github.com/klauspost/compress v1.17.11
github.com/koron/go-ssdp v0.0.5
github.com/libp2p/go-buffer-pool v0.1.0
github.com/libp2p/go-flow-metrics v0.2.0
github.com/libp2p/go-libp2p-asn-util v0.4.1
github.com/libp2p/go-libp2p-testing v0.12.0
github.com/libp2p/go-msgio v0.3.0
github.com/libp2p/go-nat v0.2.0
github.com/libp2p/go-netroute v0.2.2
github.com/libp2p/go-reuseport v0.4.0
github.com/libp2p/go-yamux/v5 v5.0.0
@@ -89,11 +91,8 @@ require (
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect
github.com/google/pprof v0.0.0-20250208200701-d0013a598941 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/huin/goupnp v1.3.0 // indirect
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
github.com/jbenet/goprocess v0.1.4 // indirect
github.com/klauspost/cpuid/v2 v2.2.9 // indirect
github.com/koron/go-ssdp v0.0.5 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/miekg/dns v1.1.63 // indirect
github.com/mikioh/tcpopt v0.0.0-20190314235656-172688c1accc // indirect

2
go.sum
View File

@@ -187,8 +187,6 @@ github.com/libp2p/go-libp2p-testing v0.12.0 h1:EPvBb4kKMWO29qP4mZGyhVzUyR25dvfUI
github.com/libp2p/go-libp2p-testing v0.12.0/go.mod h1:KcGDRXyN7sQCllucn1cOOS+Dmm7ujhfEyXQL5lvkcPg=
github.com/libp2p/go-msgio v0.3.0 h1:mf3Z8B1xcFN314sWX+2vOTShIE0Mmn2TXn3YCUQGNj0=
github.com/libp2p/go-msgio v0.3.0/go.mod h1:nyRM819GmVaF9LX3l03RMh10QdOroF++NBbxAb0mmDM=
github.com/libp2p/go-nat v0.2.0 h1:Tyz+bUFAYqGyJ/ppPPymMGbIgNRH+WqC5QrT5fKrrGk=
github.com/libp2p/go-nat v0.2.0/go.mod h1:3MJr+GRpRkyT65EpVPBstXLvOlAPzUVlG6Pwg9ohLJk=
github.com/libp2p/go-netroute v0.2.2 h1:Dejd8cQ47Qx2kRABg6lPwknU7+nBnFRpko45/fFPuZ8=
github.com/libp2p/go-netroute v0.2.2/go.mod h1:Rntq6jUAH0l9Gg17w5bFGhcC9a+vk4KNXs6s7IljKYE=
github.com/libp2p/go-reuseport v0.4.0 h1:nR5KU7hD0WxXCJbmw7r2rhRYruNRl2koHw8fQscQm2s=

View File

@@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of
this License; and
You must cause any modified files to carry prominent notices stating that You
changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same "printed page" as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1 @@
Originally forked from: [fd/go-nat](https://github.com/fd/go-nat).

View File

@@ -0,0 +1,187 @@
// Package nat implements NAT handling facilities
package nat
import (
"context"
"errors"
"fmt"
"math"
"math/rand"
"net"
"strings"
"time"
logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-netroute"
)
var log = logging.Logger("internal/nat")
var ErrNoExternalAddress = errors.New("no external address")
var ErrNoInternalAddress = errors.New("no internal address")
type ErrNoNATFound struct {
Errs []error
}
func (e ErrNoNATFound) Unwrap() []error {
return e.Errs
}
func (e ErrNoNATFound) Error() string {
var errStrs []string
for _, err := range e.Errs {
errStrs = append(errStrs, err.Error())
}
return fmt.Sprintf("no NAT found: [%s]", strings.Join(errStrs, "; "))
}
// protocol is either "udp" or "tcp"
type NAT interface {
// Type returns the kind of NAT port mapping service that is used
Type() string
// GetDeviceAddress returns the internal address of the gateway device.
GetDeviceAddress() (addr net.IP, err error)
// GetExternalAddress returns the external address of the gateway device.
GetExternalAddress() (addr net.IP, err error)
// GetInternalAddress returns the address of the local host.
GetInternalAddress() (addr net.IP, err error)
// AddPortMapping maps a port on the local host to an external port.
AddPortMapping(ctx context.Context, protocol string, internalPort int, description string, timeout time.Duration) (mappedExternalPort int, err error)
// DeletePortMapping removes a port mapping.
DeletePortMapping(ctx context.Context, protocol string, internalPort int) (err error)
}
// discoverNATs returns all NATs discovered in the network.
func discoverNATs(ctx context.Context) ([]NAT, []error) {
type natsAndErrs struct {
nats []NAT
errs []error
}
upnpCh := make(chan natsAndErrs)
pmpCh := make(chan natsAndErrs)
go func() {
defer close(upnpCh)
// We do these UPNP queries sequentially because some routers will fail to handle parallel requests.
nats, errs := discoverUPNP_IG1(ctx)
// Do IG2 after IG1 so that its NAT devices will appear as "better" when we
// find the best NAT to return below.
n, e := discoverUPNP_IG2(ctx)
nats = append(nats, n...)
errs = append(errs, e...)
if len(nats) == 0 {
// We don't have a NAT. We should try querying all devices over
// SSDP to find a InternetGatewayDevice. This shouldn't be necessary for
// a well behaved router.
n, e = discoverUPNP_GenIGDev(ctx)
nats = append(nats, n...)
errs = append(errs, e...)
}
select {
case upnpCh <- natsAndErrs{nats, errs}:
case <-ctx.Done():
}
}()
go func() {
defer close(pmpCh)
nat, err := discoverNATPMP(ctx)
var nats []NAT
var errs []error
if err != nil {
errs = append(errs, err)
} else {
nats = append(nats, nat)
}
select {
case pmpCh <- natsAndErrs{nats, errs}:
case <-ctx.Done():
}
}()
var nats []NAT
var errs []error
for upnpCh != nil || pmpCh != nil {
select {
case res := <-pmpCh:
pmpCh = nil
nats = append(nats, res.nats...)
errs = append(errs, res.errs...)
case res := <-upnpCh:
upnpCh = nil
nats = append(nats, res.nats...)
errs = append(errs, res.errs...)
case <-ctx.Done():
errs = append(errs, ctx.Err())
return nats, errs
}
}
return nats, errs
}
// DiscoverGateway attempts to find a gateway device.
func DiscoverGateway(ctx context.Context) (NAT, error) {
nats, errs := discoverNATs(ctx)
switch len(nats) {
case 0:
return nil, ErrNoNATFound{Errs: errs}
case 1:
if len(errs) > 0 {
log.Debugf("NAT found, but some potentially unrelated errors occurred: %v", errs)
}
return nats[0], nil
}
gw, _ := getDefaultGateway()
bestNAT := nats[0]
natGw, _ := bestNAT.GetDeviceAddress()
bestNATIsGw := gw != nil && natGw.Equal(gw)
// 1. Prefer gateways discovered _last_. This is an OK heuristic for
// discovering the most-upstream (furthest) NAT.
// 2. Prefer gateways that actually match our known gateway address.
// Some relays like to claim to be NATs even if they aren't.
for _, nat := range nats[1:] {
natGw, _ := nat.GetDeviceAddress()
natIsGw := gw != nil && natGw.Equal(gw)
if bestNATIsGw && !natIsGw {
continue
}
bestNATIsGw = natIsGw
bestNAT = nat
}
if len(errs) > 0 {
log.Debugf("NAT found, but some potentially unrelated errors occurred: %v", errs)
}
return bestNAT, nil
}
var random = rand.New(rand.NewSource(time.Now().UnixNano()))
func randomPort() int {
return random.Intn(math.MaxUint16-10000) + 10000
}
func getDefaultGateway() (net.IP, error) {
router, err := netroute.New()
if err != nil {
return nil, err
}
_, ip, _, err := router.Route(net.IPv4zero)
return ip, err
}

View File

@@ -0,0 +1,138 @@
package nat
import (
"context"
"net"
"time"
natpmp "github.com/jackpal/go-nat-pmp"
)
var (
_ NAT = (*natpmpNAT)(nil)
)
func discoverNATPMP(ctx context.Context) (NAT, error) {
ip, err := getDefaultGateway()
if err != nil {
return nil, err
}
clientCh := make(chan *natpmp.Client, 1)
errCh := make(chan error, 1)
// We can't cancel the natpmp library, but we can at least still return
// on context cancellation by putting this in a goroutine
go func() {
client, err := discoverNATPMPWithAddr(ctx, ip)
if err != nil {
errCh <- err
return
}
clientCh <- client
}()
select {
case client := <-clientCh:
return &natpmpNAT{client, ip, make(map[int]int)}, nil
case err := <-errCh:
return nil, err
case <-ctx.Done():
return nil, ctx.Err()
}
}
func discoverNATPMPWithAddr(ctx context.Context, ip net.IP) (*natpmp.Client, error) {
var client *natpmp.Client
if deadline, ok := ctx.Deadline(); ok {
client = natpmp.NewClientWithTimeout(ip, time.Until(deadline))
} else {
client = natpmp.NewClient(ip)
}
_, err := client.GetExternalAddress()
if err != nil {
return nil, err
}
return client, nil
}
type natpmpNAT struct {
c *natpmp.Client
gateway net.IP
ports map[int]int
}
func (n *natpmpNAT) GetDeviceAddress() (addr net.IP, err error) {
return n.gateway, nil
}
func (n *natpmpNAT) GetInternalAddress() (addr net.IP, err error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, iface := range ifaces {
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
switch x := addr.(type) {
case *net.IPNet:
if x.Contains(n.gateway) {
return x.IP, nil
}
}
}
}
return nil, ErrNoInternalAddress
}
func (n *natpmpNAT) GetExternalAddress() (addr net.IP, err error) {
res, err := n.c.GetExternalAddress()
if err != nil {
return nil, err
}
d := res.ExternalIPAddress
return net.IPv4(d[0], d[1], d[2], d[3]), nil
}
func (n *natpmpNAT) AddPortMapping(_ context.Context, protocol string, internalPort int, _ string, timeout time.Duration) (int, error) {
var (
err error
)
timeoutInSeconds := int(timeout / time.Second)
if externalPort := n.ports[internalPort]; externalPort > 0 {
_, err = n.c.AddPortMapping(protocol, internalPort, externalPort, timeoutInSeconds)
if err == nil {
n.ports[internalPort] = externalPort
return externalPort, nil
}
}
for i := 0; i < 3; i++ {
externalPort := randomPort()
_, err = n.c.AddPortMapping(protocol, internalPort, externalPort, timeoutInSeconds)
if err == nil {
n.ports[internalPort] = externalPort
return externalPort, nil
}
}
return 0, err
}
func (n *natpmpNAT) DeletePortMapping(_ context.Context, _ string, internalPort int) (err error) {
delete(n.ports, internalPort)
return nil
}
func (n *natpmpNAT) Type() string {
return "NAT-PMP"
}

View File

@@ -0,0 +1,256 @@
package nat
import (
"context"
"fmt"
"net"
"net/url"
"strings"
"time"
"github.com/huin/goupnp"
"github.com/huin/goupnp/dcps/internetgateway1"
"github.com/huin/goupnp/dcps/internetgateway2"
"github.com/koron/go-ssdp"
)
var _ NAT = (*upnp_NAT)(nil)
func discoverUPNP_IG1(ctx context.Context) ([]NAT, []error) {
return discoverSearchTarget(ctx, internetgateway1.URN_WANConnectionDevice_1)
}
func discoverUPNP_IG2(ctx context.Context) ([]NAT, []error) {
return discoverSearchTarget(ctx, internetgateway2.URN_WANConnectionDevice_2)
}
func discoverSearchTarget(ctx context.Context, target string) (nats []NAT, errs []error) {
// find devices
devs, err := goupnp.DiscoverDevicesCtx(ctx, target)
if err != nil {
errs = append(errs, err)
return
}
for _, dev := range devs {
if dev.Err != nil {
errs = append(errs, dev.Err)
continue
}
dev.Root.Device.VisitServices(serviceVisitor(ctx, dev.Root, &nats, &errs))
}
return
}
// discoverUPNP_GenIGDev is a fallback for routers that fail to respond to our
// targetted SSDP queries. It will query all devices and try to find any
// InternetGatewayDevice.
func discoverUPNP_GenIGDev(ctx context.Context) (nats []NAT, errs []error) {
DeviceList, err := ssdp.Search(ssdp.All, 5, "")
if err != nil {
errs = append(errs, err)
return
}
// Limit the number of InternetGateways we'll query. Normally we'd only
// expect 1 or 2, but in case of a weird network we also don't want to do
// too much work.
const maxIGDevs = 3
foundIGDevs := 0
for _, Service := range DeviceList {
if !strings.Contains(Service.Type, "InternetGatewayDevice") {
continue
}
if foundIGDevs >= maxIGDevs {
log.Debug("found more than maxIGDevs UPnP devices, stopping search")
break
}
foundIGDevs++
DeviceURL, err := url.Parse(Service.Location)
if err != nil {
errs = append(errs, err)
continue
}
RootDevice, err := goupnp.DeviceByURLCtx(ctx, DeviceURL)
if err != nil {
errs = append(errs, err)
continue
}
RootDevice.Device.VisitServices(serviceVisitor(ctx, RootDevice, &nats, &errs))
}
return
}
// serviceVisitor is a vistor function that visits all services of a root
// device and collects NATs.
//
// It works on InternetGateway V1 and V2 devices. For V1 devices, V2 services should not be encountered, and the visitor will collect an error in that case.
func serviceVisitor(ctx context.Context, rootDevice *goupnp.RootDevice, outNats *[]NAT, outErrs *[]error) func(srv *goupnp.Service) {
return func(srv *goupnp.Service) {
if ctx.Err() != nil {
return
}
switch srv.ServiceType {
case internetgateway2.URN_WANIPConnection_1:
client := &internetgateway2.WANIPConnection1{ServiceClient: goupnp.ServiceClient{
SOAPClient: srv.NewSOAPClient(),
RootDevice: rootDevice,
Service: srv,
}}
_, isNat, err := client.GetNATRSIPStatusCtx(ctx)
if err != nil {
*outErrs = append(*outErrs, err)
} else if isNat {
*outNats = append(*outNats, &upnp_NAT{client, make(map[int]int), "UPNP (IP1)", rootDevice})
}
case internetgateway2.URN_WANIPConnection_2:
if rootDevice.Device.DeviceType == internetgateway2.URN_WANConnectionDevice_1 {
*outErrs = append(*outErrs, fmt.Errorf("found V2 service on V1 device"))
return
}
client := &internetgateway2.WANIPConnection2{ServiceClient: goupnp.ServiceClient{
SOAPClient: srv.NewSOAPClient(),
RootDevice: rootDevice,
Service: srv,
}}
_, isNat, err := client.GetNATRSIPStatusCtx(ctx)
if err != nil {
*outErrs = append(*outErrs, err)
} else if isNat {
*outNats = append(*outNats, &upnp_NAT{client, make(map[int]int), "UPNP (IP2)", rootDevice})
}
case internetgateway2.URN_WANPPPConnection_1:
client := &internetgateway2.WANPPPConnection1{ServiceClient: goupnp.ServiceClient{
SOAPClient: srv.NewSOAPClient(),
RootDevice: rootDevice,
Service: srv,
}}
_, isNat, err := client.GetNATRSIPStatusCtx(ctx)
if err != nil {
*outErrs = append(*outErrs, err)
} else if isNat {
*outNats = append(*outNats, &upnp_NAT{client, make(map[int]int), "UPNP (PPP1)", rootDevice})
}
}
}
}
type upnp_NAT_Client interface {
GetExternalIPAddress() (string, error)
AddPortMappingCtx(context.Context, string, uint16, string, uint16, string, bool, string, uint32) error
DeletePortMappingCtx(context.Context, string, uint16, string) error
}
type upnp_NAT struct {
c upnp_NAT_Client
ports map[int]int
typ string
rootDevice *goupnp.RootDevice
}
func (u *upnp_NAT) GetExternalAddress() (addr net.IP, err error) {
ipString, err := u.c.GetExternalIPAddress()
if err != nil {
return nil, err
}
ip := net.ParseIP(ipString)
if ip == nil {
return nil, ErrNoExternalAddress
}
return ip, nil
}
func mapProtocol(s string) string {
switch s {
case "udp":
return "UDP"
case "tcp":
return "TCP"
default:
panic("invalid protocol: " + s)
}
}
func (u *upnp_NAT) AddPortMapping(ctx context.Context, protocol string, internalPort int, description string, timeout time.Duration) (int, error) {
ip, err := u.GetInternalAddress()
if err != nil {
return 0, nil
}
timeoutInSeconds := uint32(timeout / time.Second)
if externalPort := u.ports[internalPort]; externalPort > 0 {
err = u.c.AddPortMappingCtx(ctx, "", uint16(externalPort), mapProtocol(protocol), uint16(internalPort), ip.String(), true, description, timeoutInSeconds)
if err == nil {
return externalPort, nil
}
}
for i := 0; i < 3; i++ {
externalPort := randomPort()
err = u.c.AddPortMappingCtx(ctx, "", uint16(externalPort), mapProtocol(protocol), uint16(internalPort), ip.String(), true, description, timeoutInSeconds)
if err == nil {
u.ports[internalPort] = externalPort
return externalPort, nil
}
}
return 0, err
}
func (u *upnp_NAT) DeletePortMapping(ctx context.Context, protocol string, internalPort int) error {
if externalPort := u.ports[internalPort]; externalPort > 0 {
delete(u.ports, internalPort)
return u.c.DeletePortMappingCtx(ctx, "", uint16(externalPort), mapProtocol(protocol))
}
return nil
}
func (u *upnp_NAT) GetDeviceAddress() (net.IP, error) {
addr, err := net.ResolveUDPAddr("udp4", u.rootDevice.URLBase.Host)
if err != nil {
return nil, err
}
return addr.IP, nil
}
func (u *upnp_NAT) GetInternalAddress() (net.IP, error) {
devAddr, err := u.GetDeviceAddress()
if err != nil {
return nil, err
}
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, iface := range ifaces {
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
switch x := addr.(type) {
case *net.IPNet:
if x.Contains(devAddr) {
return x.IP, nil
}
}
}
}
return nil, ErrNoInternalAddress
}
func (n *upnp_NAT) Type() string { return n.typ }

View File

@@ -1,9 +1,9 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/libp2p/go-nat (interfaces: NAT)
// Source: github.com/libp2p/go-libp2p/p2p/net/nat/internal/nat (interfaces: NAT)
//
// Generated by this command:
//
// mockgen -package nat -destination mock_nat_test.go github.com/libp2p/go-nat NAT
// mockgen -package nat -destination mock_nat_test.go github.com/libp2p/go-libp2p/p2p/net/nat/internal/nat NAT
//
// Package nat is a generated GoMock package.

View File

@@ -11,7 +11,7 @@ import (
logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-nat"
"github.com/libp2p/go-libp2p/p2p/net/nat/internal/nat"
)
// ErrNoMapping signals no mapping exists for an address

View File

@@ -7,13 +7,12 @@ import (
"net/netip"
"testing"
"github.com/libp2p/go-nat"
"github.com/libp2p/go-libp2p/p2p/net/nat/internal/nat"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
)
//go:generate sh -c "go run go.uber.org/mock/mockgen -package nat -destination mock_nat_test.go github.com/libp2p/go-nat NAT"
//go:generate sh -c "go run go.uber.org/mock/mockgen -package nat -destination mock_nat_test.go github.com/libp2p/go-libp2p/p2p/net/nat/internal/nat NAT"
func setupMockNAT(t *testing.T) (mockNAT *MockNAT, reset func()) {
t.Helper()

View File

@@ -40,7 +40,6 @@ require (
github.com/libp2p/go-flow-metrics v0.2.0 // indirect
github.com/libp2p/go-libp2p-asn-util v0.4.1 // indirect
github.com/libp2p/go-msgio v0.3.0 // indirect
github.com/libp2p/go-nat v0.2.0 // indirect
github.com/libp2p/go-netroute v0.2.2 // indirect
github.com/libp2p/go-reuseport v0.4.0 // indirect
github.com/libp2p/go-yamux/v5 v5.0.0 // indirect

View File

@@ -143,8 +143,6 @@ github.com/libp2p/go-libp2p-testing v0.12.0 h1:EPvBb4kKMWO29qP4mZGyhVzUyR25dvfUI
github.com/libp2p/go-libp2p-testing v0.12.0/go.mod h1:KcGDRXyN7sQCllucn1cOOS+Dmm7ujhfEyXQL5lvkcPg=
github.com/libp2p/go-msgio v0.3.0 h1:mf3Z8B1xcFN314sWX+2vOTShIE0Mmn2TXn3YCUQGNj0=
github.com/libp2p/go-msgio v0.3.0/go.mod h1:nyRM819GmVaF9LX3l03RMh10QdOroF++NBbxAb0mmDM=
github.com/libp2p/go-nat v0.2.0 h1:Tyz+bUFAYqGyJ/ppPPymMGbIgNRH+WqC5QrT5fKrrGk=
github.com/libp2p/go-nat v0.2.0/go.mod h1:3MJr+GRpRkyT65EpVPBstXLvOlAPzUVlG6Pwg9ohLJk=
github.com/libp2p/go-netroute v0.2.2 h1:Dejd8cQ47Qx2kRABg6lPwknU7+nBnFRpko45/fFPuZ8=
github.com/libp2p/go-netroute v0.2.2/go.mod h1:Rntq6jUAH0l9Gg17w5bFGhcC9a+vk4KNXs6s7IljKYE=
github.com/libp2p/go-reuseport v0.4.0 h1:nR5KU7hD0WxXCJbmw7r2rhRYruNRl2koHw8fQscQm2s=