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

import (
	"errors"
	"fmt"

	conn "github.com/jbenet/go-ipfs/net/conn"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8 9
	msg "github.com/jbenet/go-ipfs/net/message"

10
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
11 12
)

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

	if hasErr {
		return retErr
	}
	return nil
}

// Listen for new connections on the given multiaddr
37
func (s *Swarm) connListen(maddr ma.Multiaddr) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38 39

	list, err := conn.Listen(s.ctx, maddr, s.local, s.peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40 41 42 43
	if err != nil {
		return err
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44 45 46 47 48
	// 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
49 50 51 52 53 54
	// 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 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55 56 57
			select {
			case <-s.ctx.Done():
				return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
59 60
			case conn := <-list.Accept():
				go s.handleIncomingConn(conn)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61 62 63 64 65 66 67
			}
		}
	}()

	return nil
}

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

	// Setup the new connection
72
	_, err := s.connSetup(nconn)
73 74
	if err != nil && err != ErrAlreadyOpen {
		s.errChan <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75
		nconn.Close()
76 77 78 79 80
	}
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
86
	log.Debug("%s Started connection: %s", c.LocalPeer(), c.RemotePeer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88
	// add address of connection to Peer. Maybe it should happen in connSecure.
89 90 91 92
	// NOT adding this address here, because the incoming address in TCP
	// is an EPHEMERAL address, and not the address we want to keep around.
	// addresses should be figured out through the DHT.
	// c.Remote.AddAddress(c.Conn.RemoteMultiaddr())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93

94 95
	// add to conns
	s.connsLock.Lock()
96
	if c2, ok := s.conns[c.RemotePeer().Key()]; ok {
Jeromy's avatar
Jeromy committed
97
		log.Debug("Conn already open!")
98
		s.connsLock.Unlock()
99 100 101 102

		c.Close()
		return c2, nil // not error anymore, use existing conn.
		// return ErrAlreadyOpen
103
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104
	s.conns[c.RemotePeer().Key()] = c
Jeromy's avatar
Jeromy committed
105
	log.Debug("Added conn to map!")
106 107 108 109
	s.connsLock.Unlock()

	// kick off reader goroutine
	go s.fanIn(c)
110
	return c, nil
111 112
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
113 114 115 116 117 118 119 120 121 122 123 124 125
// 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()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126
			c, found := s.conns[msg.Peer().Key()]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127 128 129 130 131 132 133 134 135
			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
136
			// log.Debug("[peer: %s] Sent message [to = %s]", s.local, msg.Peer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
138
			// queue it in the connection's buffer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139
			c.Out() <- msg.Data()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140 141 142 143 144 145
		}
	}
}

// Handles the receiving + wrapping of messages, per conn.
// Consider using reflect.Select with one goroutine instead of n.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146
func (s *Swarm) fanIn(c conn.Conn) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
147 148 149 150 151 152 153
	for {
		select {
		case <-s.ctx.Done():
			// close Conn.
			c.Close()
			goto out

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154
		case data, ok := <-c.In():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155
			if !ok {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156
				e := fmt.Errorf("Error retrieving from conn: %v", c.RemotePeer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157 158 159 160
				s.errChan <- e
				goto out
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161
			// log.Debug("[peer: %s] Received message [from = %s]", s.local, c.Peer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162
			s.Incoming <- msg.New(c.RemotePeer(), data)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163 164 165 166 167
		}
	}

out:
	s.connsLock.Lock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168
	delete(s.conns, c.RemotePeer().Key())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169 170
	s.connsLock.Unlock()
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
// Commenting out because it's platform specific
// 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
// }