basic_host.go 14.5 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
2
3
package basichost

import (
4
	"context"
5
	"io"
6
	"time"
7

Jeromy's avatar
Jeromy committed
8
9
	logging "github.com/ipfs/go-log"
	goprocess "github.com/jbenet/goprocess"
Steven Allen's avatar
Steven Allen committed
10
	goprocessctx "github.com/jbenet/goprocess/context"
11
	ifconnmgr "github.com/libp2p/go-libp2p-interface-connmgr"
Jeromy's avatar
Jeromy committed
12
	inet "github.com/libp2p/go-libp2p-net"
Jeromy's avatar
Jeromy committed
13
14
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
Jeromy's avatar
Jeromy committed
15
	protocol "github.com/libp2p/go-libp2p-protocol"
Can ZHANG's avatar
Can ZHANG committed
16
	identify "github.com/libp2p/go-libp2p/p2p/protocol/identify"
vyzo's avatar
vyzo committed
17
	ping "github.com/libp2p/go-libp2p/p2p/protocol/ping"
Jeromy's avatar
Jeromy committed
18
	ma "github.com/multiformats/go-multiaddr"
19
	madns "github.com/multiformats/go-multiaddr-dns"
Jeromy's avatar
Jeromy committed
20
	msmux "github.com/multiformats/go-multistream"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21
22
)

23
var log = logging.Logger("basichost")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24

25
26
27
28
29
30
31
var (
	// DefaultNegotiationTimeout is the default value for HostOpts.NegotiationTimeout.
	DefaultNegotiationTimeout = time.Second * 60

	// DefaultAddrsFactory is the default value for HostOpts.AddrsFactory.
	DefaultAddrsFactory = func(addrs []ma.Multiaddr) []ma.Multiaddr { return addrs }
)
32

33
34
35
36
// AddrsFactory functions can be passed to New in order to override
// addresses returned by Addrs.
type AddrsFactory func([]ma.Multiaddr) []ma.Multiaddr

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37
// Option is a type used to pass in options to the host.
38
39
//
// Deprecated in favor of HostOpts and NewHost.
40
41
type Option int

42
43
44
45
46
47
48
49
// NATPortMap makes the host attempt to open port-mapping in NAT devices
// for all its listeners. Pass in this option in the constructor to
// asynchronously a) find a gateway, b) open port mappings, c) republish
// port mappings periodically. The NATed addresses are included in the
// Host's Addrs() list.
//
// This option is deprecated in favor of HostOpts and NewHost.
const NATPortMap Option = iota
50

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51
52
53
54
55
// BasicHost is the basic implementation of the host.Host interface. This
// particular host implementation:
//  * uses a protocol muxer to mux per-protocol streams
//  * uses an identity service to send + receive node information
//  * uses a nat service to establish NAT port mappings
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56
type BasicHost struct {
57
58
59
	network    inet.Network
	mux        *msmux.MultistreamMuxer
	ids        *identify.IDService
vyzo's avatar
vyzo committed
60
	pings      *ping.PingService
61
62
63
	natmgr     NATManager
	addrs      AddrsFactory
	maResolver *madns.Resolver
64
	cmgr       ifconnmgr.ConnManager
65

66
	negtimeout time.Duration
67

68
	proc goprocess.Process
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
69
70
}

71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// HostOpts holds options that can be passed to NewHost in order to
// customize construction of the *BasicHost.
type HostOpts struct {

	// MultistreamMuxer is essential for the *BasicHost and will use a sensible default value if omitted.
	MultistreamMuxer *msmux.MultistreamMuxer

	// NegotiationTimeout determines the read and write timeouts on streams.
	// If 0 or omitted, it will use DefaultNegotiationTimeout.
	// If below 0, timeouts on streams will be deactivated.
	NegotiationTimeout time.Duration

	// IdentifyService holds an implementation of the /ipfs/id/ protocol.
	// If omitted, a new *identify.IDService will be used.
	IdentifyService *identify.IDService

	// AddrsFactory holds a function which can be used to override or filter the result of Addrs.
	// If omitted, there's no override or filtering, and the results of Addrs and AllAddrs are the same.
	AddrsFactory AddrsFactory

91
92
93
94
	// MultiaddrResolves holds the go-multiaddr-dns.Resolver used for resolving
	// /dns4, /dns6, and /dnsaddr addresses before trying to connect to a peer.
	MultiaddrResolver *madns.Resolver

95
96
	// NATManager takes care of setting NAT port mappings, and discovering external addresses.
	// If omitted, this will simply be disabled.
Steven Allen's avatar
Steven Allen committed
97
	NATManager func(inet.Network) NATManager
Jeromy's avatar
Jeromy committed
98
99

	// ConnManager is a libp2p connection manager
100
	ConnManager ifconnmgr.ConnManager
vyzo's avatar
vyzo committed
101
102
103

	// EnablePing indicates whether to instantiate the ping service
	EnablePing bool
104
105
106
}

