conn.go 5.55 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"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
11
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
12 13
)

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

	// listen on every address
22
	for i, addr := range s.local.Addresses() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
23 24 25 26
		err := s.connListen(addr)
		if err != nil {
			hasErr = true
			retErr.Errors[i] = err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27
			log.Errorf("Failed to listen on: %s - %s", addr, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
28 29 30 31 32 33 34 35 36 37
		}
	}

	if hasErr {
		return retErr
	}
	return nil
}

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
45 46 47 48 49
	// 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
50 51 52 53
	// 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
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54 55
	// this listener is a child.
	s.Children().Add(1)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56
	go func() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57 58
		defer s.Children().Done()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
59
		for {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60
			select {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61
			case <-s.Closing():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62
				return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64
			case conn := <-list.Accept():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66
				// handler also a child.
				s.Children().Add(1)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67
				go s.handleIncomingConn(conn)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68 69 70 71 72 73 74
			}
		}
	}()

	return nil
}

75
// Handle getting ID from this peer, handshake, and adding it into the map
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76
func (s *Swarm) handleIncomingConn(nconn conn.Conn) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77 78
	// this handler is a child. added by caller.
	defer s.Children().Done()
79 80

	// Setup the new connection
81
	_, err := s.connSetup(nconn)
82 83
	if err != nil && err != ErrAlreadyOpen {
		s.errChan <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84
		nconn.Close()
85 86 87 88
	}
}

// connSetup adds the passed in connection to its peerMap and starts
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
89
// the fanInSingle routine for that connection
90
func (s *Swarm) connSetup(c conn.Conn) (conn.Conn, error) {
91
	if c == nil {
92
		return nil, errors.New("Tried to start nil connection.")
93 94
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
	// add address of connection to Peer. Maybe it should happen in connSecure.
98 99 100 101
	// 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
102

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103 104 105 106 107 108 109
	// handshake3
	ctxT, _ := context.WithTimeout(c.Context(), conn.HandshakeTimeout)
	if err := conn.Handshake3(ctxT, c); err != nil {
		c.Close()
		return nil, fmt.Errorf("Handshake3 failed: %s", err)
	}

110 111
	// add to conns
	s.connsLock.Lock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
113 114
	mc, found := s.conns[c.RemotePeer().Key()]
	if !found {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115 116 117 118
		// multiconn doesn't exist, make a new one.
		conns := []conn.Conn{c}
		mc, err := conn.NewMultiConn(s.Context(), s.local, c.RemotePeer(), conns)
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
119
			log.Errorf("error creating multiconn: %s", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
120 121 122 123 124
			c.Close()
			return nil, err
		}

		s.conns[c.RemotePeer().Key()] = mc
125
		s.connsLock.Unlock()
126

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127 128
		// kick off reader goroutine
		go s.fanInSingle(mc)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129
		log.Debugf("added new multiconn: %s", mc)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130 131 132 133
	} else {
		s.connsLock.Unlock() // unlock before adding new conn

		mc.Add(c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134
		log.Debugf("multiconn found: %s", mc)
135
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137
	log.Debugf("multiconn added new conn %s", c)
138
	return c, nil
139 140
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141 142
// Handles the unwrapping + sending of messages to the right connection.
func (s *Swarm) fanOut() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143 144 145
	s.Children().Add(1)
	defer s.Children().Done()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146
	i := 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
147 148
	for {
		select {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149
		case <-s.Closing():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150 151 152 153
			return // told to close.

		case msg, ok := <-s.Outgoing:
			if !ok {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154
				log.Infof("%s outgoing channel closed", s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155 156 157 158
				return
			}

			s.connsLock.RLock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159
			c, found := s.conns[msg.Peer().Key()]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
160 161 162
			s.connsLock.RUnlock()

			if !found {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163
				e := fmt.Errorf("Sent msg to peer without open conn: %v", msg.Peer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164
				s.errChan <- e
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165
				log.Error(e)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166 167 168
				continue
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169
			i++
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170
			log.Debugf("%s sent message to %s (%d)", s.local, msg.Peer(), i)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171
			// queue it in the connection's buffer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172
			c.Out() <- msg.Data()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173 174 175 176 177 178
		}
	}
}

// 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
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
func (s *Swarm) fanInSingle(c conn.Conn) {
	s.Children().Add(1)
	c.Children().Add(1) // child of Conn as well.

	// cleanup all data associated with this child Connection.
	defer func() {
		// remove it from the map.
		s.connsLock.Lock()
		delete(s.conns, c.RemotePeer().Key())
		s.connsLock.Unlock()

		s.Children().Done()
		c.Children().Done() // child of Conn as well.
	}()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194
	i := 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
195 196
	for {
		select {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197 198 199 200 201
		case <-s.Closing(): // Swarm closing
			return

		case <-c.Closing(): // Conn closing
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203
		case data, ok := <-c.In():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204
			if !ok {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205
				log.Infof("%s in channel closed", c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206
				return // channel closed.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208
			i++
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209
			log.Debugf("%s received message from %s (%d)", s.local, c.RemotePeer(), i)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
210
			s.Incoming <- msg.New(c.RemotePeer(), data)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
211 212 213
		}
	}
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
// 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
// }