-
Notifications
You must be signed in to change notification settings - Fork 1
/
autonat.go
215 lines (179 loc) · 4.8 KB
/
autonat.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package autonat
import (
"context"
"errors"
"math/rand"
"sync"
"time"
host "github.com/ipsn/go-ipfs/gxlibs/github.com/libp2p/go-libp2p-host"
inet "github.com/ipsn/go-ipfs/gxlibs/github.com/libp2p/go-libp2p-net"
peer "github.com/ipsn/go-ipfs/gxlibs/github.com/libp2p/go-libp2p-peer"
ma "github.com/ipsn/go-ipfs/gxlibs/github.com/multiformats/go-multiaddr"
)
// NATStatus is the state of NAT as detected by the ambient service.
type NATStatus int
const (
// NAT status is unknown; this means that the ambient service has not been
// able to decide the presence of NAT in the most recent attempt to test
// dial through known autonat peers. initial state.
NATStatusUnknown NATStatus = iota
// NAT status is publicly dialable
NATStatusPublic
// NAT status is private network
NATStatusPrivate
)
var (
AutoNATBootDelay = 15 * time.Second
AutoNATRetryInterval = 90 * time.Second
AutoNATRefreshInterval = 15 * time.Minute
AutoNATRequestTimeout = 60 * time.Second
)
// AutoNAT is the interface for ambient NAT autodiscovery
type AutoNAT interface {
// Status returns the current NAT status
Status() NATStatus
// PublicAddr returns the public dial address when NAT status is public and an
// error otherwise
PublicAddr() (ma.Multiaddr, error)
}
// AmbientAutoNAT is the implementation of ambient NAT autodiscovery
type AmbientAutoNAT struct {
ctx context.Context
host host.Host
getAddrs GetAddrs
mx sync.Mutex
peers map[peer.ID]struct{}
status NATStatus
addr ma.Multiaddr
// Reflects the confidence on of the NATStatus being private, as a single
// dialback may fail for reasons unrelated to NAT.
// If it is <3, then multiple autoNAT peers may be contacted for dialback
// If only a single autoNAT peer is known, then the confidence increases
// for each failure until it reaches 3.
confidence int
}
// NewAutoNAT creates a new ambient NAT autodiscovery instance attached to a host
// If getAddrs is nil, h.Addrs will be used
func NewAutoNAT(ctx context.Context, h host.Host, getAddrs GetAddrs) AutoNAT {
if getAddrs == nil {
getAddrs = h.Addrs
}
as := &AmbientAutoNAT{
ctx: ctx,
host: h,
getAddrs: getAddrs,
peers: make(map[peer.ID]struct{}),
status: NATStatusUnknown,
}
h.Network().Notify(as)
go as.background()
return as
}
func (as *AmbientAutoNAT) Status() NATStatus {
return as.status
}
func (as *AmbientAutoNAT) PublicAddr() (ma.Multiaddr, error) {
as.mx.Lock()
defer as.mx.Unlock()
if as.status != NATStatusPublic {
return nil, errors.New("NAT Status is not public")
}
return as.addr, nil
}
func (as *AmbientAutoNAT) background() {
// wait a bit for the node to come online and establish some connections
// before starting autodetection
select {
case <-time.After(AutoNATBootDelay):
case <-as.ctx.Done():
return
}
for {
as.autodetect()
delay := AutoNATRefreshInterval
if as.status == NATStatusUnknown {
delay = AutoNATRetryInterval
}
select {
case <-time.After(delay):
case <-as.ctx.Done():
return
}
}
}
func (as *AmbientAutoNAT) autodetect() {
peers := as.getPeers()
if len(peers) == 0 {
log.Debugf("skipping NAT auto detection; no autonat peers")
return
}
cli := NewAutoNATClient(as.host, as.getAddrs)
failures := 0
for _, p := range peers {
ctx, cancel := context.WithTimeout(as.ctx, AutoNATRequestTimeout)
a, err := cli.DialBack(ctx, p)
cancel()
switch {
case err == nil:
log.Debugf("NAT status is public; address through %s: %s", p.Pretty(), a.String())
as.mx.Lock()
as.addr = a
as.status = NATStatusPublic
as.confidence = 0
as.mx.Unlock()
return
case IsDialError(err):
log.Debugf("dial error through %s: %s", p.Pretty(), err.Error())
failures++
if failures >= 3 || as.confidence >= 3 { // 3 times is enemy action
log.Debugf("NAT status is private")
as.mx.Lock()
as.status = NATStatusPrivate
as.confidence = 3
as.mx.Unlock()
return
}
default:
log.Debugf("Error dialing through %s: %s", p.Pretty(), err.Error())
}
}
as.mx.Lock()
if failures > 0 {
as.status = NATStatusPrivate
as.confidence++
log.Debugf("NAT status is private")
} else {
as.status = NATStatusUnknown
as.confidence = 0
log.Debugf("NAT status is unknown")
}
as.mx.Unlock()
}
func (as *AmbientAutoNAT) getPeers() []peer.ID {
as.mx.Lock()
defer as.mx.Unlock()
if len(as.peers) == 0 {
return nil
}
var connected, others []peer.ID
for p := range as.peers {
if as.host.Network().Connectedness(p) == inet.Connected {
connected = append(connected, p)
} else {
others = append(others, p)
}
}
shufflePeers(connected)
if len(connected) < 3 {
shufflePeers(others)
return append(connected, others...)
} else {
return connected
}
}
func shufflePeers(peers []peer.ID) {
for i := range peers {
j := rand.Intn(i + 1)
peers[i], peers[j] = peers[j], peers[i]
}
}