autorelay.go 6.83 KB
Newer Older
vyzo's avatar
vyzo committed
1
2
3
4
5
6
7
8
9
10
11
12
package relay

import (
	"context"
	"fmt"
	"math/rand"
	"sync"
	"time"

	basic "github.com/libp2p/go-libp2p/p2p/host/basic"

	autonat "github.com/libp2p/go-libp2p-autonat"
vyzo's avatar
vyzo committed
13
	_ "github.com/libp2p/go-libp2p-circuit"
vyzo's avatar
vyzo committed
14
15
16
17
18
19
20
21
22
	discovery "github.com/libp2p/go-libp2p-discovery"
	host "github.com/libp2p/go-libp2p-host"
	inet "github.com/libp2p/go-libp2p-net"
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
	ma "github.com/multiformats/go-multiaddr"
	manet "github.com/multiformats/go-multiaddr-net"
)

vyzo's avatar
vyzo committed
23
const (
vyzo's avatar
vyzo committed
24
	RelayRendezvous = "/libp2p/relay"
vyzo's avatar
vyzo committed
25
26
)

vyzo's avatar
vyzo committed
27
28
29
var (
	DesiredRelays = 3

vyzo's avatar
vyzo committed
30
	BootDelay = 60 * time.Second
vyzo's avatar
vyzo committed
31
32

	unspecificRelay ma.Multiaddr
vyzo's avatar
vyzo committed
33
)
vyzo's avatar
vyzo committed
34

vyzo's avatar
vyzo committed
35
36
37
38
39
40
41
42
func init() {
	var err error
	unspecificRelay, err = ma.NewMultiaddr("/p2p-circuit")
	if err != nil {
		panic(err)
	}
}

vyzo's avatar
vyzo committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// AutoRelayHost is a Host that uses relays for connectivity when a NAT is detected.
type AutoRelayHost struct {
	*basic.BasicHost
	discover discovery.Discoverer
	autonat  autonat.AutoNAT
	addrsF   basic.AddrsFactory

	disconnect chan struct{}

	mx     sync.Mutex
	relays map[peer.ID]pstore.PeerInfo
	addrs  []ma.Multiaddr
}

func NewAutoRelayHost(ctx context.Context, bhost *basic.BasicHost, discover discovery.Discoverer) *AutoRelayHost {
	h := &AutoRelayHost{
		BasicHost:  bhost,
		discover:   discover,
		addrsF:     bhost.AddrsFactory,
		relays:     make(map[peer.ID]pstore.PeerInfo),
		disconnect: make(chan struct{}, 1),
	}
65
	h.autonat = autonat.NewAutoNAT(ctx, bhost, h.baseAddrs)
vyzo's avatar
vyzo committed
66
67
68
69
70
71
72
73
74
75
76
77
	bhost.AddrsFactory = h.hostAddrs
	bhost.Network().Notify(h)
	go h.background(ctx)
	return h
}

func (h *AutoRelayHost) hostAddrs(addrs []ma.Multiaddr) []ma.Multiaddr {
	h.mx.Lock()
	defer h.mx.Unlock()
	if h.addrs != nil && h.autonat.Status() == autonat.NATStatusPrivate {
		return h.addrs
	} else {
vyzo's avatar
vyzo committed
78
		return filterUnspecificRelay(h.addrsF(addrs))
vyzo's avatar
vyzo committed
79
80
81
	}
}

82
83
84
85
func (h *AutoRelayHost) baseAddrs() []ma.Multiaddr {
	return filterUnspecificRelay(h.addrsF(h.AllAddrs()))
}

vyzo's avatar
vyzo committed
86
87
func (h *AutoRelayHost) background(ctx context.Context) {
	select {
vyzo's avatar
vyzo committed
88
	case <-time.After(autonat.AutoNATBootDelay + BootDelay):
vyzo's avatar
vyzo committed
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
	case <-ctx.Done():
		return
	}

	for {
		wait := autonat.AutoNATRefreshInterval
		switch h.autonat.Status() {
		case autonat.NATStatusUnknown:
			wait = autonat.AutoNATRetryInterval
		case autonat.NATStatusPublic:
		case autonat.NATStatusPrivate:
			h.findRelays(ctx)
		}

		select {
		case <-h.disconnect:
			// invalidate addrs
			h.mx.Lock()
			h.addrs = nil
			h.mx.Unlock()
		case <-time.After(wait):
		case <-ctx.Done():
			return
		}
	}
}

func (h *AutoRelayHost) findRelays(ctx context.Context) {
	h.mx.Lock()
	if len(h.relays) >= DesiredRelays {
		h.mx.Unlock()
		return
	}
	need := DesiredRelays - len(h.relays)
	h.mx.Unlock()

	limit := 20
126
127
	if need > limit/2 {
		limit = 2 * need
vyzo's avatar
vyzo committed
128
129
130
	}

	dctx, cancel := context.WithTimeout(ctx, 60*time.Second)
vyzo's avatar
vyzo committed
131
	pis, err := discovery.FindPeers(dctx, h.discover, RelayRendezvous, limit)
vyzo's avatar
vyzo committed
132
133
134
135
136
137
	cancel()
	if err != nil {
		log.Debugf("error discovering relays: %s", err.Error())
		return
	}

138
	pis = h.selectRelays(pis)
vyzo's avatar
vyzo committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

	update := 0

	for _, pi := range pis {
		h.mx.Lock()
		if _, ok := h.relays[pi.ID]; ok {
			h.mx.Unlock()
			continue
		}
		h.mx.Unlock()

		cctx, cancel := context.WithTimeout(ctx, 60*time.Second)
		err = h.Connect(cctx, pi)
		cancel()
		if err != nil {
			log.Debugf("error connecting to relay %s: %s", pi.ID, err.Error())
			continue
		}

		log.Debugf("connected to relay %s", pi.ID)
		h.mx.Lock()
		h.relays[pi.ID] = pi
		h.mx.Unlock()

vyzo's avatar
vyzo committed
163
164
165
		// tag the connection as very important
		h.ConnManager().TagPeer(pi.ID, "relay", 42)

vyzo's avatar
vyzo committed
166
167
168
169
170
171
172
173
174
175
176
177
		update++
		need--
		if need == 0 {
			break
		}
	}

	if update > 0 || h.addrs == nil {
		h.updateAddrs()
	}
}

