-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
pmp.go
113 lines (88 loc) · 2.55 KB
/
pmp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package nat
import (
"fmt"
"net"
"sync"
"time"
"github.com/jackpal/gateway"
natpmp "github.com/jackpal/go-nat-pmp"
)
// Compile-time check to ensure PMP implements the Traversal interface.
var _ Traversal = (*PMP)(nil)
// PMP is a concrete implementation of the Traversal interface that uses the
// NAT-PMP technique.
type PMP struct {
client *natpmp.Client
forwardedPortsMtx sync.Mutex
forwardedPorts map[uint16]struct{}
}
// DiscoverPMP attempts to scan the local network for a NAT-PMP enabled device
// within the given timeout.
func DiscoverPMP(timeout time.Duration) (*PMP, error) {
// Retrieve the gateway IP address of the local network.
gatewayIP, err := gateway.DiscoverGateway()
if err != nil {
return nil, err
}
pmp := &PMP{
client: natpmp.NewClientWithTimeout(gatewayIP, timeout),
forwardedPorts: make(map[uint16]struct{}),
}
// We'll then attempt to retrieve the external IP address of this
// device to ensure it is not behind multiple NATs.
if _, err := pmp.ExternalIP(); err != nil {
return nil, err
}
return pmp, nil
}
// ExternalIP returns the external IP address of the NAT-PMP enabled device.
func (p *PMP) ExternalIP() (net.IP, error) {
res, err := p.client.GetExternalAddress()
if err != nil {
return nil, err
}
ip := net.IP(res.ExternalIPAddress[:])
if isPrivateIP(ip) {
return nil, ErrMultipleNAT
}
return ip, nil
}
// AddPortMapping enables port forwarding for the given port.
func (p *PMP) AddPortMapping(port uint16) error {
p.forwardedPortsMtx.Lock()
defer p.forwardedPortsMtx.Unlock()
_, err := p.client.AddPortMapping("tcp", int(port), int(port), 0)
if err != nil {
return err
}
p.forwardedPorts[port] = struct{}{}
return nil
}
// DeletePortMapping disables port forwarding for the given port.
func (p *PMP) DeletePortMapping(port uint16) error {
p.forwardedPortsMtx.Lock()
defer p.forwardedPortsMtx.Unlock()
if _, exists := p.forwardedPorts[port]; !exists {
return fmt.Errorf("port %d is not being forwarded", port)
}
_, err := p.client.AddPortMapping("tcp", int(port), 0, 0)
if err != nil {
return err
}
delete(p.forwardedPorts, port)
return nil
}
// ForwardedPorts returns a list of ports currently being forwarded.
func (p *PMP) ForwardedPorts() []uint16 {
p.forwardedPortsMtx.Lock()
defer p.forwardedPortsMtx.Unlock()
ports := make([]uint16, 0, len(p.forwardedPorts))
for port := range p.forwardedPorts {
ports = append(ports, port)
}
return ports
}
// Name returns the name of the specific NAT traversal technique used.
func (p *PMP) Name() string {
return "NAT-PMP"
}