conn.go 5.25 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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39
	list, err := conn.Listen(s.Context(), 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
	// 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
53 54
	// this listener is a child.
	s.Children().Add(1)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55
	go func() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56 57
		defer s.Children().Done()

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

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

	return nil
}

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

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

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

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

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

102 103
	// add to conns
	s.connsLock.Lock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104 105 106 107 108 109 110 111 112 113 114 115 116

	mc, ok := s.conns[c.RemotePeer().Key()]
	if !ok {
		// 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 {
			log.Error("error creating multiconn: %s", err)
			c.Close()
			return nil, err
		}

		s.conns[c.RemotePeer().Key()] = mc
117
		s.connsLock.Unlock()
118

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
119 120 121 122 123 124
		log.Debug("added new multiconn: %s", mc)
	} else {
		s.connsLock.Unlock() // unlock before adding new conn

		mc.Add(c)
		log.Debug("multiconn found: %s", mc)
125
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126 127

	log.Debug("multiconn added new conn %s", c)
128 129

	// kick off reader goroutine
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130
	go s.fanInSingle(c)
131
	return c, nil
132 133
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134 135
// Handles the unwrapping + sending of messages to the right connection.
func (s *Swarm) fanOut() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136 137 138
	s.Children().Add(1)
	defer s.Children().Done()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139
	i := 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140 141
	for {
		select {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142
		case <-s.Closing():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143 144 145 146
			return // told to close.

		case msg, ok := <-s.Outgoing:
			if !ok {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
147
				log.Info("%s outgoing channel closed", s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148 149 150 151
				return
			}

			s.connsLock.RLock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
152
			c, found := s.conns[msg.Peer().Key()]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153 154 155
			s.connsLock.RUnlock()

			if !found {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156
				e := fmt.Errorf("Sent msg to peer without open conn: %v", msg.Peer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157
				s.errChan <- e
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
				log.Error("%s", e)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159 160 161
				continue
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162 163
			i++
			log.Debug("%s sent message to %s (%d)", s.local, msg.Peer(), i)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164
			// queue it in the connection's buffer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165
			c.Out() <- msg.Data()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166 167 168 169 170 171
		}
	}
}

// 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
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
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
187
	i := 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188 189
	for {
		select {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190 191 192 193 194
		case <-s.Closing(): // Swarm closing
			return

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
196
		case data, ok := <-c.In():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197
			if !ok {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
198
				log.Info("%s in channel closed", c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
199
				return // channel closed.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
200
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201 202
			i++
			log.Debug("%s received message from %s (%d)", s.local, c.RemotePeer(), i)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203
			s.Incoming <- msg.New(c.RemotePeer(), data)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204 205 206
		}
	}
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
// 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
// }