// NewHost constructs a new *BasicHost and activates it by attaching its stream and connection handlers to the given inet.Network.
107
func NewHost(ctx context.Context, net inet.Network, opts *HostOpts) (*BasicHost, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
108
	h := &BasicHost{
109
110
111
112
		network:    net,
		mux:        msmux.NewMultistreamMuxer(),
		negtimeout: DefaultNegotiationTimeout,
		addrs:      DefaultAddrsFactory,
113
		maResolver: madns.DefaultResolver,
114
115
	}

Steven Allen's avatar
Steven Allen committed
116
	h.proc = goprocessctx.WithContextAndTeardown(ctx, func() error {
117
118
119
120
121
122
		if h.natmgr != nil {
			h.natmgr.Close()
		}
		return h.Network().Close()
	})

123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
	if opts.MultistreamMuxer != nil {
		h.mux = opts.MultistreamMuxer
	}

	if opts.IdentifyService != nil {
		h.ids = opts.IdentifyService
	} else {
		// we can't set this as a default above because it depends on the *BasicHost.
		h.ids = identify.NewIDService(h)
	}

	if uint64(opts.NegotiationTimeout) != 0 {
		h.negtimeout = opts.NegotiationTimeout
	}

	if opts.AddrsFactory != nil {
		h.addrs = opts.AddrsFactory
	}

	if opts.NATManager != nil {
Steven Allen's avatar
Steven Allen committed
143
		h.natmgr = opts.NATManager(net)
144
145
	}

146
147
148
149
	if opts.MultiaddrResolver != nil {
		h.maResolver = opts.MultiaddrResolver
	}

Jeromy's avatar
Jeromy committed
150
	if opts.ConnManager == nil {
151
		h.cmgr = &ifconnmgr.NullConnMgr{}
Jeromy's avatar
Jeromy committed
152
153
	} else {
		h.cmgr = opts.ConnManager
154
		net.Notify(h.cmgr.Notifee())
Jeromy's avatar
Jeromy committed
155
156
	}

vyzo's avatar
vyzo committed
157
158
159
160
	if opts.EnablePing {
		h.pings = ping.NewPingService(h)
	}

161
162
	net.SetConnHandler(h.newConnHandler)
	net.SetStreamHandler(h.newStreamHandler)
163
	return h, nil
164
}
Jeromy's avatar
Jeromy committed
165

166
// New constructs and sets up a new *BasicHost with given Network and options.
Steven Allen's avatar
Steven Allen committed
167
168
169
170
171
172
// The following options can be passed:
// * NATPortMap
// * AddrsFactory
// * ifconnmgr.ConnManager
// * madns.Resolver
//
173
174
175
// This function is deprecated in favor of NewHost and HostOpts.
func New(net inet.Network, opts ...interface{}) *BasicHost {
	hostopts := &HostOpts{}
176

177
	for _, o := range opts {
Jeromy's avatar
Jeromy committed
178
179
180
181
		switch o := o.(type) {
		case Option:
			switch o {
			case NATPortMap:
Steven Allen's avatar
Steven Allen committed
182
				hostopts.NATManager = NewNATManager
Jeromy's avatar
Jeromy committed
183
			}
184
		case AddrsFactory:
185
			hostopts.AddrsFactory = AddrsFactory(o)
186
		case ifconnmgr.ConnManager:
Jeromy's avatar
Jeromy committed
187
			hostopts.ConnManager = o
188
189
		case *madns.Resolver:
			hostopts.MultiaddrResolver = o
190
191
192
		}
	}

193
	h, err := NewHost(context.Background(), net, hostopts)
194
195
196
197
198
199
200
	if err != nil {
		// this cannot happen with legacy options
		// plus we want to keep the (deprecated) legacy interface unchanged
		panic(err)
	}

	return h
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201
202
203
204
}

