id.go 13.8 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
2
3
package identify

import (
4
	"context"
5
	"net"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	"sync"
7
	"time"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8

Jeromy's avatar
Jeromy committed
9
	ggio "github.com/gogo/protobuf/io"
Jeromy's avatar
Jeromy committed
10
	logging "github.com/ipfs/go-log"
11
	autonat "github.com/libp2p/go-libp2p-autonat"
Jeromy's avatar
Jeromy committed
12
	ic "github.com/libp2p/go-libp2p-crypto"
Jeromy's avatar
Jeromy committed
13
	host "github.com/libp2p/go-libp2p-host"
Jeromy's avatar
Jeromy committed
14
	lgbl "github.com/libp2p/go-libp2p-loggables"
Jeromy's avatar
Jeromy committed
15
	inet "github.com/libp2p/go-libp2p-net"
Jeromy's avatar
Jeromy committed
16
17
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
18
	pb "github.com/libp2p/go-libp2p/p2p/protocol/identify/pb"
Jeromy's avatar
Jeromy committed
19
	ma "github.com/multiformats/go-multiaddr"
Jeromy's avatar
Jeromy committed
20
	msmux "github.com/multiformats/go-multistream"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21
22
)

Jeromy's avatar
Jeromy committed
23
var log = logging.Logger("net/identify")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24
25

// ID is the protocol.ID of the Identify Service.
Jeromy's avatar
Jeromy committed
26
const ID = "/ipfs/id/1.0.0"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27

28
29
30
// IDPush is the protocol.ID of the Identify push protocol
const IDPush = "/ipfs/id/push/1.0.0"

Jeromy's avatar
Jeromy committed
31
// LibP2PVersion holds the current protocol version for a client running this code
32
// TODO(jbenet): fix the versioning mess.
Jeromy's avatar
Jeromy committed
33
const LibP2PVersion = "ipfs/0.1.0"
Jeromy's avatar
Jeromy committed
34
35

var ClientVersion = "go-libp2p/3.3.4"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

// IDService is a structure that implements ProtocolIdentify.
// It is a trivial service that gives the other peer some
// useful information about the local peer. A sort of hello.
//
// The IDService sends:
//  * Our IPFS Protocol Version
//  * Our IPFS Agent Version
//  * Our public Listen Addresses
type IDService struct {
	Host host.Host

	// connections undergoing identification
	// for wait purposes
	currid map[inet.Conn]chan struct{}
	currmu sync.RWMutex
52

Steven Allen's avatar
Steven Allen committed
53
54
	addrMu sync.Mutex

55
56
	// our own observed addresses.
	// TODO: instead of expiring, remove these when we disconnect
57
	observedAddrs ObservedAddrSet
58
59
60

	// NAT status
	natStatus pb.Identify_NATStatus
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61
62
}

63
64
// NewIDService constructs a new *IDService and activates it by
// attaching its stream handler to the given host.Host.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65
66
67
68
69
func NewIDService(h host.Host) *IDService {
	s := &IDService{
		Host:   h,
		currid: make(map[inet.Conn]chan struct{}),
	}
Steven Allen's avatar
Steven Allen committed
70
	h.SetStreamHandler(ID, s.requestHandler)
71
	h.SetStreamHandler(IDPush, s.pushHandler)
72
	h.Network().Notify((*netNotifiee)(s))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73
74
75
	return s
}

