This repository has been archived by the owner on Jul 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
deprecated.go
298 lines (250 loc) · 7.49 KB
/
deprecated.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
package autonat
import (
"context"
"math/rand"
"net"
"sync"
"time"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p-core/event"
"github.com/libp2p/go-libp2p-core/helpers"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/peerstore"
pb "github.com/libp2p/go-libp2p-autonat/pb"
autonat "github.com/libp2p/go-libp2p-autonat"
"github.com/libp2p/go-msgio/protoio"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr-net"
)
const P_CIRCUIT = 290
var (
// AutoNATServiceDialTimeout defines how long to wait for connection
// attempts before failing.
// Deprecated - use autonat.config.requestTimeout
AutoNATServiceDialTimeout = 15 * time.Second
// AutoNATServiceResetInterval defines how often to reset throttling.
// Deprecated - use autonat.WithSchedule
AutoNATServiceResetInterval = 1 * time.Minute
// AutoNATServiceResetJitter defines the amplitude of randomness in throttle
// reset timing.
// Deprecated - use autonat.WithSchedule
AutoNATServiceResetJitter = 15 * time.Second
// AutoNATServiceThrottle defines how many times each ResetInterval a peer
// can ask for its autonat address.
// Deprecated - use autonat.WithPeerThrottling
AutoNATServiceThrottle = 3
// AutoNATGlobalThrottle defines how many total autonat requests this
// service will answer each ResetInterval.
// Deprecated - use autonat.WithThrottling
AutoNATGlobalThrottle = 30
// AutoNATMaxPeerAddresses defines maximum number of addreses the autonat
// service will consider when attempting to connect to the peer.
// Deprecated - use autonat.config.maxPeerAddresses
AutoNATMaxPeerAddresses = 16
)
// AutoNATService provides NAT autodetection services to other peers
// Deprecated - use autonat.EnableService
type AutoNATService struct {
ctx context.Context
h host.Host
dialer host.Host
// rate limiter
mx sync.Mutex
reqs map[peer.ID]int
globalReqMax int
globalReqs int
}
// NewAutoNATService creates a new AutoNATService instance attached to a host
// Deprecated - use autonat.EnableService
func NewAutoNATService(ctx context.Context, h host.Host, forceEnabled bool, opts ...libp2p.Option) (*AutoNATService, error) {
opts = append(opts, libp2p.NoListenAddrs)
dialer, err := libp2p.New(ctx, opts...)
if err != nil {
return nil, err
}
as := &AutoNATService{
ctx: ctx,
h: h,
dialer: dialer,
globalReqMax: AutoNATGlobalThrottle,
reqs: make(map[peer.ID]int),
}
if forceEnabled {
as.globalReqMax = 0
h.SetStreamHandler(autonat.AutoNATProto, as.handleStream)
go as.resetRateLimiter()
} else {
go as.enableWhenPublic()
}
return as, nil
}
func (as *AutoNATService) handleStream(s network.Stream) {
defer helpers.FullClose(s)
pid := s.Conn().RemotePeer()
log.Debugf("New stream from %s", pid.Pretty())
r := protoio.NewDelimitedReader(s, network.MessageSizeMax)
w := protoio.NewDelimitedWriter(s)
var req pb.Message
var res pb.Message
err := r.ReadMsg(&req)
if err != nil {
log.Debugf("Error reading message from %s: %s", pid.Pretty(), err.Error())
s.Reset()
return
}
t := req.GetType()
if t != pb.Message_DIAL {
log.Debugf("Unexpected message from %s: %s (%d)", pid.Pretty(), t.String(), t)
s.Reset()
return
}
dr := as.handleDial(pid, s.Conn().RemoteMultiaddr(), req.GetDial().GetPeer())
res.Type = pb.Message_DIAL_RESPONSE.Enum()
res.DialResponse = dr
err = w.WriteMsg(&res)
if err != nil {
log.Debugf("Error writing response to %s: %s", pid.Pretty(), err.Error())
s.Reset()
return
}
}
func (as *AutoNATService) handleDial(p peer.ID, obsaddr ma.Multiaddr, mpi *pb.Message_PeerInfo) *pb.Message_DialResponse {
if mpi == nil {
return newDialResponseError(pb.Message_E_BAD_REQUEST, "missing peer info")
}
mpid := mpi.GetId()
if mpid != nil {
mp, err := peer.IDFromBytes(mpid)
if err != nil {
return newDialResponseError(pb.Message_E_BAD_REQUEST, "bad peer id")
}
if mp != p {
return newDialResponseError(pb.Message_E_BAD_REQUEST, "peer id mismatch")
}
}
addrs := make([]ma.Multiaddr, 0, AutoNATMaxPeerAddresses)
seen := make(map[string]struct{})
// add observed addr to the list of addresses to dial
var obsHost net.IP
if !as.skipDial(obsaddr) {
addrs = append(addrs, obsaddr)
seen[obsaddr.String()] = struct{}{}
obsHost, _ = manet.ToIP(obsaddr)
}
for _, maddr := range mpi.GetAddrs() {
addr, err := ma.NewMultiaddrBytes(maddr)
if err != nil {
log.Debugf("Error parsing multiaddr: %s", err.Error())
continue
}
if as.skipDial(addr) {
continue
}
if ip, err := manet.ToIP(addr); err != nil || !obsHost.Equal(ip) {
continue
}
str := addr.String()
_, ok := seen[str]
if ok {
continue
}
addrs = append(addrs, addr)
seen[str] = struct{}{}
if len(addrs) >= AutoNATMaxPeerAddresses {
break
}
}
if len(addrs) == 0 {
return newDialResponseError(pb.Message_E_DIAL_ERROR, "no dialable addresses")
}
return as.doDial(peer.AddrInfo{ID: p, Addrs: addrs})
}
func (as *AutoNATService) skipDial(addr ma.Multiaddr) bool {
// skip relay addresses
_, err := addr.ValueForProtocol(P_CIRCUIT)
if err == nil {
return true
}
// skip private network (unroutable) addresses
if !manet.IsPublicAddr(addr) {
return true
}
// Skip dialing addresses we believe are the local node's
for _, localAddr := range as.h.Addrs() {
if localAddr.Equal(addr) {
return true
}
}
return false
}
func (as *AutoNATService) doDial(pi peer.AddrInfo) *pb.Message_DialResponse {
// rate limit check
as.mx.Lock()
count := as.reqs[pi.ID]
if count >= AutoNATServiceThrottle || (as.globalReqMax > 0 && as.globalReqs >= as.globalReqMax) {
as.mx.Unlock()
return newDialResponseError(pb.Message_E_DIAL_REFUSED, "too many dials")
}
as.reqs[pi.ID] = count + 1
as.globalReqs++
as.mx.Unlock()
ctx, cancel := context.WithTimeout(as.ctx, AutoNATServiceDialTimeout)
defer cancel()
as.dialer.Peerstore().ClearAddrs(pi.ID)
as.dialer.Peerstore().AddAddrs(pi.ID, pi.Addrs, peerstore.TempAddrTTL)
conn, err := as.dialer.Network().DialPeer(ctx, pi.ID)
if err != nil {
log.Debugf("error dialing %s: %s", pi.ID.Pretty(), err.Error())
// wait for the context to timeout to avoid leaking timing information
// this renders the service ineffective as a port scanner
<-ctx.Done()
return newDialResponseError(pb.Message_E_DIAL_ERROR, "dial failed")
}
ra := conn.RemoteMultiaddr()
as.dialer.Network().ClosePeer(pi.ID)
return newDialResponseOK(ra)
}
func (as *AutoNATService) enableWhenPublic() {
sub, _ := as.h.EventBus().Subscribe(&event.EvtLocalReachabilityChanged{})
defer sub.Close()
running := false
for {
select {
case ev, ok := <-sub.Out():
if !ok {
return
}
state := ev.(event.EvtLocalReachabilityChanged).Reachability
if state == network.ReachabilityPublic {
as.h.SetStreamHandler(autonat.AutoNATProto, as.handleStream)
if !running {
go as.resetRateLimiter()
running = true
}
} else {
as.h.RemoveStreamHandler(autonat.AutoNATProto)
}
case <-as.ctx.Done():
return
}
}
}
func (as *AutoNATService) resetRateLimiter() {
timer := time.NewTimer(AutoNATServiceResetInterval)
defer timer.Stop()
for {
select {
case <-timer.C:
as.mx.Lock()
as.reqs = make(map[peer.ID]int)
as.globalReqs = 0
as.mx.Unlock()
jitter := rand.Float32() * float32(AutoNATServiceResetJitter)
timer.Reset(AutoNATServiceResetInterval + time.Duration(int64(jitter)))
case <-as.ctx.Done():
return
}
}
}