basic_host.go 13.4 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
	identify "github.com/libp2p/go-libp2p/p2p/protocol/identify"

Jeromy's avatar
Jeromy committed
10
11
	logging "github.com/ipfs/go-log"
	goprocess "github.com/jbenet/goprocess"
12
	circuit "github.com/libp2p/go-libp2p-circuit"
Jeromy's avatar
Jeromy committed
13
	connmgr "github.com/libp2p/go-libp2p-connmgr"
Jeromy's avatar
Jeromy committed
14
15
16
	metrics "github.com/libp2p/go-libp2p-metrics"
	mstream "github.com/libp2p/go-libp2p-metrics/stream"
	inet "github.com/libp2p/go-libp2p-net"
Jeromy's avatar
Jeromy committed
17
18
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
Jeromy's avatar
Jeromy committed
19
	protocol "github.com/libp2p/go-libp2p-protocol"
Jeromy's avatar
Jeromy committed
20
	ma "github.com/multiformats/go-multiaddr"
Jeromy's avatar
Jeromy committed
21
	msmux "github.com/multiformats/go-multistream"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22
23
)

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

26
27
28
29
30
31
32
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 }
)
33

34
35
36
37
// 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
38
// Option is a type used to pass in options to the host.
39
40
//
// Deprecated in favor of HostOpts and NewHost.
41
42
type Option int

43
44
45
46
47
48
49
50
// 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
51

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52
53
54
55
56
// 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
57
58
type BasicHost struct {
	network inet.Network
Jeromy's avatar
Jeromy committed
59
	mux     *msmux.MultistreamMuxer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60
	ids     *identify.IDService
61
	natmgr  NATManager
62
	addrs   AddrsFactory
Jeromy's avatar
Jeromy committed
63
	cmgr    connmgr.ConnManager
64

65
	negtimeout time.Duration
66

67
	proc goprocess.Process
Jeromy's avatar
Jeromy committed
68
69

	bwc metrics.Reporter
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70
71
}

72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// 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

	// NATManager takes care of setting NAT port mappings, and discovering external addresses.
	// If omitted, this will simply be disabled.
94
	NATManager NATManager
95
96
97

	//
	BandwidthReporter metrics.Reporter
Jeromy's avatar
Jeromy committed
98
99
100

	// ConnManager is a libp2p connection manager
	ConnManager connmgr.ConnManager
101
102

	// Relay indicates whether the host should use circuit relay transport
103
	EnableRelay bool
104
105
106

	// RelayOpts are options for the relay transport; only meaningful when Relay=true
	RelayOpts []circuit.RelayOpt
107
108
109
}

// NewHost constructs a new *BasicHost and activates it by attaching its stream and connection handlers to the given inet.Network.
110
func NewHost(ctx context.Context, net inet.Network, opts *HostOpts) (*BasicHost, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111
	h := &BasicHost{
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
		network:    net,
		mux:        msmux.NewMultistreamMuxer(),
		negtimeout: DefaultNegotiationTimeout,
		addrs:      DefaultAddrsFactory,
	}

	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 {
		h.natmgr = opts.NATManager
	}

	if opts.BandwidthReporter != nil {
		h.bwc = opts.BandwidthReporter
		h.ids.Reporter = opts.BandwidthReporter
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144
145
	}

Jeromy's avatar
Jeromy committed
146
147
148
149
150
151
152
	if opts.ConnManager == nil {
		// create 'disabled' conn manager for now
		h.cmgr = connmgr.NewConnManager(0, 0, 0)
	} else {
		h.cmgr = opts.ConnManager
	}

153
154
155
	var relayCtx context.Context
	var relayCancel func()

156
	h.proc = goprocess.WithTeardown(func() error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157
158
159
		if h.natmgr != nil {
			h.natmgr.Close()
		}
160
161
162
		if relayCancel != nil {
			relayCancel()
		}
163
164
165
		return h.Network().Close()
	})

166
167
168
	net.SetConnHandler(h.newConnHandler)
	net.SetStreamHandler(h.newStreamHandler)

169
	if opts.EnableRelay {
170
		relayCtx, relayCancel = context.WithCancel(ctx)
171
172
173
174
175
176
177
		err := circuit.AddRelayTransport(relayCtx, h, opts.RelayOpts...)
		if err != nil {
			h.Close()
			return nil, err
		}
	}

178
	return h, nil
179
}
Jeromy's avatar
Jeromy committed
180

