conn.go 7.64 KB
Newer Older
1
package conn
2 3

import (
4
	"fmt"
5
	"time"
6

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
8
	msgio "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-msgio"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
10
	manet "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/net"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11

12 13
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
14 15
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16 17
var log = u.Logger("conn")

18 19 20
const (
	// ChanBuffer is the size of the buffer in the Conn Chan
	ChanBuffer = 10
21

22 23 24 25 26 27
	// MaxMessageSize is the size of the largest single message
	MaxMessageSize = 1 << 20 // 1 MB

	// HandshakeTimeout for when nodes first connect
	HandshakeTimeout = time.Second * 5
)
28

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29 30 31 32 33
// msgioPipe is a pipe using msgio channels.
type msgioPipe struct {
	outgoing *msgio.Chan
	incoming *msgio.Chan
}
34

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35 36 37 38 39 40 41 42 43 44 45 46
func newMsgioPipe(size int) *msgioPipe {
	return &msgioPipe{
		outgoing: msgio.NewChan(10),
		incoming: msgio.NewChan(10),
	}
}

// singleConn represents a single connection to another Peer (IPFS Node).
type singleConn struct {
	local  *peer.Peer
	remote *peer.Peer
	maconn manet.Conn
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
47
	msgio  *msgioPipe
48 49

	ContextCloser
50 51
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52 53
// newConn constructs a new connection
func newSingleConn(ctx context.Context, local, remote *peer.Peer,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54
	maconn manet.Conn) (Conn, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55 56

	conn := &singleConn{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57 58 59 60
		local:  local,
		remote: remote,
		maconn: maconn,
		msgio:  newMsgioPipe(10),
61 62
	}

63 64
	conn.ContextCloser = NewContextCloser(ctx, conn.close)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66 67
	log.Info("newSingleConn: %v to %v", local, remote)

	// setup the various io goroutines
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68 69
	go conn.msgio.outgoing.WriteTo(maconn)
	go conn.msgio.incoming.ReadFrom(maconn, MaxMessageSize)
70

71 72 73 74 75 76 77
	// version handshake
	ctxT, _ := context.WithTimeout(ctx, HandshakeTimeout)
	if err := VersionHandshake(ctxT, conn); err != nil {
		conn.Close()
		return nil, fmt.Errorf("Version handshake: %s", err)
	}

78 79 80
	return conn, nil
}

81 82 83
// close is the internal close function, called by ContextCloser.Close
func (c *singleConn) close() error {
	log.Debug("%s closing Conn with %s", c.local, c.remote)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84 85

	// close underlying connection
86
	err := c.maconn.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87
	c.msgio.outgoing.Close()
88
	return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
89 90
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
// ID is an identifier unique to this connection.
func (c *singleConn) ID() string {
	return ID(c)
}

// LocalMultiaddr is the Multiaddr on this side
func (c *singleConn) LocalMultiaddr() ma.Multiaddr {
	return c.maconn.LocalMultiaddr()
}

// RemoteMultiaddr is the Multiaddr on the remote side
func (c *singleConn) RemoteMultiaddr() ma.Multiaddr {
	return c.maconn.RemoteMultiaddr()
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106 107 108 109 110 111 112 113 114 115
// LocalPeer is the Peer on this side
func (c *singleConn) LocalPeer() *peer.Peer {
	return c.local
}

// RemotePeer is the Peer on the remote side
func (c *singleConn) RemotePeer() *peer.Peer {
	return c.remote
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116 117
// In returns a readable message channel
func (c *singleConn) In() <-chan []byte {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118
	return c.msgio.incoming.MsgChan
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
119 120
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121 122
// Out returns a writable message channel
func (c *singleConn) Out() chan<- []byte {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123
	return c.msgio.outgoing.MsgChan
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124 125
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126 127 128 129 130 131 132 133 134 135
// ID returns the
func ID(c Conn) string {
	l := fmt.Sprintf("%s/%s", c.LocalMultiaddr(), c.LocalPeer().ID)
	r := fmt.Sprintf("%s/%s", c.RemoteMultiaddr(), c.RemotePeer().ID)
	lh := u.Hash([]byte(l))
	rh := u.Hash([]byte(r))
	ch := u.XOR(lh, rh)
	return u.Key(ch).Pretty()
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149
// Dialer is an object that can open connections. We could have a "convenience"
// Dial function as before, but it would have many arguments, as dialing is
// no longer simple (need a peerstore, a local peer, a context, a network, etc)
type Dialer struct {

	// LocalPeer is the identity of the local Peer.
	LocalPeer *peer.Peer

	// Peerstore is the set of peers we know about locally. The Dialer needs it
	// because when an incoming connection is identified, we should reuse the
	// same peer objects (otherwise things get inconsistent).
	Peerstore peer.Peerstore
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
150
// Dial connects to a particular peer, over a given network
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
151 152 153
// Example: d.Dial(ctx, "udp", peer)
func (d *Dialer) Dial(ctx context.Context, network string, remote *peer.Peer) (Conn, error) {
	laddr := d.LocalPeer.NetAddress(network)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154 155
	if laddr == nil {
		return nil, fmt.Errorf("No local address for network %s", network)
156
	}
157

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158 159 160 161 162 163
	raddr := remote.NetAddress(network)
	if raddr == nil {
		return nil, fmt.Errorf("No remote address for network %s", network)
	}

	// TODO: try to get reusing addr/ports to work.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164 165
	// madialer := manet.Dialer{LocalAddr: laddr}
	madialer := manet.Dialer{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167 168
	log.Info("%s dialing %s %s", d.LocalPeer, remote, raddr)
	maconn, err := madialer.Dial(raddr)
169 170 171
	if err != nil {
		return nil, err
	}
172

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173 174 175 176
	if err := d.Peerstore.Put(remote); err != nil {
		log.Error("Error putting peer into peerstore: %s", remote)
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
177 178 179 180 181 182
	c, err := newSingleConn(ctx, d.LocalPeer, remote, maconn)
	if err != nil {
		return nil, err
	}

	return newSecureConn(ctx, c, d.Peerstore)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
}

// listener is an object that can accept connections. It implements Listener
type listener struct {
	manet.Listener

	// chansize is the size of the internal channels for concurrency
	chansize int

	// channel of incoming conections
	conns chan Conn

	// Local multiaddr to listen on
	maddr ma.Multiaddr

	// LocalPeer is the identity of the local Peer.
	local *peer.Peer

	// Peerstore is the set of peers we know about locally
	peers peer.Peerstore

204 205
	// embedded ContextCloser
	ContextCloser
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206 207
}

208 209 210 211
// disambiguate
func (l *listener) Close() error {
	return l.ContextCloser.Close()
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
212

213 214 215 216
// close called by ContextCloser.Close
func (l *listener) close() error {
	log.Info("listener closing: %s %s", l.local, l.maddr)
	return l.Listener.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217 218 219 220
}

func (l *listener) isClosed() bool {
	select {
221
	case <-l.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222 223 224 225
		return true
	default:
		return false
	}
226 227
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
228 229 230 231 232 233 234 235
func (l *listener) listen() {

	// handle at most chansize concurrent handshakes
	sem := make(chan struct{}, l.chansize)

	// handle is a goroutine work function that handles the handshake.
	// it's here only so that accepting new connections can happen quickly.
	handle := func(maconn manet.Conn) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
236 237 238
		defer func() { <-sem }() // release

		c, err := newSingleConn(l.Context(), l.local, nil, maconn)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239 240
		if err != nil {
			log.Error("Error accepting connection: %v", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
242
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
243 244 245 246 247 248 249 250

		sc, err := newSecureConn(l.Context(), c, l.peers)
		if err != nil {
			log.Error("Error securing connection: %v", err)
			return
		}

		l.conns <- sc
251
	}
252

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
253 254 255
	for {
		maconn, err := l.Listener.Accept()
		if err != nil {
256

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
257
			// if cancel is nil we're closed.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
258
			if l.isClosed() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
259 260
				return // done.
			}
261

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
			log.Error("Failed to accept connection: %v", err)
			continue
		}

		sem <- struct{}{} // acquire
		go handle(maconn)
	}
}

// Accept waits for and returns the next connection to the listener.
// Note that unfortunately this
func (l *listener) Accept() <-chan Conn {
	return l.conns
}

// Multiaddr is the identity of the local Peer.
func (l *listener) Multiaddr() ma.Multiaddr {
	return l.maddr
}

// LocalPeer is the identity of the local Peer.
func (l *listener) LocalPeer() *peer.Peer {
	return l.local
}

// Peerstore is the set of peers we know about locally. The Listener needs it
// because when an incoming connection is identified, we should reuse the
// same peer objects (otherwise things get inconsistent).
func (l *listener) Peerstore() peer.Peerstore {
	return l.peers
}

// Listen listens on the particular multiaddr, with given peer and peerstore.
func Listen(ctx context.Context, addr ma.Multiaddr, local *peer.Peer, peers peer.Peerstore) (Listener, error) {

	ml, err := manet.Listen(addr)
	if err != nil {
		return nil, err
300
	}
301

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
302 303 304 305 306 307 308 309 310 311 312 313
	// todo make this a variable
	chansize := 10

	l := &listener{
		Listener: ml,
		maddr:    addr,
		peers:    peers,
		local:    local,
		conns:    make(chan Conn, chansize),
		chansize: chansize,
	}

314 315
	l.ContextCloser = NewContextCloser(ctx, l.close)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
316 317 318
	go l.listen()

	return l, nil
319
}