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

import (
4
5
	"io"

Jeromy's avatar
Jeromy committed
6
7
	metrics "github.com/ipfs/go-libp2p/p2p/metrics"
	mstream "github.com/ipfs/go-libp2p/p2p/metrics/stream"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
9
10
11
	inet "github.com/ipfs/go-libp2p/p2p/net"
	protocol "github.com/ipfs/go-libp2p/p2p/protocol"
	identify "github.com/ipfs/go-libp2p/p2p/protocol/identify"
	relay "github.com/ipfs/go-libp2p/p2p/protocol/relay"
Jeromy's avatar
Jeromy committed
12
	goprocess "gx/ipfs/QmQopLATEYMNg7dVqZRNDfeE2S1yKy8zrRh5xnYiuqeZBn/goprocess"
13
	peer "gx/ipfs/QmZwZjMVGss5rqYsJVGy18gNbkTJffFyq2x1uJ4e4p3ZAt/go-libp2p-peer"
Jeromy's avatar
Jeromy committed
14
15
16
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
	logging "gx/ipfs/Qmazh5oNUVsDZTs2g59rq8aYQqwpss8tcUWQzor5sCCEuH/go-log"
	ma "gx/ipfs/QmcobAGsCjYt5DXoq9et9L8yR8er7o7Cu3DTvpaq12jYSz/go-multiaddr"
Jeromy's avatar
Jeromy committed
17

Jeromy's avatar
Jeromy committed
18
	msmux "gx/ipfs/QmUeEcYJrzAEKdQXjzTxCgNZgc9sRuwharsvzzm5Gd2oGB/go-multistream"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19
20
)

Jeromy's avatar
Jeromy committed
21
var log = logging.Logger("github.com/ipfs/go-libp2p/p2p/host/basic")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
23
// Option is a type used to pass in options to the host.
24
25
26
type Option int