181
182
183
184
185
// New constructs and sets up a new *BasicHost with given Network and options.
// Three options can be passed: NATPortMap, AddrsFactory, and metrics.Reporter.
// This function is deprecated in favor of NewHost and HostOpts.
func New(net inet.Network, opts ...interface{}) *BasicHost {
	hostopts := &HostOpts{}
186

187
	for _, o := range opts {
Jeromy's avatar
Jeromy committed
188
189
190
191
		switch o := o.(type) {
		case Option:
			switch o {
			case NATPortMap:
192
				hostopts.NATManager = newNatManager(net)
Jeromy's avatar
Jeromy committed
193
194
			}
		case metrics.Reporter:
195
			hostopts.BandwidthReporter = o
196
		case AddrsFactory:
197
			hostopts.AddrsFactory = AddrsFactory(o)
Jeromy's avatar
Jeromy committed
198
199
		case connmgr.ConnManager:
			hostopts.ConnManager = o
200
201
202
		}
	}

203
	h, err := NewHost(context.Background(), net, hostopts)
204
205
206
207
208
209
210
	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
211
212
213
214
}

// newConnHandler is the remote-opened conn handler for inet.Network
func (h *BasicHost) newConnHandler(c inet.Conn) {
215
216
217
	// 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
218
219
220
221
	h.ids.IdentifyConn(c)
}

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

226
227
	if h.negtimeout > 0 {
		if err := s.SetDeadline(time.Now().Add(h.negtimeout)); err != nil {
228
229
230
231
232
233
			log.Error("setting stream deadline: ", err)
			s.Close()
			return
		}
	}

234
	lzc, protoID, handle, err := h.Mux().NegotiateLazy(s)
235
	took := time.Now().Sub(before)
Jeromy's avatar
Jeromy committed
236
	if err != nil {
237
		if err == io.EOF {
238
239
240
241
242
			logf := log.Debugf
			if took > time.Second*10 {
				logf = log.Warningf
			}
			logf("protocol EOF: %s (took %s)", s.Conn().RemotePeer(), took)
243
		} else {
244
			log.Warning("protocol mux failed: %s (took %s)", err, took)
245
		}
246
		s.Close()
Jeromy's avatar
Jeromy committed
247
248
		return
	}
249

250
251
252
253
254
	s = &streamWrapper{
		Stream: s,
		rw:     lzc,
	}

255
	if h.negtimeout > 0 {
256
257
258
259
260
261
262
		if err := s.SetDeadline(time.Time{}); err != nil {
			log.Error("resetting stream deadline: ", err)
			s.Close()
			return
		}
	}

263
	s.SetProtocol(protocol.ID(protoID))
Jeromy's avatar
Jeromy committed
264

265
266
267
268
	if h.bwc != nil {
		s = mstream.WrapStream(s, h.bwc)
	}
	log.Debugf("protocol negotiation took %s", took)
Jeromy's avatar
Jeromy committed
269

270
	go handle(protoID, s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
271
272
273
274
275
276
277
278
}

// 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
279
func (h *BasicHost) Peerstore() pstore.Peerstore {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
280
281
282
	return h.Network().Peerstore()
}

283
// Network returns the Network interface of the Host
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
284
285
286
287
288
func (h *BasicHost) Network() inet.Network {
	return h.network
}

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

293
// IDService returns
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294
295
296
297
298
299
300
301
302
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) {
303
304
	h.Mux().AddHandler(string(pid), func(p string, rwc io.ReadWriteCloser) error {
		is := rwc.(inet.Stream)
305
		is.SetProtocol(protocol.ID(p))
306
		handler(is)
Jeromy's avatar
Jeromy committed
307
308
		return nil
	})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
309
310
}

311
312
313
314
315
// 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)
316
		is.SetProtocol(protocol.ID(p))
317
318
319
320
321
		handler(is)
		return nil
	})
}

322
// RemoveStreamHandler returns ..
Jeromy's avatar
Jeromy committed
323
func (h *BasicHost) RemoveStreamHandler(pid protocol.ID) {
Jeromy's avatar
Jeromy committed
324
	h.Mux().RemoveHandler(string(pid))
Jeromy's avatar
Jeromy committed
325
326
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
327
328
329
330
// 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)
331
func (h *BasicHost) NewStream(ctx context.Context, p peer.ID, pids ...protocol.ID) (inet.Stream, error) {
332
333
334
335
336
	pref, err := h.preferredProtocol(p, pids)
	if err != nil {
		return nil, err
	}

337
338
339
340
	if pref != "" {
		return h.newStream(ctx, p, pref)
	}

341
	var protoStrs []string
342
	for _, pid := range pids {
343
344
		protoStrs = append(protoStrs, string(pid))
	}
345

346
347
348
349
	s, err := h.Network().NewStream(ctx, p)
	if err != nil {
		return nil, err
	}
350

351
352
353
354
	selected, err := msmux.SelectOneOf(protoStrs, s)
	if err != nil {
		s.Close()
		return nil, err
355
	}
356
357
	selpid := protocol.ID(selected)
	s.SetProtocol(selpid)
358
	h.Peerstore().AddProtocols(p, selected)
359

Jeromy's avatar
Jeromy committed
360
361
362
363
364
	if h.bwc != nil {
		s = mstream.WrapStream(s, h.bwc)
	}

	return s, nil
365
366
}

367
368
369
370
func pidsToStrings(pids []protocol.ID) []string {
	out := make([]string, len(pids))
	for i, p := range pids {
		out[i] = string(p)
371
	}
372
	return out
373
374
}

375
376
377
378
379
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
380
381
	}

