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

import (
4
	"strings"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
6
	"sync"

Jeromy's avatar
Jeromy committed
7
8
9
10
11
	ma "gx/ipfs/QmR3JkmZBKYXgNMNsNZawm914455Qof3PEopwuVSeXG7aV/go-multiaddr"
	msmux "gx/ipfs/QmUeEcYJrzAEKdQXjzTxCgNZgc9sRuwharsvzzm5Gd2oGB/go-multistream"
	ggio "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/io"
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
	semver "gx/ipfs/QmcrrEpx3VMUbrbgVroH3YiYyUS5c4YAykzyPJWKspUYLa/go-semver/semver"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13
	host "github.com/ipfs/go-libp2p/p2p/host"
Jeromy's avatar
Jeromy committed
14
	mstream "github.com/ipfs/go-libp2p/p2p/metrics/stream"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
16
17
	inet "github.com/ipfs/go-libp2p/p2p/net"
	peer "github.com/ipfs/go-libp2p/p2p/peer"
	pb "github.com/ipfs/go-libp2p/p2p/protocol/identify/pb"
Jeromy's avatar
Jeromy committed
18

Jeromy's avatar
Jeromy committed
19
	lgbl "github.com/ipfs/go-libp2p/loggables"
Jeromy's avatar
Jeromy committed
20
	logging "gx/ipfs/Qmazh5oNUVsDZTs2g59rq8aYQqwpss8tcUWQzor5sCCEuH/go-log"
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/identify"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27

Jeromy's avatar
Jeromy committed
28
// LibP2PVersion holds the current protocol version for a client running this code
29
// TODO(jbenet): fix the versioning mess.
Jeromy's avatar
Jeromy committed
30
31
const LibP2PVersion = "ipfs/0.1.0"
const ClientVersion = "go-libp2p/0.1.0"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

// 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
48
49
50

	// our own observed addresses.
	// TODO: instead of expiring, remove these when we disconnect
51
	observedAddrs ObservedAddrSet
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52
53
54
55
56
57
58
59
60
61
62
}

func NewIDService(h host.Host) *IDService {
	s := &IDService{
		Host:   h,
		currid: make(map[inet.Conn]chan struct{}),
	}
	h.SetStreamHandler(ID, s.RequestHandler)
	return s
}

63
64
// OwnObservedAddrs returns the addresses peers have reported we've dialed from
func (ids *IDService) OwnObservedAddrs() []ma.Multiaddr {
65
	return ids.observedAddrs.Addrs()
66
67
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68
69
70
71
72
73
74
75
76
77
78
79
80
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
	}
	ids.currid[c] = make(chan struct{})
	ids.currmu.Unlock()

	s, err := c.NewStream()
	if err != nil {
Jeromy's avatar
Jeromy committed
81
		log.Debugf("error opening initial stream for %s: %s", ID, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82
		log.Event(context.TODO(), "IdentifyOpenFailed", c.RemotePeer())
Jeromy's avatar
Jeromy committed
83
84
		c.Close()
		return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
85
	} else {
Jeromy's avatar
Jeromy committed
86
87
		bwc := ids.Host.GetBandwidthReporter()
		s = mstream.WrapStream(s, ID, bwc)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88
89

		// ok give the response to our handler.
Jeromy's avatar
Jeromy committed
90
		if err := msmux.SelectProtoOrFail(ID, s); err != nil {
91
			log.Debugf("error writing stream header for %s", ID)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
92
			log.Event(context.TODO(), "IdentifyOpenFailed", c.RemotePeer())
Jeromy's avatar
Jeromy committed
93
94
			s.Close()
			return
Jeromy's avatar
Jeromy committed
95
96
		} else {
			ids.ResponseHandler(s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
98
99
100
101
102
103
104
105
		}
	}

	ids.currmu.Lock()
	ch, found := ids.currid[c]
	delete(ids.currid, c)
	ids.currmu.Unlock()

	if !found {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106
		log.Debugf("IdentifyConn failed to find channel (programmer error) for %s", c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107
108
109
110
111
112
113
114
115
116
		return
	}

	close(ch) // release everyone waiting.
}

func (ids *IDService) RequestHandler(s inet.Stream) {
	defer s.Close()
	c := s.Conn()

Jeromy's avatar
Jeromy committed
117
118
119
	bwc := ids.Host.GetBandwidthReporter()
	s = mstream.WrapStream(s, ID, bwc)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
	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())
}

func (ids *IDService) ResponseHandler(s inet.Stream) {
	defer s.Close()
	c := s.Conn()

	r := ggio.NewDelimitedReader(s, 2048)
	mes := pb.Identify{}
	if err := r.ReadMsg(&mes); err != nil {
		return
	}
	ids.consumeMessage(&mes, c)

	log.Debugf("%s received message from %s %s", ID,
		c.RemotePeer(), c.RemoteMultiaddr())
}

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()

157
158
159
160
161
	// 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
162
	}
