conn.go 6.66 KB
Newer Older
1 2 3 4 5 6
package swarm

import (
	"errors"
	"fmt"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	spipe "github.com/jbenet/go-ipfs/crypto/spipe"
8
	conn "github.com/jbenet/go-ipfs/net/conn"
Henry's avatar
Henry committed
9
	handshake "github.com/jbenet/go-ipfs/net/handshake"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10 11
	msg "github.com/jbenet/go-ipfs/net/message"

12
	proto "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
13
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
14
	manet "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/net"
15 16
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17 18 19 20 21 22 23 24 25 26 27 28 29
// Open listeners for each network the swarm should listen on
func (s *Swarm) listen() error {
	hasErr := false
	retErr := &ListenErr{
		Errors: make([]error, len(s.local.Addresses)),
	}

	// listen on every address
	for i, addr := range s.local.Addresses {
		err := s.connListen(addr)
		if err != nil {
			hasErr = true
			retErr.Errors[i] = err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30
			log.Error("Failed to listen on: %s - %s", addr, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31 32 33 34 35 36 37 38 39 40
		}
	}

	if hasErr {
		return retErr
	}
	return nil
}

// Listen for new connections on the given multiaddr
41
func (s *Swarm) connListen(maddr ma.Multiaddr) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42
	list, err := manet.Listen(maddr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43 44 45 46 47 48 49 50 51 52 53 54
	if err != nil {
		return err
	}

	// NOTE: this may require a lock around it later. currently, only run on setup
	s.listeners = append(s.listeners, list)

	// Accept and handle new connections on this listener until it errors
	go func() {
		for {
			nconn, err := list.Accept()
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55
				e := fmt.Errorf("Failed to accept connection: %s - %s", maddr, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
				s.errChan <- e

				// if cancel is nil, we're closed.
				if s.cancel == nil {
					return
				}
			} else {
				go s.handleIncomingConn(nconn)
			}
		}
	}()

	return nil
}

71
// Handle getting ID from this peer, handshake, and adding it into the map
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
72
func (s *Swarm) handleIncomingConn(nconn manet.Conn) {
73

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74
	addr := nconn.RemoteMultiaddr()
75

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76 77 78 79 80 81 82
	// Construct conn with nil peer for now, because we don't know its ID yet.
	// connSetup will figure this out, and pull out / construct the peer.
	c, err := conn.NewConn(nil, addr, nconn)
	if err != nil {
		s.errChan <- err
		return
	}
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

	// Setup the new connection
	err = s.connSetup(c)
	if err != nil && err != ErrAlreadyOpen {
		s.errChan <- err
		c.Close()
	}
}

// connSetup adds the passed in connection to its peerMap and starts
// the fanIn routine for that connection
func (s *Swarm) connSetup(c *conn.Conn) error {
	if c == nil {
		return errors.New("Tried to start nil connection.")
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
99
	if c.Peer != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
100
		log.Debug("Starting connection: %s", c.Peer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101
	} else {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
102
		log.Debug("Starting connection: [unknown peer]")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103
	}
104

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105 106 107
	if err := s.connSecure(c); err != nil {
		return fmt.Errorf("Conn securing error: %v", err)
	}
108

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109
	log.Debug("Secured connection: %s", c.Peer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111
	// add address of connection to Peer. Maybe it should happen in connSecure.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112 113
	c.Peer.AddAddress(c.Addr)

114 115 116 117
	if err := s.connVersionExchange(c); err != nil {
		return fmt.Errorf("Conn version exchange error: %v", err)
	}

118 119 120
	// add to conns
	s.connsLock.Lock()
	if _, ok := s.conns[c.Peer.Key()]; ok {
Jeromy's avatar
Jeromy committed
121
		log.Debug("Conn already open!")
122 123 124 125
		s.connsLock.Unlock()
		return ErrAlreadyOpen
	}
	s.conns[c.Peer.Key()] = c
Jeromy's avatar
Jeromy committed
126
	log.Debug("Added conn to map!")
127 128 129 130 131 132 133
	s.connsLock.Unlock()

	// kick off reader goroutine
	go s.fanIn(c)
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134 135 136
// connSecure setups a secure remote connection.
func (s *Swarm) connSecure(c *conn.Conn) error {

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137
	sp, err := spipe.NewSecurePipe(s.ctx, 10, s.local, s.peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
138 139 140 141 142 143 144 145 146 147 148
	if err != nil {
		return err
	}

	err = sp.Wrap(s.ctx, spipe.Duplex{
		In:  c.Incoming.MsgChan,
		Out: c.Outgoing.MsgChan,
	})
	if err != nil {
		return err
	}
149

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150 151 152 153 154 155 156
	if c.Peer == nil {
		c.Peer = sp.RemotePeer()

	} else if c.Peer != sp.RemotePeer() {
		panic("peers not being constructed correctly.")
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157
	c.Secure = sp
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
	return nil
159
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
160

161 162 163
// connVersionExchange exchanges local and remote versions and compares them
// closes remote and returns an error in case of major difference
func (s *Swarm) connVersionExchange(remote *conn.Conn) error {
Henry's avatar
Henry committed
164 165
	var remoteVersion, myVersion *handshake.SemVer
	myVersion = handshake.Current()
166

Henry's avatar
Henry committed
167
	// BUG(cryptix): do we need to use a NetMessage here?
168 169 170 171 172
	myVersionMsg, err := msg.FromObject(s.local, myVersion)
	if err != nil {
		return fmt.Errorf("connVersionExchange: could not prepare local version: %q", err)
	}

Henry's avatar
Henry committed
173 174 175 176
	// buffered channel to send our version just once
	outBuf := make(chan []byte, 1)
	outBuf <- myVersionMsg.Data()

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
	var gotTheirs, sendMine bool
	for {
		if gotTheirs && sendMine {
			break
		}

		select {
		case <-s.ctx.Done():
			// close Conn.
			remote.Close()
			return nil // BUG(cryptix): should this be an error?

		case <-remote.Closed:
			return errors.New("remote closed connection during version exchange")

Henry's avatar
Henry committed
192 193 194 195 196
		case our, ok := <-outBuf:
			if ok {
				remote.Secure.Out <- our
				sendMine = true
				close(outBuf) // only send local version once
197
				log.Debug("Send my version(%s) [to = %s]", myVersion, remote.Peer)
Henry's avatar
Henry committed
198
			}
199 200 201 202 203 204

		case data, ok := <-remote.Secure.In:
			if !ok {
				return fmt.Errorf("Error retrieving from conn: %v", remote.Peer)
			}

Henry's avatar
Henry committed
205
			remoteVersion = new(handshake.SemVer)
206 207 208 209 210 211
			err = proto.Unmarshal(data, remoteVersion)
			if err != nil {
				s.Close()
				return fmt.Errorf("connSetup: could not decode remote version: %q", err)
			}
			gotTheirs = true
212
			log.Debug("Received remote version(%s) [from = %s]", remoteVersion, remote.Peer)
Henry's avatar
Henry committed
213 214

			// BUG(cryptix): could add another case here to trigger resending our version
215 216 217
		}
	}

Henry's avatar
Henry committed
218
	if !handshake.Compatible(myVersion, remoteVersion) {
Henry's avatar
Henry committed
219 220 221 222
		remote.Close()
		return errors.New("protocol missmatch")
	}

223
	log.Debug("[peer: %s] Version compatible", remote.Peer)
Henry's avatar
Henry committed
224
	return nil
225 226
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227 228 229 230 231 232 233 234 235 236 237 238 239
// Handles the unwrapping + sending of messages to the right connection.
func (s *Swarm) fanOut() {
	for {
		select {
		case <-s.ctx.Done():
			return // told to close.

		case msg, ok := <-s.Outgoing:
			if !ok {
				return
			}

			s.connsLock.RLock()
240
			conn, found := s.conns[msg.Peer().Key()]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241 242 243 244 245 246 247 248 249
			s.connsLock.RUnlock()

			if !found {
				e := fmt.Errorf("Sent msg to peer without open conn: %v",
					msg.Peer)
				s.errChan <- e
				continue
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
250
			// log.Debug("[peer: %s] Sent message [to = %s]", s.local, msg.Peer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
251

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252
			// queue it in the connection's buffer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
253
			conn.Secure.Out <- msg.Data()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
		}
	}
}

// Handles the receiving + wrapping of messages, per conn.
// Consider using reflect.Select with one goroutine instead of n.
func (s *Swarm) fanIn(c *conn.Conn) {
	for {
		select {
		case <-s.ctx.Done():
			// close Conn.
			c.Close()
			goto out

		case <-c.Closed:
			goto out

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
271
		case data, ok := <-c.Secure.In:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
272
			if !ok {
273
				e := fmt.Errorf("Error retrieving from conn: %v", c.Peer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
274 275 276 277
				s.errChan <- e
				goto out
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
278
			// log.Debug("[peer: %s] Received message [from = %s]", s.local, c.Peer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
279

280
			msg := msg.New(c.Peer, data)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
281 282 283 284 285 286 287 288 289
			s.Incoming <- msg
		}
	}

out:
	s.connsLock.Lock()
	delete(s.conns, c.Peer.Key())
	s.connsLock.Unlock()
}