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

import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4
	"errors"
5
	"fmt"
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

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

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

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
19
// ChanBuffer is the size of the buffer in the Conn Chan
20 21
const ChanBuffer = 10

22 23
// 1 MB
const MaxMessageSize = 1 << 20
24

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25 26 27 28 29
// msgioPipe is a pipe using msgio channels.
type msgioPipe struct {
	outgoing *msgio.Chan
	incoming *msgio.Chan
}
30

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
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

	// context + cancel
	ctx    context.Context
	cancel context.CancelFunc

	secure   *spipe.SecurePipe
	insecure *msgioPipe
50 51
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52 53 54 55 56 57 58 59 60 61 62 63 64
// newConn constructs a new connection
func newSingleConn(ctx context.Context, local, remote *peer.Peer,
	peers peer.Peerstore, maconn manet.Conn) (Conn, error) {

	ctx, cancel := context.WithCancel(ctx)

	conn := &singleConn{
		local:    local,
		remote:   remote,
		maconn:   maconn,
		ctx:      ctx,
		cancel:   cancel,
		insecure: newMsgioPipe(10),
65 66
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67 68 69 70 71
	log.Info("newSingleConn: %v to %v", local, remote)

	// setup the various io goroutines
	go conn.insecure.outgoing.WriteTo(maconn)
	go conn.insecure.incoming.ReadFrom(maconn, MaxMessageSize)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
72
	go conn.waitToClose()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73 74 75 76

	// perform secure handshake before returning this connection.
	if err := conn.secureHandshake(peers); err != nil {
		conn.Close()
77 78 79 80 81 82
		return nil, err
	}

	return conn, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83 84 85 86 87 88 89 90 91 92 93 94
// secureHandshake performs the spipe secure handshake.
func (c *singleConn) secureHandshake(peers peer.Peerstore) error {
	if c.secure != nil {
		return errors.New("Conn is already secured or being secured.")
	}

	// setup a Duplex pipe for spipe
	insecure := spipe.Duplex{
		In:  c.insecure.incoming.MsgChan,
		Out: c.insecure.outgoing.MsgChan,
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
95
	// spipe performs the secure handshake, which takes multiple RTT
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96
	sp, err := spipe.NewSecurePipe(c.ctx, 10, c.local, peers, insecure)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98 99 100
		return err
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101 102 103
	// assign it into the conn object
	c.secure = sp

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117
	if c.remote == nil {
		c.remote = c.secure.RemotePeer()

	} else if c.remote != c.secure.RemotePeer() {
		// this panic is here because this would be an insidious programmer error
		// that we need to ensure we catch.
		log.Error("%v != %v", c.remote, c.secure.RemotePeer())
		panic("peers not being constructed correctly.")
	}

	return nil
}

// waitToClose waits on the given context's Done before closing Conn.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118
func (c *singleConn) waitToClose() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
119
	select {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
120
	case <-c.ctx.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121 122 123 124 125 126 127
	}

	// close underlying connection
	c.maconn.Close()

	// closing channels
	c.insecure.outgoing.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
128 129 130
	if c.secure != nil { // may never have gotten here.
		c.secure.Close()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
131 132
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
133 134 135
// isClosed returns whether this Conn is open or closed.
func (c *singleConn) isClosed() bool {
	select {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136
	case <-c.ctx.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137 138 139 140
		return true
	default:
		return false
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141 142 143 144 145
}

// Close closes the connection, and associated channels.
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
146 147
	if c.isClosed() {
		return fmt.Errorf("connection already closed")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
	}

	// cancel context.
	c.cancel()
	return nil
}

// 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
165 166 167
// In returns a readable message channel
func (c *singleConn) In() <-chan []byte {
	return c.secure.In
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168 169
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170 171 172
// Out returns a writable message channel
func (c *singleConn) Out() chan<- []byte {
	return c.secure.Out
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
}

// 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
189
// Dial connects to a particular peer, over a given network
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190 191 192
// 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
193 194
	if laddr == nil {
		return nil, fmt.Errorf("No local address for network %s", network)
195
	}
196

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197 198 199 200 201 202
	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
203 204
	// madialer := manet.Dialer{LocalAddr: laddr}
	madialer := manet.Dialer{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206 207
	log.Info("%s dialing %s %s", d.LocalPeer, remote, raddr)
	maconn, err := madialer.Dial(raddr)
208 209 210
	if err != nil {
		return nil, err
	}
211

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
	if err := d.Peerstore.Put(remote); err != nil {
		log.Error("Error putting peer into peerstore: %s", remote)
	}

	return newSingleConn(ctx, d.LocalPeer, remote, d.Peerstore, maconn)
}

// 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

	// ctx + cancel func
	ctx    context.Context
	cancel context.CancelFunc
}

// waitToClose is needed to hand
func (l *listener) waitToClose() {
	select {
	case <-l.ctx.Done():
	}

	l.Listener.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
250 251 252 253
}

func (l *listener) isClosed() bool {
	select {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
254
	case <-l.ctx.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
255 256 257 258
		return true
	default:
		return false
	}
259 260
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
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) {
		c, err := newSingleConn(l.ctx, l.local, nil, l.peers, maconn)
		if err != nil {
			log.Error("Error accepting connection: %v", err)
		} else {
			l.conns <- c
		}
		<-sem // release
276
	}
277

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
278 279 280
	for {
		maconn, err := l.Listener.Accept()
		if err != nil {
281

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
282
			// if cancel is nil we're closed.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283
			if l.isClosed() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
284 285
				return // done.
			}
286

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
			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
}

// Close closes the listener.
// Any blocked Accept operations will be unblocked and return errors
func (l *listener) Close() error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
322 323 324 325
	if l.isClosed() {
		return errors.New("listener already closed")
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
326
	l.cancel()
327
	return nil
328 329
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
330 331 332 333 334 335 336 337
// 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) {

	ctx, cancel := context.WithCancel(ctx)

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
	// todo make this a variable
	chansize := 10

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

	go l.listen()
	go l.waitToClose()

	return l, nil
358
}