163
	log.Debugf("%s sent listen addrs to %s: %s", c.LocalPeer(), c.RemotePeer(), laddrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164
165

	// set protocol versions
Jeromy's avatar
Jeromy committed
166
	pv := LibP2PVersion
167
168
169
	av := ClientVersion
	mes.ProtocolVersion = &pv
	mes.AgentVersion = &av
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170
171
172
173
174
175
}

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

	// mes.Protocols
176

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
177
	// mes.ObservedAddr
178
	ids.consumeObservedAddress(mes.GetObservedAddr(), c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179
180
181
182
183
184
185

	// mes.ListenAddrs
	laddrs := mes.GetListenAddrs()
	lmaddrs := make([]ma.Multiaddr, 0, len(laddrs))
	for _, addr := range laddrs {
		maddr, err := ma.NewMultiaddrBytes(addr)
		if err != nil {
186
			log.Debugf("%s failed to parse multiaddr from %s %s", ID,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
187
188
189
190
191
192
				p, c.RemoteMultiaddr())
			continue
		}
		lmaddrs = append(lmaddrs, maddr)
	}

193
194
	// update our peerstore with the addresses. here, we SET the addresses, clearing old ones.
	// We are receiving from the peer itself. this is current address ground truth.
195
	ids.Host.Peerstore().SetAddrs(p, lmaddrs, peer.ConnectedAddrTTL)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
196
197
198
	log.Debugf("%s received listen addrs for %s: %s", c.LocalPeer(), c.RemotePeer(), lmaddrs)

	// get protocol versions
199
200
	pv := mes.GetProtocolVersion()
	av := mes.GetAgentVersion()
201
202
203
204

	// version check. if we shouldn't talk, bail.
	// TODO: at this point, we've already exchanged information.
	// move this into a first handshake before the connection can open streams.
Jeromy's avatar
Jeromy committed
205
	if !protocolVersionsAreCompatible(pv, LibP2PVersion) {
206
		logProtocolMismatchDisconnect(c, pv, av)
207
208
209
210
		c.Close()
		return
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
	ids.Host.Peerstore().Put(p, "ProtocolVersion", pv)
	ids.Host.Peerstore().Put(p, "AgentVersion", av)
}

// 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
}
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

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)
264
	ids.observedAddrs.Add(maddr, c.RemoteMultiaddr())
265
266
267
268
269
270
271
272
273
274
}

func addrInAddrs(a ma.Multiaddr, as []ma.Multiaddr) bool {
	for _, b := range as {
		if a.Equal(b) {
			return true
		}
	}
	return false
}
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
// protocolVersionsAreCompatible checks that the two implementations
// can talk to each other. It will use semver, but for now while
// we're in tight development, we will return false for minor version
// changes too.
func protocolVersionsAreCompatible(v1, v2 string) bool {
	if strings.HasPrefix(v1, "ipfs/") {
		v1 = v1[5:]
	}
	if strings.HasPrefix(v2, "ipfs/") {
		v2 = v2[5:]
	}

	v1s, err := semver.NewVersion(v1)
	if err != nil {
		return false
	}

	v2s, err := semver.NewVersion(v2)
	if err != nil {
		return false
	}

	return v1s.Major == v2s.Major && v1s.Minor == v2s.Minor
}

301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// 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()
	ps := ids.Host.Peerstore()
	addrs := ps.Addrs(v.RemotePeer())
	ps.SetAddrs(v.RemotePeer(), addrs, peer.RecentlyConnectedAddrTTL)
}

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) {}
325
326
327
328
329
330
331
332
333
334

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)
	log.Debug("IdentifyProtocolMismatch %s %s %s (disconnected)", c.RemotePeer(), protocol, agent)
}