178
179
180
181
182
183
184
func (h *AutoRelayHost) selectRelays(pis []pstore.PeerInfo) []pstore.PeerInfo {
	// 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
}

vyzo's avatar
vyzo committed
185
186
187
188
189
func (h *AutoRelayHost) updateAddrs() {
	h.doUpdateAddrs()
	h.PushIdentify()
}

vyzo's avatar
vyzo committed
190
191
192
193
194
195
196
197
198
// This function updates our NATed advertised addrs (h.addrs)
// The public addrs are rewritten so that they only retain the public IP part; they
// become undialable but are useful as a hint to the dialer to determine whether or not
// to dial private addrs.
// 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.
vyzo's avatar
vyzo committed
199
200
201
202
func (h *AutoRelayHost) doUpdateAddrs() {
	h.mx.Lock()
	defer h.mx.Unlock()

203
	addrs := h.baseAddrs()
vyzo's avatar
vyzo committed
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
	raddrs := make([]ma.Multiaddr, 0, len(addrs)+len(h.relays))

	// remove our public addresses from the list and replace them by just the public IP
	for _, addr := range addrs {
		if manet.IsPublicAddr(addr) {
			ip, err := addr.ValueForProtocol(ma.P_IP4)
			if err == nil {
				pub, err := ma.NewMultiaddr(fmt.Sprintf("/ip4/%s", ip))
				if err != nil {
					panic(err)
				}

				if !containsAddr(raddrs, pub) {
					raddrs = append(raddrs, pub)
				}
				continue
			}

			ip, err = addr.ValueForProtocol(ma.P_IP6)
			if err == nil {
				pub, err := ma.NewMultiaddr(fmt.Sprintf("/ip6/%s", ip))
				if err != nil {
					panic(err)
				}
				if !containsAddr(raddrs, pub) {
					raddrs = append(raddrs, pub)
				}
				continue
			}
		} else {
			raddrs = append(raddrs, addr)
		}
	}

vyzo's avatar
vyzo committed
238
	// add relay specific addrs to the list
vyzo's avatar
vyzo committed
239
	for _, pi := range h.relays {
vyzo's avatar
vyzo committed
240
		circuit, err := ma.NewMultiaddr(fmt.Sprintf("/p2p/%s/p2p-circuit", pi.ID.Pretty()))
vyzo's avatar
vyzo committed
241
242
243
244
		if err != nil {
			panic(err)
		}

vyzo's avatar
vyzo committed
245
246
247
248
249
250
251
252
253
254
255
		for _, addr := range pi.Addrs {
			if !manet.IsPrivateAddr(addr) {
				pub := addr.Encapsulate(circuit)
				raddrs = append(raddrs, pub)
			}
		}
	}

	h.addrs = raddrs
}

vyzo's avatar
vyzo committed
256
257
258
259
260
261
262
263
264
265
266
func filterUnspecificRelay(addrs []ma.Multiaddr) []ma.Multiaddr {
	res := make([]ma.Multiaddr, 0, len(addrs))
	for _, addr := range addrs {
		if addr.Equal(unspecificRelay) {
			continue
		}
		res = append(res, addr)
	}
	return res
}

vyzo's avatar
vyzo committed
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
func shuffleRelays(pis []pstore.PeerInfo) {
	for i := range pis {
		j := rand.Intn(i + 1)
		pis[i], pis[j] = pis[j], pis[i]
	}
}

func containsAddr(lst []ma.Multiaddr, addr ma.Multiaddr) bool {
	for _, xaddr := range lst {
		if xaddr.Equal(addr) {
			return true
		}
	}
	return false
}

// notify
func (h *AutoRelayHost) Listen(inet.Network, ma.Multiaddr)      {}
func (h *AutoRelayHost) ListenClose(inet.Network, ma.Multiaddr) {}
func (h *AutoRelayHost) Connected(inet.Network, inet.Conn)      {}

func (h *AutoRelayHost) Disconnected(_ inet.Network, c inet.Conn) {
	p := c.RemotePeer()
	h.mx.Lock()
	defer h.mx.Unlock()
	if _, ok := h.relays[p]; ok {
		delete(h.relays, p)
		select {
		case h.disconnect <- struct{}{}:
		default:
		}
	}
}

func (h *AutoRelayHost) OpenedStream(inet.Network, inet.Stream) {}
func (h *AutoRelayHost) ClosedStream(inet.Network, inet.Stream) {}

var _ host.Host = (*AutoRelayHost)(nil)