swarm.go 4.98 KB
Newer Older
1 2 3 4 5
package swarm

import (
	"errors"
	"fmt"
Jeromy's avatar
Jeromy committed
6
	"strings"
7 8 9 10 11 12
	"sync"

	conn "github.com/jbenet/go-ipfs/net/conn"
	msg "github.com/jbenet/go-ipfs/net/message"
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13
	ctxc "github.com/jbenet/go-ipfs/util/ctxcloser"
14 15

	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
16
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
17 18
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20
var log = u.Logger("swarm")

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
// ErrAlreadyOpen signals that a connection to a peer is already open.
var ErrAlreadyOpen = errors.New("Error: Connection to this peer already open.")

// ListenErr contains a set of errors mapping to each of the swarms addresses.
// Used to return multiple errors, as in listen.
type ListenErr struct {
	Errors []error
}

func (e *ListenErr) Error() string {
	if e == nil {
		return "<nil error>"
	}
	var out string
	for i, v := range e.Errors {
		if v != nil {
			out += fmt.Sprintf("%d: %s\n", i, v)
		}
	}
	return out
}

// Swarm is a connection muxer, allowing connections to other peers to
// be opened and closed, while still using the same Chan for all
// communication. The Chan sends/receives Messages, which note the
// destination or source Peer.
type Swarm struct {

	// local is the peer this swarm represents
50
	local peer.Peer
51

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52 53 54
	// peers is a collection of peers for swarm to use
	peers peer.Peerstore

55 56 57 58 59 60 61
	// Swarm includes a Pipe object.
	*msg.Pipe

	// errChan is the channel of errors.
	errChan chan error

	// conns are the open connections the swarm is handling.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62 63
	// these are MultiConns, which multiplex multiple separate underlying Conns.
	conns     conn.MultiConnMap
64 65 66
	connsLock sync.RWMutex

	// listeners for each network address
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67
	listeners []conn.Listener
68

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
69
	// ContextCloser
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70
	ctxc.ContextCloser
71 72 73
}

// NewSwarm constructs a Swarm, with a Chan.
74
func NewSwarm(ctx context.Context, listenAddrs []ma.Multiaddr, local peer.Peer, ps peer.Peerstore) (*Swarm, error) {
75 76
	s := &Swarm{
		Pipe:    msg.NewPipe(10),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77
		conns:   conn.MultiConnMap{},
78
		local:   local,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
79
		peers:   ps,
80 81 82
		errChan: make(chan error, 100),
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83
	// ContextCloser for proper child management.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84
	s.ContextCloser = ctxc.NewContextCloser(ctx, s.close)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
85

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
86
	s.Children().Add(1)
87
	go s.fanOut()
88
	return s, s.listen(listenAddrs)
89 90
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91 92
// close stops a swarm. It's the underlying function called by ContextCloser
func (s *Swarm) close() error {
93 94 95 96
	// close listeners
	for _, list := range s.listeners {
		list.Close()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97 98
	// close connections
	conn.CloseConns(s.Connections()...)
99 100 101 102 103 104 105 106 107 108 109
	return nil
}

// Dial connects to a peer.
//
// The idea is that the client of Swarm does not need to know what network
// the connection will happen over. Swarm can use whichever it choses.
// This allows us to use various transport protocols, do NAT traversal/relay,
// etc. to achive connection.
//
// For now, Dial uses only TCP. This will be extended.
110 111
func (s *Swarm) Dial(peer peer.Peer) (conn.Conn, error) {
	if peer.ID().Equal(s.local.ID()) {
112 113 114 115
		return nil, errors.New("Attempted connection to self!")
	}

	// check if we already have an open connection first
116
	c := s.GetConnection(peer.ID())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117 118 119 120 121
	if c != nil {
		return c, nil
	}

	// check if we don't have the peer in Peerstore
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
122
	peer, err := s.peers.Add(peer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123 124 125
	if err != nil {
		return nil, err
	}
126 127

	// open connection to peer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
128 129 130 131 132
	d := &conn.Dialer{
		LocalPeer: s.local,
		Peerstore: s.peers,
	}

Jeromy's avatar
Jeromy committed
133
	// If we are attempting to connect to the zero addr, fail out early
Jeromy's avatar
Jeromy committed
134 135 136 137 138 139 140 141 142
	raddr := peer.NetAddress("tcp")
	if raddr == nil {
		return nil, fmt.Errorf("No remote address for network tcp")
	}

	if strings.HasPrefix(raddr.String(), "/ip4/0.0.0.0") {
		return nil, fmt.Errorf("Attempted to connect to loopback address: %s", raddr)
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143
	c, err = d.Dial(s.Context(), "tcp", peer)
144 145 146 147
	if err != nil {
		return nil, err
	}

148 149
	c, err = s.connSetup(c)
	if err != nil {
150 151 152 153 154 155 156
		c.Close()
		return nil, err
	}

	return c, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157
// GetConnection returns the connection in the swarm to given peer.ID
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
func (s *Swarm) GetConnection(pid peer.ID) conn.Conn {
159
	s.connsLock.RLock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
160
	c, found := s.conns[u.Key(pid)]
161 162 163 164 165
	s.connsLock.RUnlock()

	if !found {
		return nil
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166
	return c
167 168
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169 170 171 172 173 174 175 176 177 178 179 180 181
// Connections returns a slice of all connections.
func (s *Swarm) Connections() []conn.Conn {
	s.connsLock.RLock()

	conns := make([]conn.Conn, 0, len(s.conns))
	for _, c := range s.conns {
		conns = append(conns, c)
	}

	s.connsLock.RUnlock()
	return conns
}

182
// CloseConnection removes a given peer from swarm + closes the connection
183 184
func (s *Swarm) CloseConnection(p peer.Peer) error {
	c := s.GetConnection(p.ID())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185
	if c == nil {
186 187 188 189
		return u.ErrNotFound
	}

	s.connsLock.Lock()
190
	delete(s.conns, u.Key(p.ID()))
191 192
	s.connsLock.Unlock()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
193
	return c.Close()
194 195 196 197 198 199 200 201 202 203 204
}

func (s *Swarm) Error(e error) {
	s.errChan <- e
}

// GetErrChan returns the errors chan.
func (s *Swarm) GetErrChan() chan error {
	return s.errChan
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205
// GetPeerList returns a copy of the set of peers swarm is connected to.
206 207
func (s *Swarm) GetPeerList() []peer.Peer {
	var out []peer.Peer
208
	s.connsLock.RLock()
Jeromy's avatar
Jeromy committed
209
	for _, p := range s.conns {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
210
		out = append(out, p.RemotePeer())
Jeromy's avatar
Jeromy committed
211
	}
212
	s.connsLock.RUnlock()
Jeromy's avatar
Jeromy committed
213 214
	return out
}