// newConnHandler is the remote-opened conn handler for inet.Network
func (h *BasicHost) newConnHandler(c inet.Conn) {
205
206
207
	// Clear protocols on connecting to new peer to avoid issues caused
	// by misremembering protocols between reconnects
	h.Peerstore().SetProtocols(c.RemotePeer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208
209
210
211
	h.ids.IdentifyConn(c)
}

// newStreamHandler is the remote-opened stream handler for inet.Network
Jeromy's avatar
Jeromy committed
212
// TODO: this feels a bit wonky
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213
func (h *BasicHost) newStreamHandler(s inet.Stream) {
214
	before := time.Now()
215

216
217
	if h.negtimeout > 0 {
		if err := s.SetDeadline(time.Now().Add(h.negtimeout)); err != nil {
218
			log.Error("setting stream deadline: ", err)
Steven Allen's avatar
Steven Allen committed
219
			s.Reset()
220
221
222
223
			return
		}
	}

224
	lzc, protoID, handle, err := h.Mux().NegotiateLazy(s)
225
	took := time.Now().Sub(before)
Jeromy's avatar
Jeromy committed
226
	if err != nil {
227
		if err == io.EOF {
228
229
230
231
232
			logf := log.Debugf
			if took > time.Second*10 {
				logf = log.Warningf
			}
			logf("protocol EOF: %s (took %s)", s.Conn().RemotePeer(), took)
233
		} else {
234
			log.Debugf("protocol mux failed: %s (took %s)", err, took)
235
		}
Steven Allen's avatar
Steven Allen committed
236
		s.Reset()
Jeromy's avatar
Jeromy committed
237
238
		return
	}
239

240
241
242
243
244
	s = &streamWrapper{
		Stream: s,
		rw:     lzc,
	}

245
	if h.negtimeout > 0 {
246
247
		if err := s.SetDeadline(time.Time{}); err != nil {
			log.Error("resetting stream deadline: ", err)
Steven Allen's avatar
Steven Allen committed
248
			s.Reset()
249
250
251
252
			return
		}
	}

253
	s.SetProtocol(protocol.ID(protoID))
254
	log.Debugf("protocol negotiation took %s", took)
Jeromy's avatar
Jeromy committed
255

256
	go handle(protoID, s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
257
258
259
260
261
262
263
264
}

// ID returns the (local) peer.ID associated with this Host
func (h *BasicHost) ID() peer.ID {
	return h.Network().LocalPeer()
}

// Peerstore returns the Host's repository of Peer Addresses and Keys.
Jeromy's avatar
Jeromy committed
265
func (h *BasicHost) Peerstore() pstore.Peerstore {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
266
267
268
	return h.Network().Peerstore()
}

269
// Network returns the Network interface of the Host
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
270
271
272
273
274
func (h *BasicHost) Network() inet.Network {
	return h.network
}

// Mux returns the Mux multiplexing incoming streams to protocol handlers
Jeromy's avatar
Jeromy committed
275
func (h *BasicHost) Mux() *msmux.MultistreamMuxer {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
276
	return h.mux
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
277
278
}

279
// IDService returns
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
280
281
282
283
284
285
286
287
288
func (h *BasicHost) IDService() *identify.IDService {
	return h.ids
}

// SetStreamHandler sets the protocol handler on the Host's Mux.
// This is equivalent to:
//   host.Mux().SetHandler(proto, handler)
// (Threadsafe)
func (h *BasicHost) SetStreamHandler(pid protocol.ID, handler inet.StreamHandler) {
289
290
	h.Mux().AddHandler(string(pid), func(p string, rwc io.ReadWriteCloser) error {
		is := rwc.(inet.Stream)
291
		is.SetProtocol(protocol.ID(p))
292
		handler(is)
Jeromy's avatar
Jeromy committed
293
294
		return nil
	})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
295
296
}

297
298
299
300
301
// SetStreamHandlerMatch sets the protocol handler on the Host's Mux
// using a matching function to do protocol comparisons
func (h *BasicHost) SetStreamHandlerMatch(pid protocol.ID, m func(string) bool, handler inet.StreamHandler) {
	h.Mux().AddHandlerWithFunc(string(pid), m, func(p string, rwc io.ReadWriteCloser) error {
		is := rwc.(inet.Stream)
302
		is.SetProtocol(protocol.ID(p))
303
304
305
306
307
		handler(is)
		return nil
	})
}

308
// RemoveStreamHandler returns ..
Jeromy's avatar
Jeromy committed
309
func (h *BasicHost) RemoveStreamHandler(pid protocol.ID) {
Jeromy's avatar
Jeromy committed
310
	h.Mux().RemoveHandler(string(pid))
Jeromy's avatar
Jeromy committed
311
312
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
313
314
315
316
// NewStream opens a new stream to given peer p, and writes a p2p/protocol
// header with given protocol.ID. If there is no connection to p, attempts
// to create one. If ProtocolID is "", writes no header.
// (Threadsafe)
317
func (h *BasicHost) NewStream(ctx context.Context, p peer.ID, pids ...protocol.ID) (inet.Stream, error) {
318
319
320
321
322
	pref, err := h.preferredProtocol(p, pids)
	if err != nil {
		return nil, err
	}

323
324
325
326
	if pref != "" {
		return h.newStream(ctx, p, pref)
	}

327
	var protoStrs []string
328
	for _, pid := range pids {
329
330
		protoStrs = append(protoStrs, string(pid))
	}
331

332
333
334
335
	s, err := h.Network().NewStream(ctx, p)
	if err != nil {
		return nil, err
	}
336

337
338
	selected, err := msmux.SelectOneOf(protoStrs, s)
	if err != nil {
Steven Allen's avatar
Steven Allen committed
339
		s.Reset()
340
		return nil, err
341
	}
342
343
	selpid := protocol.ID(selected)
	s.SetProtocol(selpid)
344
	h.Peerstore().AddProtocols(p, selected)
345

Jeromy's avatar
Jeromy committed
346
	return s, nil
347
348
}

349
350
351
352
func pidsToStrings(pids []protocol.ID) []string {
	out := make([]string, len(pids))
	for i, p := range pids {
		out[i] = string(p)
353
	}
354
	return out
355
356
}

357
358
359
360
361
func (h *BasicHost) preferredProtocol(p peer.ID, pids []protocol.ID) (protocol.ID, error) {
	pidstrs := pidsToStrings(pids)
	supported, err := h.Peerstore().SupportsProtocols(p, pidstrs...)
	if err != nil {
		return "", err
362
363
	}

364
365
366
367
368
	var out protocol.ID
	if len(supported) > 0 {
		out = protocol.ID(supported[0])
	}
	return out, nil
369
370
371
}

func (h *BasicHost) newStream(ctx context.Context, p peer.ID, pid protocol.ID) (inet.Stream, error) {
372
	s, err := h.Network().NewStream(ctx, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
373
374
375
376
	if err != nil {
		return nil, err
	}

377
	s.SetProtocol(pid)
378

Jeromy's avatar
Jeromy committed
379
	lzcon := msmux.NewMSSelect(s, string(pid))
Jeromy's avatar
Jeromy committed
380
	return &streamWrapper{
Jeromy's avatar
Jeromy committed
381
		Stream: s,
Jeromy's avatar
Jeromy committed
382
383
		rw:     lzcon,
	}, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
384
385
386
}

// Connect ensures there is a connection between this host and the peer with
387
388
389
390
// given peer.ID. If there is not an active connection, Connect will issue a
// h.Network.Dial, and block until a connection is open, or an error is returned.
// Connect will absorb the addresses in pi into its internal peerstore.
// It will also resolve any /dns4, /dns6, and /dnsaddr addresses.
Jeromy's avatar
Jeromy committed
391
func (h *BasicHost) Connect(ctx context.Context, pi pstore.PeerInfo) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
392
	// absorb addresses into peerstore
Jeromy's avatar
Jeromy committed
393
	h.Peerstore().AddAddrs(pi.ID, pi.Addrs, pstore.TempAddrTTL)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
394

395
	if h.Network().Connectedness(pi.ID) == inet.Connected {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
396
397
398
		return nil
	}

399
400
401
402
403
404
	resolved, err := h.resolveAddrs(ctx, h.Peerstore().PeerInfo(pi.ID))
	if err != nil {
		return err
	}
	h.Peerstore().AddAddrs(pi.ID, resolved, pstore.TempAddrTTL)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
405
406
407
	return h.dialPeer(ctx, pi.ID)
}

408
409
410
411
412
413
414
415
416
417
func (h *BasicHost) resolveAddrs(ctx context.Context, pi pstore.PeerInfo) ([]ma.Multiaddr, error) {
	proto := ma.ProtocolWithCode(ma.P_IPFS).Name
	p2paddr, err := ma.NewMultiaddr("/" + proto + "/" + pi.ID.Pretty())
	if err != nil {
		return nil, err
	}

	var addrs []ma.Multiaddr
	for _, addr := range pi.Addrs {
		addrs = append(addrs, addr)
418
419
420
		if !madns.Matches(addr) {
			continue
		}
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438

		reqaddr := addr.Encapsulate(p2paddr)
		resaddrs, err := h.maResolver.Resolve(ctx, reqaddr)
		if err != nil {
			log.Infof("error resolving %s: %s", reqaddr, err)
		}
		for _, res := range resaddrs {
			pi, err := pstore.InfoFromP2pAddr(res)
			if err != nil {
				log.Infof("error parsing %s: %s", res, err)
			}
			addrs = append(addrs, pi.Addrs...)
		}
	}

	return addrs, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
439
440
441
// dialPeer opens a connection to peer, and makes sure to identify
// the connection once it has been opened.
func (h *BasicHost) dialPeer(ctx context.Context, p peer.ID) error {
442
	log.Debugf("host %s dialing %s", h.ID(), p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
443
444
445
446
447
	c, err := h.Network().DialPeer(ctx, p)
	if err != nil {
		return err
	}

448
449
450
451
	// Clear protocols on connecting to new peer to avoid issues caused
	// by misremembering protocols between reconnects
	h.Peerstore().SetProtocols(p)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
452
453
454
455
456
457
458
459
460
461
462
463
464
465
	// identify the connection before returning.
	done := make(chan struct{})
	go func() {
		h.ids.IdentifyConn(c)
		close(done)
	}()

	// respect don contexteone
	select {
	case <-done:
	case <-ctx.Done():
		return ctx.Err()
	}

Jeromy's avatar
Jeromy committed
466
	log.Debugf("host %s finished dialing %s", h.ID(), p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
467
468
469
	return nil
}

470
func (h *BasicHost) ConnManager() ifconnmgr.ConnManager {
Jeromy's avatar
Jeromy committed
471
472
473
	return h.cmgr
}

474
475
// Addrs returns listening addresses that are safe to announce to the network.
// The output is the same as AllAddrs, but processed by AddrsFactory.
476
func (h *BasicHost) Addrs() []ma.Multiaddr {
477
478
479
	return h.addrs(h.AllAddrs())
}

480
481
482
483
484
// mergeAddrs merges input address lists, leave only unique addresses
func mergeAddrs(addrLists ...[]ma.Multiaddr) (uniqueAddrs []ma.Multiaddr) {
	exists := make(map[string]bool)
	for _, addrList := range addrLists {
		for _, addr := range addrList {
Can ZHANG's avatar
Can ZHANG committed
485
486
			k := string(addr.Bytes())
			if exists[k] {
487
488
				continue
			}
Can ZHANG's avatar
Can ZHANG committed
489
			exists[k] = true
490
491
492
493
494
495
			uniqueAddrs = append(uniqueAddrs, addr)
		}
	}
	return uniqueAddrs
}

496
497
498
// AllAddrs returns all the addresses of BasicHost at this moment in time.
// It's ok to not include addresses if they're not available to be used now.
func (h *BasicHost) AllAddrs() []ma.Multiaddr {
499
	listenAddrs, err := h.Network().InterfaceListenAddresses()
500
501
502
	if err != nil {
		log.Debug("error retrieving network interface addrs")
	}
503
504
505
506
	var observedAddrs []ma.Multiaddr
	if h.ids != nil {
		// peer observed addresses
		observedAddrs = h.ids.OwnObservedAddrs()
507
	}
508
509
510
511
512
	var natAddrs []ma.Multiaddr
	// natmgr is nil if we do not use nat option;
	// h.natmgr.NAT() is nil if not ready, or no nat is available.
	if h.natmgr != nil && h.natmgr.NAT() != nil {
		natAddrs = h.natmgr.NAT().ExternalAddrs()
513
514
	}

515
	return mergeAddrs(listenAddrs, observedAddrs, natAddrs)
516
517
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
518
519
// Close shuts down the Host's services (network, etc).
func (h *BasicHost) Close() error {
520
	return h.proc.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
521
}
Jeromy's avatar
Jeromy committed
522

Jeromy's avatar
Jeromy committed
523
524
525
526
527
528
529
530
531
532
533
534
type streamWrapper struct {
	inet.Stream
	rw io.ReadWriter
}

func (s *streamWrapper) Read(b []byte) (int, error) {
	return s.rw.Read(b)
}

func (s *streamWrapper) Write(b []byte) (int, error) {
	return s.rw.Write(b)
}