net.go 6.47 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
// Package net provides an interface for ipfs to interact with the network through
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
2 3 4
package net

import (
5
	ic "github.com/jbenet/go-ipfs/crypto"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	swarm "github.com/jbenet/go-ipfs/net/swarm"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7 8
	peer "github.com/jbenet/go-ipfs/peer"

9
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
10
	ctxgroup "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-ctxgroup"
11
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13
)

14
type stream swarm.Stream
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15

16 17 18
func (s *stream) SwarmStream() *swarm.Stream {
	return (*swarm.Stream)(s)
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19

20 21 22 23 24
// Conn returns the connection this stream is part of.
func (s *stream) Conn() Conn {
	c := s.SwarmStream().Conn()
	return (*conn_)(c)
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25

26 27 28 29
// Conn returns the connection this stream is part of.
func (s *stream) Close() error {
	return s.SwarmStream().Close()
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30

31 32 33
// Read reads bytes from a stream.
func (s *stream) Read(p []byte) (n int, err error) {
	return s.SwarmStream().Read(p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34 35
}

36 37 38 39
// Write writes bytes to a stream, flushing for each call.
func (s *stream) Write(p []byte) (n int, err error) {
	return s.SwarmStream().Write(p)
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40

41
type conn_ swarm.Conn
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42

43 44 45 46
func (c *conn_) SwarmConn() *swarm.Conn {
	return (*swarm.Conn)(c)
}

47
func (c *conn_) NewStreamWithProtocol(pr ProtocolID) (Stream, error) {
48
	s, err := (*swarm.Conn)(c).NewStream()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
49 50 51
	if err != nil {
		return nil, err
	}
52 53 54

	ss := (*stream)(s)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55
	if err := WriteProtocolHeader(pr, ss); err != nil {
56 57 58 59 60
		ss.Close()
		return nil, err
	}

	return ss, nil
61
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62

63 64 65
func (c *conn_) LocalMultiaddr() ma.Multiaddr {
	return c.SwarmConn().LocalMultiaddr()
}
66

67 68
func (c *conn_) RemoteMultiaddr() ma.Multiaddr {
	return c.SwarmConn().RemoteMultiaddr()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
69 70
}

71 72 73 74 75
func (c *conn_) LocalPeer() peer.ID {
	return c.SwarmConn().LocalPeer()
}

func (c *conn_) RemotePeer() peer.ID {
76 77 78
	return c.SwarmConn().RemotePeer()
}

79 80 81 82 83 84 85 86
func (c *conn_) LocalPrivateKey() ic.PrivKey {
	return c.SwarmConn().LocalPrivateKey()
}

func (c *conn_) RemotePublicKey() ic.PubKey {
	return c.SwarmConn().RemotePublicKey()
}

87 88
// network implements the Network interface,
type network struct {
89
	local peer.ID      // local peer
90 91
	mux   Mux          // protocol multiplexing
	swarm *swarm.Swarm // peer connection multiplexing
92 93
	ps    peer.Peerstore
	ids   *IDService
94 95 96 97

	cg ctxgroup.ContextGroup // for Context closing
}

98
// NewNetwork constructs a new network and starts listening on given addresses.
99
func NewNetwork(ctx context.Context, listen []ma.Multiaddr, local peer.ID,
100
	peers peer.Peerstore) (Network, error) {
101 102 103 104 105 106 107 108 109

	s, err := swarm.NewSwarm(ctx, listen, local, peers)
	if err != nil {
		return nil, err
	}

	n := &network{
		local: local,
		swarm: s,
110
		mux:   Mux{Handlers: StreamHandlerMap{}},
111
		cg:    ctxgroup.WithContext(ctx),
112
		ps:    peers,
113 114
	}

115 116 117
	n.cg.SetTeardown(n.close)
	n.cg.AddChildGroup(s.CtxGroup())

118
	s.SetStreamHandler(func(s *swarm.Stream) {
119
		n.mux.Handle((*stream)(s))
120 121
	})

122 123 124 125 126
	// setup a conn handler that immediately "asks the other side about them"
	// this is ProtocolIdentify.
	n.ids = NewIDService(n)
	s.SetConnHandler(n.newConnHandler)

127 128
	return n, nil
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129

130 131 132 133 134 135 136 137 138 139 140 141
func (n *network) newConnHandler(c *swarm.Conn) {
	cc := (*conn_)(c)
	s, err := cc.NewStreamWithProtocol(ProtocolIdentify)
	if err != nil {
		log.Error("network: unable to open initial stream for %s", ProtocolIdentify)
		log.Event(n.CtxGroup().Context(), "IdentifyOpenFailed", c.RemotePeer())
	}

	// ok give the response to our handler.
	n.ids.ResponseHandler(s)
}

142 143
// DialPeer attempts to establish a connection to a given peer.
// Respects the context.
144
func (n *network) DialPeer(ctx context.Context, p peer.ID) error {
145
	_, err := n.swarm.Dial(ctx, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146 147 148
	return err
}

149 150 151 152
func (n *network) Protocols() []ProtocolID {
	return n.mux.Protocols()
}

153 154 155 156 157 158 159 160 161 162
// CtxGroup returns the network's ContextGroup
func (n *network) CtxGroup() ctxgroup.ContextGroup {
	return n.cg
}

// Swarm returns the network's peerstream.Swarm
func (n *network) Swarm() *swarm.Swarm {
	return n.Swarm()
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163
// LocalPeer the network's LocalPeer
164
func (n *network) LocalPeer() peer.ID {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165 166 167
	return n.swarm.LocalPeer()
}

168
// Peers returns the connected peers
169
func (n *network) Peers() []peer.ID {
170 171 172
	return n.swarm.Peers()
}

173 174 175 176 177
// Peers returns the connected peers
func (n *network) Peerstore() peer.Peerstore {
	return n.ps
}

178 179 180 181 182 183 184 185 186 187
// Conns returns the connected peers
func (n *network) Conns() []Conn {
	conns1 := n.swarm.Connections()
	out := make([]Conn, len(conns1))
	for i, c := range conns1 {
		out[i] = (*conn_)(c)
	}
	return out
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188
// ClosePeer connection to peer
189
func (n *network) ClosePeer(p peer.ID) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190 191 192
	return n.swarm.CloseConnection(p)
}

193 194 195 196 197 198 199 200 201 202
// close is the real teardown function
func (n *network) close() error {
	return n.swarm.Close()
}

// Close calls the ContextCloser func
func (n *network) Close() error {
	return n.cg.Close()
}

203 204 205 206 207
// BandwidthTotals returns the total amount of bandwidth transferred
func (n *network) BandwidthTotals() (in uint64, out uint64) {
	// need to implement this. probably best to do it in swarm this time.
	// need a "metrics" object
	return 0, 0
Jeromy's avatar
Jeromy committed
208 209
}

210
// ListenAddresses returns a list of addresses at which this network listens.
211
func (n *network) ListenAddresses() []ma.Multiaddr {
212 213 214 215 216 217
	return n.swarm.ListenAddresses()
}

// InterfaceListenAddresses returns a list of addresses at which this network
// listens. It expands "any interface" addresses (/ip4/0.0.0.0, /ip6/::) to
// use the known local interfaces.
218 219
func (n *network) InterfaceListenAddresses() ([]ma.Multiaddr, error) {
	return swarm.InterfaceListenAddresses(n.swarm)
220
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221 222

// Connectedness returns a state signaling connection capabilities
Brian Tiger Chow's avatar
Brian Tiger Chow committed
223
// For now only returns Connected || NotConnected. Expand into more later.
224
func (n *network) Connectedness(p peer.ID) Connectedness {
225 226
	c := n.swarm.ConnectionsToPeer(p)
	if c != nil && len(c) < 1 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227 228 229 230
		return Connected
	}
	return NotConnected
}
231

232 233 234
// NewStream returns a new stream to given peer p.
// If there is no connection to p, attempts to create one.
// If ProtocolID is "", writes no header.
235
func (c *network) NewStream(pr ProtocolID, p peer.ID) (Stream, error) {
236 237 238 239 240 241 242
	s, err := c.swarm.NewStreamWithPeer(p)
	if err != nil {
		return nil, err
	}

	ss := (*stream)(s)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
243
	if err := WriteProtocolHeader(pr, ss); err != nil {
244 245 246 247 248 249 250
		ss.Close()
		return nil, err
	}

	return ss, nil
}

251 252 253 254 255
// SetHandler sets the protocol handler on the Network's Muxer.
// This operation is threadsafe.
func (n *network) SetHandler(p ProtocolID, h StreamHandler) {
	n.mux.SetHandler(p, h)
}
256

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
257
func WriteProtocolHeader(pr ProtocolID, s Stream) error {
258 259 260 261 262 263 264
	if pr != "" { // only write proper protocol headers
		if err := WriteLengthPrefix(s, string(pr)); err != nil {
			return err
		}
	}
	return nil
}