76
77
// OwnObservedAddrs returns the addresses peers have reported we've dialed from
func (ids *IDService) OwnObservedAddrs() []ma.Multiaddr {
78
	return ids.observedAddrs.Addrs()
79
80
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
81
82
83
84
85
86
87
88
func (ids *IDService) IdentifyConn(c inet.Conn) {
	ids.currmu.Lock()
	if wait, found := ids.currid[c]; found {
		ids.currmu.Unlock()
		log.Debugf("IdentifyConn called twice on: %s", c)
		<-wait // already identifying it. wait for it.
		return
	}
89
90
	ch := make(chan struct{})
	ids.currid[c] = ch
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91
92
	ids.currmu.Unlock()

93
94
95
96
97
98
	defer func() {
		close(ch)
		ids.currmu.Lock()
		delete(ids.currid, c)
		ids.currmu.Unlock()
	}()
99

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
100
101
	s, err := c.NewStream()
	if err != nil {
Jeromy's avatar
Jeromy committed
102
		log.Debugf("error opening initial stream for %s: %s", ID, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103
		log.Event(context.TODO(), "IdentifyOpenFailed", c.RemotePeer())
Jeromy's avatar
Jeromy committed
104
105
		c.Close()
		return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106
107
	}

108
109
	s.SetProtocol(ID)

110
111
	// ok give the response to our handler.
	if err := msmux.SelectProtoOrFail(ID, s); err != nil {
112
		log.Event(context.TODO(), "IdentifyOpenFailed", c.RemotePeer(), logging.Metadata{"error": err})
Steven Allen's avatar
Steven Allen committed
113
		s.Reset()
114
115
116
		return
	}

Steven Allen's avatar
Steven Allen committed
117
	ids.responseHandler(s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118
119
}

Steven Allen's avatar
Steven Allen committed
120
121
func (ids *IDService) requestHandler(s inet.Stream) {
	defer inet.FullClose(s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
122
123
124
125
126
127
128
129
130
131
132
	c := s.Conn()

	w := ggio.NewDelimitedWriter(s)
	mes := pb.Identify{}
	ids.populateMessage(&mes, s.Conn())
	w.WriteMsg(&mes)

	log.Debugf("%s sent message to %s %s", ID,
		c.RemotePeer(), c.RemoteMultiaddr())
}

Steven Allen's avatar
Steven Allen committed
133
func (ids *IDService) responseHandler(s inet.Stream) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134
135
136
137
138
	c := s.Conn()

	r := ggio.NewDelimitedReader(s, 2048)
	mes := pb.Identify{}
	if err := r.ReadMsg(&mes); err != nil {
139
		log.Warning("error reading identify message: ", err)
140
		s.Reset()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141
142
143
144
145
		return
	}
	ids.consumeMessage(&mes, c)
	log.Debugf("%s received message from %s %s", ID,
		c.RemotePeer(), c.RemoteMultiaddr())
146
147

	go inet.FullClose(s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148
149
}

150
151
152
153
154
155
func (ids *IDService) pushHandler(s inet.Stream) {
	ids.responseHandler(s)
}

func (ids *IDService) Push() {
	for _, p := range ids.Host.Network().Peers() {
vyzo's avatar
vyzo committed
156
157
158
159
160
161
162
163
164
165
166
		go func(p peer.ID) {
			ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
			defer cancel()
			s, err := ids.Host.NewStream(ctx, p, IDPush)
			if err != nil {
				log.Debugf("error opening push stream: %s", err.Error())
				return
			}

			ids.requestHandler(s)
		}(p)
167
168
169
	}
}

170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
func (ids *IDService) SetNatStatus(status autonat.NATStatus) {
	switch status {
	case autonat.NATStatusPrivate:
		ids.natStatus = pb.Identify_NATStatusPrivate
	case autonat.NATStatusPublic:
		ids.natStatus = pb.Identify_NATStatusPublic
	default:
		ids.natStatus = pb.Identify_NATStatusUnknown
	}
}

func (ids *IDService) GetNatStatus() pb.Identify_NATStatus {
	return ids.natStatus
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185
186
187
188
189
190
191
192
193
194
195
196
197
func (ids *IDService) populateMessage(mes *pb.Identify, c inet.Conn) {

	// set protocols this node is currently handling
	protos := ids.Host.Mux().Protocols()
	mes.Protocols = make([]string, len(protos))
	for i, p := range protos {
		mes.Protocols[i] = string(p)
	}

	// observed address so other side is informed of their
	// "public" address, at least in relation to us.
	mes.ObservedAddr = c.RemoteMultiaddr().Bytes()

198
199
200
201
202
	// set listen addrs, get our latest addrs from Host.
	laddrs := ids.Host.Addrs()
	mes.ListenAddrs = make([][]byte, len(laddrs))
	for i, addr := range laddrs {
		mes.ListenAddrs[i] = addr.Bytes()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203
	}
204
	log.Debugf("%s sent listen addrs to %s: %s", c.LocalPeer(), c.RemotePeer(), laddrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205

206
	// set our public key
jbenet's avatar
jbenet committed
207
208
209
210
211
212
213
214
215
216
217
	ownKey := ids.Host.Peerstore().PubKey(ids.Host.ID())
	if ownKey == nil {
		log.Errorf("did not have own public key in Peerstore")
	} else {
		if kb, err := ownKey.Bytes(); err != nil {
			log.Errorf("failed to convert key to bytes")
		} else {
			mes.PublicKey = kb
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
218
	// set protocol versions
Jeromy's avatar
Jeromy committed
219
	pv := LibP2PVersion
220
221
222
	av := ClientVersion
	mes.ProtocolVersion = &pv
	mes.AgentVersion = &av
223
224
225

	// set if behind NAT when possible
	mes.NatStatus = &ids.natStatus
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
226
227
228
229
230
231
}

func (ids *IDService) consumeMessage(mes *pb.Identify, c inet.Conn) {
	p := c.RemotePeer()

	// mes.Protocols
232
	ids.Host.Peerstore().SetProtocols(p, mes.Protocols...)
233

234
235
	ids.Host.Peerstore().Put(p, "natStatus", mes.GetNatStatus())

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
236
	// mes.ObservedAddr
237
	ids.consumeObservedAddress(mes.GetObservedAddr(), c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
238
239
240
241
242
243
244

	// mes.ListenAddrs
	laddrs := mes.GetListenAddrs()
	lmaddrs := make([]ma.Multiaddr, 0, len(laddrs))
	for _, addr := range laddrs {
		maddr, err := ma.NewMultiaddrBytes(addr)
		if err != nil {
245
			log.Debugf("%s failed to parse multiaddr from %s %s", ID,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246
247
248
249
250
251
				p, c.RemoteMultiaddr())
			continue
		}
		lmaddrs = append(lmaddrs, maddr)
	}

252
253
254
255
256
	// if the address reported by the connection roughly matches their annoucned
	// listener addresses, its likely to be an external NAT address
	if HasConsistentTransport(c.RemoteMultiaddr(), lmaddrs) {
		lmaddrs = append(lmaddrs, c.RemoteMultiaddr())
	}
257

Steven Allen's avatar
Steven Allen committed
258
259
260
261
262
263
264
265
266
267
268
	// Extend the TTLs on the known (probably) good addresses.
	// Taking the lock ensures that we don't concurrently process a disconnect.
	ids.addrMu.Lock()
	switch ids.Host.Network().Connectedness(p) {
	case inet.Connected:
		ids.Host.Peerstore().AddAddrs(p, lmaddrs, pstore.ConnectedAddrTTL)
	default:
		ids.Host.Peerstore().AddAddrs(p, lmaddrs, pstore.RecentlyConnectedAddrTTL)
	}
	ids.addrMu.Unlock()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
269
270
271
	log.Debugf("%s received listen addrs for %s: %s", c.LocalPeer(), c.RemotePeer(), lmaddrs)

	// get protocol versions
272
273
	pv := mes.GetProtocolVersion()
	av := mes.GetAgentVersion()
274

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
275
276
	ids.Host.Peerstore().Put(p, "ProtocolVersion", pv)
	ids.Host.Peerstore().Put(p, "AgentVersion", av)
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292

	// get the key from the other side. we may not have it (no-auth transport)
	ids.consumeReceivedPubKey(c, mes.PublicKey)
}

func (ids *IDService) consumeReceivedPubKey(c inet.Conn, kb []byte) {
	lp := c.LocalPeer()
	rp := c.RemotePeer()

	if kb == nil {
		log.Debugf("%s did not receive public key for remote peer: %s", lp, rp)
		return
	}

	newKey, err := ic.UnmarshalPublicKey(kb)
	if err != nil {
293
		log.Warningf("%s cannot unmarshal key from remote peer: %s, %s", lp, rp, err)
294
295
296
297
298
299
300
301
302
		return
	}

	// verify key matches peer.ID
	np, err := peer.IDFromPublicKey(newKey)
	if err != nil {
		log.Debugf("%s cannot get peer.ID from key of remote peer: %s, %s", lp, rp, err)
		return
	}
303

304
	if np != rp {
305
306
307
308
309
310
311
312
313
314
315
316
317
		// if the newKey's peer.ID does not match known peer.ID...

		if rp == "" && np != "" {
			// if local peerid is empty, then use the new, sent key.
			err := ids.Host.Peerstore().AddPubKey(rp, newKey)
			if err != nil {
				log.Debugf("%s could not add key for %s to peerstore: %s", lp, rp, err)
			}

		} else {
			// we have a local peer.ID and it does not match the sent key... error.
			log.Errorf("%s received key for remote peer %s mismatch: %s", lp, rp, np)
		}
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
		return
	}

	currKey := ids.Host.Peerstore().PubKey(rp)
	if currKey == nil {
		// no key? no auth transport. set this one.
		err := ids.Host.Peerstore().AddPubKey(rp, newKey)
		if err != nil {
			log.Debugf("%s could not add key for %s to peerstore: %s", lp, rp, err)
		}
		return
	}

	// ok, we have a local key, we should verify they match.
	if currKey.Equals(newKey) {
		return // ok great. we're done.
	}

	// weird, got a different key... but the different key MATCHES the peer.ID.
	// this odd. let's log error and investigate. this should basically never happen
	// and it means we have something funky going on and possibly a bug.
	log.Errorf("%s identify got a different key for: %s", lp, rp)

	// okay... does ours NOT match the remote peer.ID?
	cp, err := peer.IDFromPublicKey(currKey)
	if err != nil {
		log.Errorf("%s cannot get peer.ID from local key of remote peer: %s, %s", lp, rp, err)
		return
	}
	if cp != rp {
		log.Errorf("%s local key for remote peer %s yields different peer.ID: %s", lp, rp, cp)
		return
	}

	// okay... curr key DOES NOT match new key. both match peer.ID. wat?
	log.Errorf("%s local key and received key for %s do not match, but match peer.ID", lp, rp)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
354
355
}

356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// HasConsistentTransport returns true if the address 'a' shares a
// protocol set with any address in the green set. This is used
// to check if a given address might be one of the addresses a peer is
// listening on.
func HasConsistentTransport(a ma.Multiaddr, green []ma.Multiaddr) bool {
	protosMatch := func(a, b []ma.Protocol) bool {
		if len(a) != len(b) {
			return false
		}

		for i, p := range a {
			if b[i].Code != p.Code {
				return false
			}
		}
		return true
	}

	protos := a.Protocols()

	for _, ga := range green {
		if protosMatch(protos, ga.Protocols()) {
			return true
		}
	}

	return false
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// IdentifyWait returns a channel which will be closed once
// "ProtocolIdentify" (handshake3) finishes on given conn.
// This happens async so the connection can start to be used
// even if handshake3 knowledge is not necesary.
// Users **MUST** call IdentifyWait _after_ IdentifyConn
func (ids *IDService) IdentifyWait(c inet.Conn) <-chan struct{} {
	ids.currmu.Lock()
	ch, found := ids.currid[c]
	ids.currmu.Unlock()
	if found {
		return ch
	}

	// if not found, it means we are already done identifying it, or
	// haven't even started. either way, return a new channel closed.
	ch = make(chan struct{})
	close(ch)
	return ch
}
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433

func (ids *IDService) consumeObservedAddress(observed []byte, c inet.Conn) {
	if observed == nil {
		return
	}

	maddr, err := ma.NewMultiaddrBytes(observed)
	if err != nil {
		log.Debugf("error parsing received observed addr for %s: %s", c, err)
		return
	}

	// we should only use ObservedAddr when our connection's LocalAddr is one
	// of our ListenAddrs. If we Dial out using an ephemeral addr, knowing that
	// address's external mapping is not very useful because the port will not be
	// the same as the listen addr.
	ifaceaddrs, err := ids.Host.Network().InterfaceListenAddresses()
	if err != nil {
		log.Infof("failed to get interface listen addrs", err)
		return
	}

	log.Debugf("identify identifying observed multiaddr: %s %s", c.LocalMultiaddr(), ifaceaddrs)
	if !addrInAddrs(c.LocalMultiaddr(), ifaceaddrs) {
		// not in our list
		return
	}

	// ok! we have the observed version of one of our ListenAddresses!
	log.Debugf("added own observed listen addr: %s --> %s", c.LocalMultiaddr(), maddr)
434
435
	ids.observedAddrs.Add(maddr, c.LocalMultiaddr(), c.RemoteMultiaddr(),
		c.Stat().Direction)
436
437
438
}

func addrInAddrs(a ma.Multiaddr, as []ma.Multiaddr) bool {
439
440
441
442
443
444
445
446
447
448
449
450
	// allow wildcard addresses
	if ip, err := a.ValueForProtocol(ma.P_IP4); err == nil {
		if parsed := net.ParseIP(ip); parsed != nil && parsed.IsUnspecified() {
			return true
		}
	}
	if ip, err := a.ValueForProtocol(ma.P_IP6); err == nil {
		if parsed := net.ParseIP(ip); parsed != nil && parsed.IsUnspecified() {
			return true
		}
	}

451
452
453
454
455
456
457
	for _, b := range as {
		if a.Equal(b) {
			return true
		}
	}
	return false
}
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473

// netNotifiee defines methods to be used with the IpfsDHT
type netNotifiee IDService

func (nn *netNotifiee) IDService() *IDService {
	return (*IDService)(nn)
}

func (nn *netNotifiee) Connected(n inet.Network, v inet.Conn) {
	// TODO: deprecate the setConnHandler hook, and kick off
	// identification here.
}

func (nn *netNotifiee) Disconnected(n inet.Network, v inet.Conn) {
	// undo the setting of addresses to peer.ConnectedAddrTTL we did
	ids := nn.IDService()
Steven Allen's avatar
Steven Allen committed
474
475
476
477
478
479
480
481
	ids.addrMu.Lock()
	defer ids.addrMu.Unlock()

	if ids.Host.Network().Connectedness(v.RemotePeer()) != inet.Connected {
		// Last disconnect.
		ps := ids.Host.Peerstore()
		ps.UpdateAddrs(v.RemotePeer(), pstore.ConnectedAddrTTL, pstore.RecentlyConnectedAddrTTL)
	}
482
483
484
485
486
487
}

func (nn *netNotifiee) OpenedStream(n inet.Network, v inet.Stream) {}
func (nn *netNotifiee) ClosedStream(n inet.Network, v inet.Stream) {}
func (nn *netNotifiee) Listen(n inet.Network, a ma.Multiaddr)      {}
func (nn *netNotifiee) ListenClose(n inet.Network, a ma.Multiaddr) {}
488
489
490
491
492
493
494
495

func logProtocolMismatchDisconnect(c inet.Conn, protocol, agent string) {
	lm := make(lgbl.DeferredMap)
	lm["remotePeer"] = func() interface{} { return c.RemotePeer().Pretty() }
	lm["remoteAddr"] = func() interface{} { return c.RemoteMultiaddr().String() }
	lm["protocolVersion"] = protocol
	lm["agentVersion"] = agent
	log.Event(context.TODO(), "IdentifyProtocolMismatch", lm)
Jakub Sztandera's avatar
Jakub Sztandera committed
496
	log.Debugf("IdentifyProtocolMismatch %s %s %s (disconnected)", c.RemotePeer(), protocol, agent)
497
}