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

import (
	"errors"
	"fmt"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6 7
	"net"
	"syscall"
8

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20 21 22 23 24 25 26 27 28 29 30 31
// 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
32
			log.Error("Failed to listen on: %s - %s", addr, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33 34 35 36 37 38 39 40 41 42
		}
	}

	if hasErr {
		return retErr
	}
	return nil
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
49 50 51 52 53
	// make sure port can be reused. TOOD this doesn't work...
	// if err := setSocketReuse(list); err != nil {
	// 	return err
	// }

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54 55 56 57 58 59 60 61
	// 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
62
				e := fmt.Errorf("Failed to accept connection: %s - %s", maddr, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
				s.errChan <- e

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

	return nil
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83
	c, err := conn.NewConn(s.local, nil, nconn)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84 85 86 87
	if err != nil {
		s.errChan <- err
		return
	}
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

	// 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
104 105
	if c.Remote != nil {
		log.Debug("%s Starting connection: %s", c.Local, c.Remote)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106
	} else {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107
		log.Debug("%s Starting connection: [unknown peer]", c.Local)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
108
	}
109

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114
	log.Debug("%s secured connection: %s", c.Local, c.Remote)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116
	// add address of connection to Peer. Maybe it should happen in connSecure.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117
	c.Remote.AddAddress(c.Conn.RemoteMultiaddr())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118

119 120 121 122
	if err := s.connVersionExchange(c); err != nil {
		return fmt.Errorf("Conn version exchange error: %v", err)
	}

123 124
	// add to conns
	s.connsLock.Lock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125
	if _, ok := s.conns[c.Remote.Key()]; ok {
Jeromy's avatar
Jeromy committed
126
		log.Debug("Conn already open!")
127 128 129
		s.connsLock.Unlock()
		return ErrAlreadyOpen
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130
	s.conns[c.Remote.Key()] = c
Jeromy's avatar
Jeromy committed
131
	log.Debug("Added conn to map!")
132 133 134 135 136 137 138
	s.connsLock.Unlock()

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142
	sp, err := spipe.NewSecurePipe(s.ctx, 10, s.local, s.peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143 144 145 146 147 148 149 150 151 152 153
	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
	}
154

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155 156
	if c.Remote == nil {
		c.Remote = sp.RemotePeer()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
	} else if c.Remote != sp.RemotePeer() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159 160 161
		panic("peers not being constructed correctly.")
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162
	c.Secure = sp
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163
	return nil
164
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165

166 167 168
// 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
169 170
	var remoteHandshake, localHandshake *handshake.Handshake1
	localHandshake = handshake.CurrentHandshake()
171

Henry's avatar
Henry committed
172
	myVerBytes, err := proto.Marshal(localHandshake)
173
	if err != nil {
Henry's avatar
Henry committed
174
		return err
175 176
	}

Henry's avatar
Henry committed
177
	remote.Secure.Out <- myVerBytes
Henry's avatar
Henry committed
178

Henry's avatar
Henry committed
179
	log.Debug("Send my version(%s) [to = %s]", localHandshake, remote.Peer)
180

Henry's avatar
Henry committed
181 182 183
	select {
	case <-s.ctx.Done():
		return s.ctx.Err()
184

Henry's avatar
Henry committed
185 186
	case <-remote.Closed:
		return errors.New("remote closed connection during version exchange")
187

Henry's avatar
Henry committed
188 189 190 191
	case data, ok := <-remote.Secure.In:
		if !ok {
			return fmt.Errorf("Error retrieving from conn: %v", remote.Peer)
		}
Henry's avatar
Henry committed
192

Henry's avatar
Henry committed
193 194 195 196 197
		remoteHandshake = new(handshake.Handshake1)
		err = proto.Unmarshal(data, remoteHandshake)
		if err != nil {
			s.Close()
			return fmt.Errorf("connSetup: could not decode remote version: %q", err)
198
		}
Henry's avatar
Henry committed
199 200

		log.Debug("Received remote version(%s) [from = %s]", remoteHandshake, remote.Peer)
201 202
	}

Henry's avatar
Henry committed
203 204
	if err := handshake.Compatible(localHandshake, remoteHandshake); err != nil {
		log.Info("%s (%s) incompatible version with %s (%s)", s.local, localHandshake, remote.Peer, remoteHandshake)
Henry's avatar
Henry committed
205
		remote.Close()
Henry's avatar
Henry committed
206
		return err
Henry's avatar
Henry committed
207 208
	}

209
	log.Debug("[peer: %s] Version compatible", remote.Peer)
Henry's avatar
Henry committed
210
	return nil
211 212
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213 214 215 216 217 218 219 220 221 222 223 224 225
// 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()
226
			conn, found := s.conns[msg.Peer().Key()]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227 228 229 230 231 232 233 234 235
			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
236
			// log.Debug("[peer: %s] Sent message [to = %s]", s.local, msg.Peer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
238
			// queue it in the connection's buffer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239
			conn.Secure.Out <- msg.Data()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
		}
	}
}

// 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
257
		case data, ok := <-c.Secure.In:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
258
			if !ok {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
259
				e := fmt.Errorf("Error retrieving from conn: %v", c.Remote)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
260 261 262 263
				s.errChan <- e
				goto out
			}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
266
			msg := msg.New(c.Remote, data)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
267 268 269 270 271 272
			s.Incoming <- msg
		}
	}

out:
	s.connsLock.Lock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
273
	delete(s.conns, c.Remote.Key())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
274 275
	s.connsLock.Unlock()
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298

func setSocketReuse(l manet.Listener) error {
	nl := l.NetListener()

	// for now only TCP. TODO change this when more networks.
	file, err := nl.(*net.TCPListener).File()
	if err != nil {
		return err
	}

	fd := file.Fd()
	err = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
	if err != nil {
		return err
	}

	err = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEPORT, 1)
	if err != nil {
		return err
	}

	return nil
}