const (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27
28
29
30
31
	// 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.
32
33
34
	NATPortMap Option = iota
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35
36
37
38
39
40
// 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 relay service to allow hosts to relay conns for each other
//  * uses a nat service to establish NAT port mappings
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
42
type BasicHost struct {
	network inet.Network
Jeromy's avatar
Jeromy committed
43
	mux     *msmux.MultistreamMuxer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44
45
	ids     *identify.IDService
	relay   *relay.RelayService
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46
	natmgr  *natManager
47
48

	proc goprocess.Process
Jeromy's avatar
Jeromy committed
49
50

	bwc metrics.Reporter
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51
52
53
}

// New constructs and sets up a new *BasicHost with given Network
Jeromy's avatar
Jeromy committed
54
func New(net inet.Network, opts ...interface{}) *BasicHost {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55
56
	h := &BasicHost{
		network: net,
Jeromy's avatar
Jeromy committed
57
		mux:     msmux.NewMultistreamMuxer(),
Jeromy's avatar
Jeromy committed
58
		bwc:     metrics.NewBandwidthCounter(),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
59
60
	}

61
	h.proc = goprocess.WithTeardown(func() error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62
63
64
65
		if h.natmgr != nil {
			h.natmgr.Close()
		}

66
67
68
		return h.Network().Close()
	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
69
70
	// setup host services
	h.ids = identify.NewIDService(h)
Jeromy's avatar
Jeromy committed
71
72
73
74
75
76

	muxh := h.Mux().Handle
	handle := func(s inet.Stream) {
		muxh(s)
	}
	h.relay = relay.NewRelayService(h, handle)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77

78
	for _, o := range opts {
Jeromy's avatar
Jeromy committed
79
80
81
82
83
84
85
86
		switch o := o.(type) {
		case Option:
			switch o {
			case NATPortMap:
				h.natmgr = newNatManager(h)
			}
		case metrics.Reporter:
			h.bwc = o
87
88
89
		}
	}

Jeromy's avatar
Jeromy committed
90
91
92
	net.SetConnHandler(h.newConnHandler)
	net.SetStreamHandler(h.newStreamHandler)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93
94
95
96
97
98
99
100
101
	return h
}

// newConnHandler is the remote-opened conn handler for inet.Network
func (h *BasicHost) newConnHandler(c inet.Conn) {
	h.ids.IdentifyConn(c)
}

// newStreamHandler is the remote-opened stream handler for inet.Network
Jeromy's avatar
Jeromy committed
102
// TODO: this feels a bit wonky
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103
func (h *BasicHost) newStreamHandler(s inet.Stream) {
Jeromy's avatar
Jeromy committed
104
	protoID, handle, err := h.Mux().Negotiate(s)
Jeromy's avatar
Jeromy committed
105
	if err != nil {
106
		if err == io.EOF {
107
			log.Debugf("protocol EOF: %s", s.Conn().RemotePeer())
108
		} else {
109
			log.Warning("protocol mux failed: %s", err)
110
		}
Jeromy's avatar
Jeromy committed
111
112
113
		return
	}

Jeromy's avatar
Jeromy committed
114
	logStream := mstream.WrapStream(s, protocol.ID(protoID), h.bwc)
Jeromy's avatar
Jeromy committed
115
116

	go handle(logStream)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117
118
119
120
121
122
123
124
125
126
127
128
}

// 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.
func (h *BasicHost) Peerstore() peer.Peerstore {
	return h.Network().Peerstore()
}

129
// Network returns the Network interface of the Host
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130
131
132
133
134
func (h *BasicHost) Network() inet.Network {
	return h.network
}

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

139
// IDService returns
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140
141
142
143
144
145
146
147
148
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) {
Jeromy's avatar
Jeromy committed
149
150
151
152
	h.Mux().AddHandler(string(pid), func(rwc io.ReadWriteCloser) error {
		handler(rwc.(inet.Stream))
		return nil
	})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153
154
}

155
// RemoveStreamHandler returns ..
Jeromy's avatar
Jeromy committed
156
func (h *BasicHost) RemoveStreamHandler(pid protocol.ID) {
Jeromy's avatar
Jeromy committed
157
	h.Mux().RemoveHandler(string(pid))
Jeromy's avatar
Jeromy committed
158
159
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
160
161
162
163
// 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)
164
165
func (h *BasicHost) NewStream(ctx context.Context, pid protocol.ID, p peer.ID) (inet.Stream, error) {
	s, err := h.Network().NewStream(ctx, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166
167
168
169
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
170
171
	logStream := mstream.WrapStream(s, pid, h.bwc)

Jeromy's avatar
Jeromy committed
172
173
174
175
176
	lzcon := msmux.NewMSSelect(logStream, string(pid))
	return &streamWrapper{
		Stream: logStream,
		rw:     lzcon,
	}, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
177
178
179
180
181
182
183
184
185
186
}

// 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
// returned. // TODO: Relay + NAT.
func (h *BasicHost) Connect(ctx context.Context, pi peer.PeerInfo) error {

	// absorb addresses into peerstore
187
	h.Peerstore().AddAddrs(pi.ID, pi.Addrs, peer.TempAddrTTL)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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

	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
	}

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

	log.Debugf("host %s finished dialing %s", h.ID, p)
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224
225
// Addrs 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.
226
227
228
229
230
231
func (h *BasicHost) Addrs() []ma.Multiaddr {
	addrs, err := h.Network().InterfaceListenAddresses()
	if err != nil {
		log.Debug("error retrieving network interface addrs")
	}

232
233
234
235
	if h.ids != nil { // add external observed addresses
		addrs = append(addrs, h.ids.OwnObservedAddrs()...)
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
236
237
238
239
240
	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()...)
		}
241
242
243
244
245
	}

	return addrs
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246
247
// Close shuts down the Host's services (network, etc).
func (h *BasicHost) Close() error {
248
	return h.proc.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
249
}
Jeromy's avatar
Jeromy committed
250

251
// GetBandwidthReporter exposes the Host's bandiwth metrics reporter
Jeromy's avatar
Jeromy committed
252
253
254
func (h *BasicHost) GetBandwidthReporter() metrics.Reporter {
	return h.bwc
}
Jeromy's avatar
Jeromy committed
255
256
257
258
259
260
261
262
263
264
265
266
267

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