382
383
384
385
386
	var out protocol.ID
	if len(supported) > 0 {
		out = protocol.ID(supported[0])
	}
	return out, nil
387
388
389
}

func (h *BasicHost) newStream(ctx context.Context, p peer.ID, pid protocol.ID) (inet.Stream, error) {
390
	s, err := h.Network().NewStream(ctx, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
391
392
393
394
	if err != nil {
		return nil, err
	}

395
	s.SetProtocol(pid)
396

Jeromy's avatar
Jeromy committed
397
398
399
	if h.bwc != nil {
		s = mstream.WrapStream(s, h.bwc)
	}
Jeromy's avatar
Jeromy committed
400

Jeromy's avatar
Jeromy committed
401
	lzcon := msmux.NewMSSelect(s, string(pid))
Jeromy's avatar
Jeromy committed
402
	return &streamWrapper{
Jeromy's avatar
Jeromy committed
403
		Stream: s,
Jeromy's avatar
Jeromy committed
404
405
		rw:     lzcon,
	}, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
406
407
408
409
410
411
}

// Connect ensures there is a connection between this host and the peer with
// given peer.ID. Connect will absorb the addresses in pi into its internal
// peerstore. 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
412
// returned.
Jeromy's avatar
Jeromy committed
413
func (h *BasicHost) Connect(ctx context.Context, pi pstore.PeerInfo) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
414
415

	// absorb addresses into peerstore
Jeromy's avatar
Jeromy committed
416
	h.Peerstore().AddAddrs(pi.ID, pi.Addrs, pstore.TempAddrTTL)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434

	cs := h.Network().ConnsToPeer(pi.ID)
	if len(cs) > 0 {
		return nil
	}

	return h.dialPeer(ctx, pi.ID)
}

// 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 {
	log.Debugf("host %s dialing %s", h.ID, p)
	c, err := h.Network().DialPeer(ctx, p)
	if err != nil {
		return err
	}

435
436
437
438
	// 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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
	// 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
453
	log.Debugf("host %s finished dialing %s", h.ID(), p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
454
455
456
	return nil
}

Jeromy's avatar
Jeromy committed
457
458
459
460
func (h *BasicHost) ConnManager() connmgr.ConnManager {
	return h.cmgr
}

461
462
// Addrs returns listening addresses that are safe to announce to the network.
// The output is the same as AllAddrs, but processed by AddrsFactory.
463
func (h *BasicHost) Addrs() []ma.Multiaddr {
464
465
466
467
468
469
	return h.addrs(h.AllAddrs())
}

// 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 {
470
471
472
473
474
	addrs, err := h.Network().InterfaceListenAddresses()
	if err != nil {
		log.Debug("error retrieving network interface addrs")
	}

475
476
477
478
	if h.ids != nil { // add external observed addresses
		addrs = append(addrs, h.ids.OwnObservedAddrs()...)
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
479
480
481
482
483
	if h.natmgr != nil { // natmgr is nil if we do not use nat option.
		nat := h.natmgr.NAT()
		if nat != nil { // nat is nil if not ready, or no nat is available.
			addrs = append(addrs, nat.ExternalAddrs()...)
		}
484
485
486
487
488
	}

	return addrs
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
489
490
// Close shuts down the Host's services (network, etc).
func (h *BasicHost) Close() error {
491
	return h.proc.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
492
}
Jeromy's avatar
Jeromy committed
493

494
// GetBandwidthReporter exposes the Host's bandiwth metrics reporter
Jeromy's avatar
Jeromy committed
495
496
497
func (h *BasicHost) GetBandwidthReporter() metrics.Reporter {
	return h.bwc
}
Jeromy's avatar
Jeromy committed
498
499
500
501
502
503
504
505
506
507
508
509
510

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