-
Notifications
You must be signed in to change notification settings - Fork 1k
/
autorelay.go
332 lines (275 loc) · 7.68 KB
/
autorelay.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package relay
import (
"context"
"fmt"
"math/rand"
"sync"
"time"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/routing"
autonat "github.com/libp2p/go-libp2p-autonat"
_ "github.com/libp2p/go-libp2p-circuit"
discovery "github.com/libp2p/go-libp2p-discovery"
basic "github.com/libp2p/go-libp2p/p2p/host/basic"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr-net"
)
const (
RelayRendezvous = "/libp2p/relay"
)
var (
DesiredRelays = 3
BootDelay = 20 * time.Second
)
// AutoRelay is a Host that uses relays for connectivity when a NAT is detected.
type AutoRelay struct {
host *basic.BasicHost
discover discovery.Discoverer
router routing.PeerRouting
autonat autonat.AutoNAT
addrsF basic.AddrsFactory
disconnect chan struct{}
mx sync.Mutex
relays map[peer.ID]struct{}
status autonat.NATStatus
cachedAddrs []ma.Multiaddr
cachedAddrsExpiry time.Time
}
func NewAutoRelay(ctx context.Context, bhost *basic.BasicHost, discover discovery.Discoverer, router routing.PeerRouting) *AutoRelay {
ar := &AutoRelay{
host: bhost,
discover: discover,
router: router,
addrsF: bhost.AddrsFactory,
relays: make(map[peer.ID]struct{}),
disconnect: make(chan struct{}, 1),
status: autonat.NATStatusUnknown,
}
ar.autonat = autonat.NewAutoNAT(ctx, bhost, ar.baseAddrs)
bhost.AddrsFactory = ar.hostAddrs
bhost.Network().Notify(ar)
go ar.background(ctx)
return ar
}
func (ar *AutoRelay) baseAddrs() []ma.Multiaddr {
return ar.addrsF(ar.host.AllAddrs())
}
func (ar *AutoRelay) hostAddrs(addrs []ma.Multiaddr) []ma.Multiaddr {
return ar.relayAddrs(ar.addrsF(addrs))
}
func (ar *AutoRelay) background(ctx context.Context) {
select {
case <-time.After(autonat.AutoNATBootDelay + BootDelay):
case <-ctx.Done():
return
}
// when true, we need to identify push
push := false
for {
wait := autonat.AutoNATRefreshInterval
switch ar.autonat.Status() {
case autonat.NATStatusUnknown:
ar.mx.Lock()
ar.status = autonat.NATStatusUnknown
ar.mx.Unlock()
wait = autonat.AutoNATRetryInterval
case autonat.NATStatusPublic:
ar.mx.Lock()
if ar.status != autonat.NATStatusPublic {
push = true
}
ar.status = autonat.NATStatusPublic
ar.mx.Unlock()
case autonat.NATStatusPrivate:
update := ar.findRelays(ctx)
ar.mx.Lock()
if update || ar.status != autonat.NATStatusPrivate {
push = true
}
ar.status = autonat.NATStatusPrivate
ar.mx.Unlock()
}
if push {
ar.mx.Lock()
ar.cachedAddrs = nil
ar.mx.Unlock()
push = false
ar.host.PushIdentify()
}
select {
case <-ar.disconnect:
push = true
case <-time.After(wait):
case <-ctx.Done():
return
}
}
}
func (ar *AutoRelay) findRelays(ctx context.Context) bool {
if ar.numRelays() >= DesiredRelays {
return false
}
update := false
for retry := 0; retry < 5; retry++ {
if retry > 0 {
log.Debug("no relays connected; retrying in 30s")
select {
case <-time.After(30 * time.Second):
case <-ctx.Done():
return update
}
}
update = ar.findRelaysOnce(ctx) || update
if ar.numRelays() > 0 {
return update
}
}
return update
}
func (ar *AutoRelay) findRelaysOnce(ctx context.Context) bool {
pis, err := ar.discoverRelays(ctx)
if err != nil {
log.Debugf("error discovering relays: %s", err)
return false
}
log.Debugf("discovered %d relays", len(pis))
pis = ar.selectRelays(ctx, pis)
log.Debugf("selected %d relays", len(pis))
update := false
for _, pi := range pis {
update = ar.tryRelay(ctx, pi) || update
if ar.numRelays() >= DesiredRelays {
break
}
}
return update
}
func (ar *AutoRelay) numRelays() int {
ar.mx.Lock()
defer ar.mx.Unlock()
return len(ar.relays)
}
// usingRelay returns if we're currently using the given relay.
func (ar *AutoRelay) usingRelay(p peer.ID) bool {
ar.mx.Lock()
defer ar.mx.Unlock()
_, ok := ar.relays[p]
return ok
}
// addRelay adds the given relay to our set of relays.
// returns true when we add a new relay
func (ar *AutoRelay) tryRelay(ctx context.Context, pi peer.AddrInfo) bool {
if ar.usingRelay(pi.ID) {
return false
}
if !ar.connect(ctx, pi) {
return false
}
ar.mx.Lock()
defer ar.mx.Unlock()
// make sure we're still connected.
if ar.host.Network().Connectedness(pi.ID) != network.Connected {
return false
}
ar.relays[pi.ID] = struct{}{}
return true
}
func (ar *AutoRelay) connect(ctx context.Context, pi peer.AddrInfo) bool {
ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
if len(pi.Addrs) == 0 {
var err error
pi, err = ar.router.FindPeer(ctx, pi.ID)
if err != nil {
log.Debugf("error finding relay peer %s: %s", pi.ID, err.Error())
return false
}
}
err := ar.host.Connect(ctx, pi)
if err != nil {
log.Debugf("error connecting to relay %s: %s", pi.ID, err.Error())
return false
}
// tag the connection as very important
ar.host.ConnManager().TagPeer(pi.ID, "relay", 42)
return true
}
func (ar *AutoRelay) discoverRelays(ctx context.Context) ([]peer.AddrInfo, error) {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
return discovery.FindPeers(ctx, ar.discover, RelayRendezvous, discovery.Limit(1000))
}
func (ar *AutoRelay) selectRelays(ctx context.Context, pis []peer.AddrInfo) []peer.AddrInfo {
// TODO better relay selection strategy; this just selects random relays
// but we should probably use ping latency as the selection metric
shuffleRelays(pis)
return pis
}
// This function is computes the NATed relay addrs when our status is private:
// - The public addrs are removed from the address set.
// - The non-public addrs are included verbatim so that peers behind the same NAT/firewall
// can still dial us directly.
// - On top of those, we add the relay-specific addrs for the relays to which we are
// connected. For each non-private relay addr, we encapsulate the p2p-circuit addr
// through which we can be dialed.
func (ar *AutoRelay) relayAddrs(addrs []ma.Multiaddr) []ma.Multiaddr {
ar.mx.Lock()
defer ar.mx.Unlock()
if ar.status != autonat.NATStatusPrivate {
return addrs
}
if ar.cachedAddrs != nil && time.Now().Before(ar.cachedAddrsExpiry) {
return ar.cachedAddrs
}
raddrs := make([]ma.Multiaddr, 0, 4*len(ar.relays)+4)
// only keep private addrs from the original addr set
for _, addr := range addrs {
if manet.IsPrivateAddr(addr) {
raddrs = append(raddrs, addr)
}
}
// add relay specific addrs to the list
for p := range ar.relays {
addrs := cleanupAddressSet(ar.host.Peerstore().Addrs(p))
circuit, err := ma.NewMultiaddr(fmt.Sprintf("/p2p/%s/p2p-circuit", p.Pretty()))
if err != nil {
panic(err)
}
for _, addr := range addrs {
pub := addr.Encapsulate(circuit)
raddrs = append(raddrs, pub)
}
}
ar.cachedAddrs = raddrs
ar.cachedAddrsExpiry = time.Now().Add(30 * time.Second)
return raddrs
}
func shuffleRelays(pis []peer.AddrInfo) {
for i := range pis {
j := rand.Intn(i + 1)
pis[i], pis[j] = pis[j], pis[i]
}
}
// Notifee
func (ar *AutoRelay) Listen(network.Network, ma.Multiaddr) {}
func (ar *AutoRelay) ListenClose(network.Network, ma.Multiaddr) {}
func (ar *AutoRelay) Connected(network.Network, network.Conn) {}
func (ar *AutoRelay) Disconnected(net network.Network, c network.Conn) {
p := c.RemotePeer()
ar.mx.Lock()
defer ar.mx.Unlock()
if ar.host.Network().Connectedness(p) == network.Connected {
// We have a second connection.
return
}
if _, ok := ar.relays[p]; ok {
delete(ar.relays, p)
select {
case ar.disconnect <- struct{}{}:
default:
}
}
}
func (ar *AutoRelay) OpenedStream(network.Network, network.Stream) {}
func (ar *AutoRelay) ClosedStream(network.Network, network.Stream) {}