/
port_mapping.go
165 lines (143 loc) · 4.74 KB
/
port_mapping.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/*
* Copyright (C) 2019 The "MysteriumNetwork/node" Authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package mapping
import (
"errors"
"net"
"time"
portmap "github.com/ethereum/go-ethereum/p2p/nat"
"github.com/mysteriumnetwork/node/eventbus"
"github.com/mysteriumnetwork/node/nat/event"
"github.com/rs/zerolog/log"
)
// StageName is used to indicate port mapping NAT traversal stage
const StageName = "port_mapping"
// DefaultConfig returns default port mapping config.
func DefaultConfig() *Config {
return &Config{
MapInterface: portmap.Any(),
MapLifetime: 20 * time.Minute,
MapUpdateInterval: 15 * time.Minute,
}
}
// Config represents port mapping config.
type Config struct {
MapInterface portmap.Interface
MapLifetime time.Duration
MapUpdateInterval time.Duration
}
// PortMapper tries to map port using router's uPnP or NAT-PMP depending on given config map interface.
type PortMapper interface {
// Map maps port for given protocol. It returns release func which
// must be called when port no longer needed and ok which is true if
// port mapping was successful.
Map(id, protocol string, port int, name string) (release func(), ok bool)
}
// NewPortMapper returns port mapper instance.
func NewPortMapper(config *Config, publisher eventbus.Publisher) PortMapper {
return &portMapper{
config: config,
publisher: publisher,
}
}
type portMapper struct {
config *Config
publisher eventbus.Publisher
}
func (p *portMapper) Map(id, protocol string, port int, name string) (release func(), ok bool) {
if !p.routerIPPublic() {
err := errors.New("failed to find router public IP")
log.Info().Err(err).Msg("Port mapping is useless, skipping it.")
p.notify(id, err)
return nil, false
}
// Try add mapping first to determine if it is supported and
// if permanent lease only is supported.
permanent, err := p.addMapping(protocol, port, port, name)
p.notify(id, err)
if err != nil {
return nil, false
}
// If only permanent lease is supported we don't need to update it in intervals.
if permanent {
return func() { p.deleteMapping(protocol, port, port) }, true
}
stopUpdate := make(chan struct{})
go func() {
for {
select {
case <-stopUpdate:
return
case <-time.After(p.config.MapUpdateInterval):
_, err := p.addMapping(protocol, port, port, name)
p.notify(id, err)
}
}
}()
return func() {
p.deleteMapping(protocol, port, port)
close(stopUpdate)
}, true
}
func (p *portMapper) routerIPPublic() bool {
ip, err := p.config.MapInterface.ExternalIP()
if err != nil {
log.Warn().Err(err).Msg("Couldn't detect router IP address")
return false
}
log.Debug().Msgf("Detected router public IP address: %s", ip)
for _, s := range []string{
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"100.64.0.0/10",
"127.0.0.0/8",
"169.254.0.0/16",
} {
_, subnet, _ := net.ParseCIDR(s)
if subnet.Contains(ip) {
return false
}
}
return true
}
func (p *portMapper) notify(id string, err error) {
if err != nil {
p.publisher.Publish(event.AppTopicTraversal, event.BuildFailureEvent(id, StageName, err))
} else {
p.publisher.Publish(event.AppTopicTraversal, event.BuildSuccessfulEvent(id, StageName))
}
}
func (p *portMapper) addMapping(protocol string, extPort, intPort int, name string) (permanent bool, err error) {
if _, err := p.config.MapInterface.AddMapping(protocol, extPort, intPort, name, p.config.MapLifetime); err != nil {
log.Warn().Err(err).Msgf("Couldn't add port mapping for port %d: retrying with permanent lease", extPort)
if _, err := p.config.MapInterface.AddMapping(protocol, extPort, intPort, name, 0); err != nil {
// some gateways support only permanent leases
log.Warn().Err(err).Msgf("Couldn't add port mapping for port %d", extPort)
return false, err
}
return true, nil
}
log.Info().Msgf("Mapped network port: %d", extPort)
return false, nil
}
func (p *portMapper) deleteMapping(protocol string, extPort, intPort int) {
log.Debug().Msgf("Deleting port mapping for port: %d", extPort)
if err := p.config.MapInterface.DeleteMapping(protocol, extPort, intPort); err != nil {
log.Warn().Err(err).Msg("Couldn't delete port mapping")
}
}