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

import (
4
5
	"io"

6
7
8
	ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	goprocess "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
Jeromy's avatar
Jeromy committed
9
10
	metrics "github.com/ipfs/go-ipfs/metrics"
	mstream "github.com/ipfs/go-ipfs/metrics/stream"
11
	eventlog "github.com/ipfs/go-ipfs/thirdparty/eventlog"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12

13
14
15
16
17
	inet "github.com/ipfs/go-ipfs/p2p/net"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	protocol "github.com/ipfs/go-ipfs/p2p/protocol"
	identify "github.com/ipfs/go-ipfs/p2p/protocol/identify"
	relay "github.com/ipfs/go-ipfs/p2p/protocol/relay"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18
19
20
21
)

var log = eventlog.Logger("p2p/host/basic")

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34
35
36
37
38
39
// 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
40
41
type BasicHost struct {
	network inet.Network
Brian Tiger Chow's avatar
Brian Tiger Chow committed
42
	mux     *protocol.Mux
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43
44
	ids     *identify.IDService
	relay   *relay.RelayService
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
45
	natmgr  *natManager
46
47

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

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68
69
70
71
	// setup host services
	h.ids = identify.NewIDService(h)
	h.relay = relay.NewRelayService(h, h.Mux().HandleSync)

72
	for _, o := range opts {
Jeromy's avatar
Jeromy committed
73
74
75
76
77
78
79
80
		switch o := o.(type) {
		case Option:
			switch o {
			case NATPortMap:
				h.natmgr = newNatManager(h)
			}
		case metrics.Reporter:
			h.bwc = o
81
82
83
		}
	}

Jeromy's avatar
Jeromy committed
84
85
86
	net.SetConnHandler(h.newConnHandler)
	net.SetStreamHandler(h.newStreamHandler)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87
88
89
90
91
92
93
94
95
	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
96
// TODO: this feels a bit wonky
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
func (h *BasicHost) newStreamHandler(s inet.Stream) {
Jeromy's avatar
Jeromy committed
98
99
	protoID, handle, err := h.Mux().ReadHeader(s)
	if err != nil {
100
101
102
103
104
		if err == io.EOF {
			log.Warningf("protocol EOF: %s", s.Conn().RemotePeer())
		} else {
			log.Errorf("protocol mux failed: %s", err)
		}
Jeromy's avatar
Jeromy committed
105
106
107
108
109
110
		return
	}

	logStream := mstream.WrapStream(s, protoID, h.bwc)

	go handle(logStream)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
}

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

// Networks returns the Network interface of the Host
func (h *BasicHost) Network() inet.Network {
	return h.network
}

// Mux returns the Mux multiplexing incoming streams to protocol handlers
func (h *BasicHost) Mux() *protocol.Mux {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
130
	return h.mux
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
}

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) {
	h.Mux().SetHandler(pid, handler)
}

Jeromy's avatar
Jeromy committed
145
146
147
148
func (h *BasicHost) RemoveStreamHandler(pid protocol.ID) {
	h.Mux().RemoveHandler(pid)
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149
150
151
152
153
154
155
156
157
158
// 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)
func (h *BasicHost) NewStream(pid protocol.ID, p peer.ID) (inet.Stream, error) {
	s, err := h.Network().NewStream(p)
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
159
160
161
162
	logStream := mstream.WrapStream(s, pid, h.bwc)

	if err := protocol.WriteHeader(logStream, pid); err != nil {
		logStream.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163
164
165
		return nil, err
	}

Jeromy's avatar
Jeromy committed
166
	return logStream, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167
168
169
170
171
172
173
174
175
176
}

// 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
177
	h.Peerstore().AddAddrs(pi.ID, pi.Addrs, peer.TempAddrTTL)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
178
179
180
181
182
183
184
185
186
187
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

	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
214
215
// 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.
216
217
218
219
220
221
func (h *BasicHost) Addrs() []ma.Multiaddr {
	addrs, err := h.Network().InterfaceListenAddresses()
	if err != nil {
		log.Debug("error retrieving network interface addrs")
	}

222
223
224
225
	if h.ids != nil { // add external observed addresses
		addrs = append(addrs, h.ids.OwnObservedAddrs()...)
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
226
227
228
229
230
	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()...)
		}
231
232
233
234
235
	}

	return addrs
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
236
237
// Close shuts down the Host's services (network, etc).
func (h *BasicHost) Close() error {
238
	return h.proc.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239
}
Jeromy's avatar
Jeromy committed
240
241
242
243

func (h *BasicHost) GetBandwidthReporter() metrics.Reporter {
	return h.bwc
}