swarm.go 12.4 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package swarm

import (
4
	"context"
Steven Allen's avatar
Steven Allen committed
5
	"errors"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	"fmt"
7
	"strings"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	"sync"
Steven Allen's avatar
Steven Allen committed
9
	"sync/atomic"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10 11
	"time"

12 13 14 15 16 17
	"github.com/libp2p/go-libp2p-core/metrics"
	"github.com/libp2p/go-libp2p-core/network"
	"github.com/libp2p/go-libp2p-core/peer"
	"github.com/libp2p/go-libp2p-core/peerstore"
	"github.com/libp2p/go-libp2p-core/transport"

Jeromy's avatar
Jeromy committed
18 19 20
	logging "github.com/ipfs/go-log"
	"github.com/jbenet/goprocess"
	goprocessctx "github.com/jbenet/goprocess/context"
21

Jeromy's avatar
Jeromy committed
22
	filter "github.com/libp2p/go-maddr-filter"
23
	ma "github.com/multiformats/go-multiaddr"
Jeromy's avatar
Jeromy committed
24
	mafilter "github.com/whyrusleeping/multiaddr-filter"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25 26
)

27 28
// DialTimeoutLocal is the maximum duration a Dial to local network address
// is allowed to take.
Steven Allen's avatar
Steven Allen committed
29 30
// This includes the time between dialing the raw network connection,
// protocol selection as well the handshake, if applicable.
31
var DialTimeoutLocal = 5 * time.Second
32

Steven Allen's avatar
Steven Allen committed
33
var log = logging.Logger("swarm2")
34

Steven Allen's avatar
Steven Allen committed
35 36
// ErrSwarmClosed is returned when one attempts to operate on a closed swarm.
var ErrSwarmClosed = errors.New("swarm closed")
37

Steven Allen's avatar
Steven Allen committed
38 39 40 41
// ErrAddrFiltered is returned when trying to register a connection to a
// filtered address. You shouldn't see this error unless some underlying
// transport is misbehaving.
var ErrAddrFiltered = errors.New("address filtered")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42

43 44 45
// ErrDialTimeout is returned when one a dial times out due to the global timeout
var ErrDialTimeout = errors.New("dial timed out")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46 47 48 49 50
// Swarm is a connection muxer, allowing connections to other peers to
// be opened and closed, while still using the same Chan for all
// communication. The Chan sends/receives Messages, which note the
// destination or source Peer.
type Swarm struct {
Steven Allen's avatar
Steven Allen committed
51 52 53 54
	// Close refcount. This allows us to fully wait for the swarm to be torn
	// down before continuing.
	refs sync.WaitGroup

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55
	local peer.ID
56
	peers peerstore.Peerstore
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57

Steven Allen's avatar
Steven Allen committed
58 59 60 61
	conns struct {
		sync.RWMutex
		m map[peer.ID][]*Conn
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62

Steven Allen's avatar
Steven Allen committed
63 64
	listeners struct {
		sync.RWMutex
65

66 67
		ifaceListenAddres []ma.Multiaddr
		cacheEOL          time.Time
68

Steven Allen's avatar
Steven Allen committed
69 70
		m map[transport.Listener]struct{}
	}
Jeromy's avatar
Jeromy committed
71

Steven Allen's avatar
Steven Allen committed
72 73
	notifs struct {
		sync.RWMutex
74
		m map[network.Notifiee]struct{}
Steven Allen's avatar
Steven Allen committed
75
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76

Steven Allen's avatar
Steven Allen committed
77 78 79 80
	transports struct {
		sync.RWMutex
		m map[int]transport.Transport
	}
Jeromy's avatar
Jeromy committed
81

Steven Allen's avatar
Steven Allen committed
82 83 84
	// new connection and stream handlers
	connh   atomic.Value
	streamh atomic.Value
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
85

Steven Allen's avatar
Steven Allen committed
86 87 88 89 90 91 92
	// dialing helpers
	dsync   *DialSync
	backf   DialBackoff
	limiter *dialLimiter

	// filters for addresses that shouldnt be dialed (or accepted)
	Filters *filter.Filters
Jeromy's avatar
Jeromy committed
93

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
94 95 96
	proc goprocess.Process
	ctx  context.Context
	bwc  metrics.Reporter
97 98
}

Steven Allen's avatar
Steven Allen committed
99
// NewSwarm constructs a Swarm
100
func NewSwarm(ctx context.Context, local peer.ID, peers peerstore.Peerstore, bwc metrics.Reporter) *Swarm {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101
	s := &Swarm{
Steven Allen's avatar
Steven Allen committed
102 103 104 105
		local:   local,
		peers:   peers,
		bwc:     bwc,
		Filters: filter.NewFilters(),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106
	}
Steven Allen's avatar
Steven Allen committed
107 108 109 110

	s.conns.m = make(map[peer.ID][]*Conn)
	s.listeners.m = make(map[transport.Listener]struct{})
	s.transports.m = make(map[int]transport.Transport)
111
	s.notifs.m = make(map[network.Notifiee]struct{})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112

113
	s.dsync = NewDialSync(s.doDial)
Jeromy's avatar
Jeromy committed
114
	s.limiter = newDialLimiter(s.dialAddr)
115
	s.proc = goprocessctx.WithContext(ctx)
Steven Allen's avatar
Steven Allen committed
116
	s.ctx = goprocessctx.OnClosingContext(s.proc)
Jeromy's avatar
Jeromy committed
117

118 119 120 121
	// Set teardown after setting the context/process so we don't start the
	// teardown process early.
	s.proc.SetTeardown(s.teardown)

Steven Allen's avatar
Steven Allen committed
122
	return s
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123 124
}

Steven Allen's avatar
Steven Allen committed
125
func (s *Swarm) teardown() error {
126 127 128 129 130
	// Wait for the context to be canceled.
	// This allows other parts of the swarm to detect that we're shutting
	// down.
	<-s.ctx.Done()

Steven Allen's avatar
Steven Allen committed
131 132 133 134 135 136 137 138 139 140 141 142
	// Prevents new connections and/or listeners from being added to the swarm.

	s.listeners.Lock()
	listeners := s.listeners.m
	s.listeners.m = nil
	s.listeners.Unlock()

	s.conns.Lock()
	conns := s.conns.m
	s.conns.m = nil
	s.conns.Unlock()

Matt Joiner's avatar
Matt Joiner committed
143 144
	// Lots of goroutines but we might as well do this in parallel. We want to shut down as fast as
	// possible.
Steven Allen's avatar
Steven Allen committed
145 146 147 148 149 150 151

	for l := range listeners {
		go func(l transport.Listener) {
			if err := l.Close(); err != nil {
				log.Errorf("error when shutting down listener: %s", err)
			}
		}(l)
152 153
	}

Steven Allen's avatar
Steven Allen committed
154 155 156 157 158 159 160 161 162
	for _, cs := range conns {
		for _, c := range cs {
			go func(c *Conn) {
				if err := c.Close(); err != nil {
					log.Errorf("error when shutting down connection: %s", err)
				}
			}(c)
		}
	}
163

Steven Allen's avatar
Steven Allen committed
164 165
	// Wait for everything to finish.
	s.refs.Wait()
166

Steven Allen's avatar
Steven Allen committed
167
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168 169
}

Matt Joiner's avatar
Matt Joiner committed
170 171
// AddAddrFilter adds a multiaddr filter to the set of filters the swarm will use to determine which
// addresses not to dial to.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172 173 174 175 176 177 178 179 180
func (s *Swarm) AddAddrFilter(f string) error {
	m, err := mafilter.NewMask(f)
	if err != nil {
		return err
	}

	s.Filters.AddDialFilter(m)
	return nil
}
Jeromy's avatar
Jeromy committed
181

Steven Allen's avatar
Steven Allen committed
182 183 184 185 186
// Process returns the Process of the swarm
func (s *Swarm) Process() goprocess.Process {
	return s.proc
}

187
func (s *Swarm) addConn(tc transport.CapableConn, dir network.Direction) (*Conn, error) {
Steven Allen's avatar
Steven Allen committed
188 189 190 191 192 193
	// The underlying transport (or the dialer) *should* filter it's own
	// connections but we should double check anyways.
	raddr := tc.RemoteMultiaddr()
	if s.Filters.AddrBlocked(raddr) {
		tc.Close()
		return nil, ErrAddrFiltered
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194
	}
Jeromy's avatar
Jeromy committed
195

Steven Allen's avatar
Steven Allen committed
196
	p := tc.RemotePeer()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197

Steven Allen's avatar
Steven Allen committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
	// Add the public key.
	if pk := tc.RemotePublicKey(); pk != nil {
		s.peers.AddPubKey(p, pk)
	}

	// Clear any backoffs
	s.backf.Clear(p)

	// Finally, add the peer.
	s.conns.Lock()
	// Check if we're still online
	if s.conns.m == nil {
		s.conns.Unlock()
		tc.Close()
		return nil, ErrSwarmClosed
	}

	// Wrap and register the connection.
216
	stat := network.Stat{Direction: dir}
Steven Allen's avatar
Steven Allen committed
217 218 219
	c := &Conn{
		conn:  tc,
		swarm: s,
220
		stat:  stat,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221
	}
Steven Allen's avatar
Steven Allen committed
222 223 224 225 226 227 228 229
	c.streams.m = make(map[*Stream]struct{})
	s.conns.m[p] = append(s.conns.m[p], c)

	// Add two swarm refs:
	// * One will be decremented after the close notifications fire in Conn.doClose
	// * The other will be decremented when Conn.start exits.
	s.refs.Add(2)

230 231 232
	// Take the notification lock before releasing the conns lock to block
	// Disconnect notifications until after the Connect notifications done.
	c.notifyLk.Lock()
Steven Allen's avatar
Steven Allen committed
233 234 235 236
	s.conns.Unlock()

	// We have a connection now. Cancel all other in-progress dials.
	// This should be fast, no reason to wait till later.
237 238 239
	if dir == network.DirOutbound {
		s.dsync.CancelDial(p)
	}
Steven Allen's avatar
Steven Allen committed
240

241
	s.notifyAll(func(f network.Notifiee) {
Steven Allen's avatar
Steven Allen committed
242 243
		f.Connected(s, c)
	})
244
	c.notifyLk.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245

Steven Allen's avatar
Steven Allen committed
246 247 248 249 250 251 252 253 254 255
	c.start()

	// TODO: Get rid of this. We use it for identify but that happen much
	// earlier (really, inside the transport and, if not then, during the
	// notifications).
	if h := s.ConnHandler(); h != nil {
		go h(c)
	}

	return c, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256 257
}

Steven Allen's avatar
Steven Allen committed
258
// Peerstore returns this swarms internal Peerstore.
259
func (s *Swarm) Peerstore() peerstore.Peerstore {
Steven Allen's avatar
Steven Allen committed
260
	return s.peers
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
261 262 263 264 265 266 267 268 269 270 271 272
}

// Context returns the context of the swarm
func (s *Swarm) Context() context.Context {
	return s.ctx
}

// Close stops the Swarm.
func (s *Swarm) Close() error {
	return s.proc.Close()
}

Steven Allen's avatar
Steven Allen committed
273
// TODO: We probably don't need the conn handlers.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
274 275

// SetConnHandler assigns the handler for new connections.
Steven Allen's avatar
Steven Allen committed
276
// You will rarely use this. See SetStreamHandler
277
func (s *Swarm) SetConnHandler(handler network.ConnHandler) {
Steven Allen's avatar
Steven Allen committed
278 279
	s.connh.Store(handler)
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
280

Steven Allen's avatar
Steven Allen committed
281
// ConnHandler gets the handler for new connections.
282 283
func (s *Swarm) ConnHandler() network.ConnHandler {
	handler, _ := s.connh.Load().(network.ConnHandler)
Steven Allen's avatar
Steven Allen committed
284
	return handler
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
285 286 287
}

// SetStreamHandler assigns the handler for new streams.
288
func (s *Swarm) SetStreamHandler(handler network.StreamHandler) {
Steven Allen's avatar
Steven Allen committed
289 290 291 292
	s.streamh.Store(handler)
}

// StreamHandler gets the handler for new streams.
293 294
func (s *Swarm) StreamHandler() network.StreamHandler {
	handler, _ := s.streamh.Load().(network.StreamHandler)
Steven Allen's avatar
Steven Allen committed
295 296 297 298 299
	return handler
}

// NewStream creates a new stream on any available connection to peer, dialing
// if necessary.
300
func (s *Swarm) NewStream(ctx context.Context, p peer.ID) (network.Stream, error) {
Steven Allen's avatar
Steven Allen committed
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
	log.Debugf("[%s] opening stream to peer [%s]", s.local, p)

	// Algorithm:
	// 1. Find the best connection, otherwise, dial.
	// 2. Try opening a stream.
	// 3. If the underlying connection is, in fact, closed, close the outer
	//    connection and try again. We do this in case we have a closed
	//    connection but don't notice it until we actually try to open a
	//    stream.
	//
	// Note: We only dial once.
	//
	// TODO: Try all connections even if we get an error opening a stream on
	// a non-closed connection.
	dials := 0
	for {
		c := s.bestConnToPeer(p)
		if c == nil {
319 320
			if nodial, _ := network.GetNoDial(ctx); nodial {
				return nil, network.ErrNoConn
321 322
			}

Steven Allen's avatar
Steven Allen committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
			if dials >= DialAttempts {
				return nil, errors.New("max dial attempts exceeded")
			}
			dials++

			var err error
			c, err = s.dialPeer(ctx, p)
			if err != nil {
				return nil, err
			}
		}
		s, err := c.NewStream()
		if err != nil {
			if c.conn.IsClosed() {
				continue
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
339 340
			return nil, err
		}
Steven Allen's avatar
Steven Allen committed
341
		return s, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
342 343 344
	}
}

Steven Allen's avatar
Steven Allen committed
345
// ConnsToPeer returns all the live connections to peer.
346
func (s *Swarm) ConnsToPeer(p peer.ID) []network.Conn {
Steven Allen's avatar
Steven Allen committed
347 348 349 350 351
	// TODO: Consider sorting the connection list best to worst. Currently,
	// it's sorted oldest to newest.
	s.conns.RLock()
	defer s.conns.RUnlock()
	conns := s.conns.m[p]
352
	output := make([]network.Conn, len(conns))
Steven Allen's avatar
Steven Allen committed
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
	for i, c := range conns {
		output[i] = c
	}
	return output
}

// bestConnToPeer returns the best connection to peer.
func (s *Swarm) bestConnToPeer(p peer.ID) *Conn {
	// Selects the best connection we have to the peer.
	// TODO: Prefer some transports over others. Currently, we just select
	// the newest non-closed connection with the most streams.
	s.conns.RLock()
	defer s.conns.RUnlock()

	var best *Conn
	bestLen := 0
	for _, c := range s.conns.m[p] {
		if c.conn.IsClosed() {
			// We *will* garbage collect this soon anyways.
			continue
		}
		c.streams.Lock()
		cLen := len(c.streams.m)
		c.streams.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
377

Steven Allen's avatar
Steven Allen committed
378 379 380 381
		if cLen >= bestLen {
			best = c
			bestLen = cLen
		}
382

Steven Allen's avatar
Steven Allen committed
383 384
	}
	return best
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
385 386
}

Steven Allen's avatar
Steven Allen committed
387 388 389
// Connectedness returns our "connectedness" state with the given peer.
//
// To check if we have an open connection, use `s.Connectedness(p) ==
390 391
// network.Connected`.
func (s *Swarm) Connectedness(p peer.ID) network.Connectedness {
Steven Allen's avatar
Steven Allen committed
392
	if s.bestConnToPeer(p) != nil {
393
		return network.Connected
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
394
	}
395
	return network.NotConnected
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
396 397
}

Steven Allen's avatar
Steven Allen committed
398
// Conns returns a slice of all connections.
399
func (s *Swarm) Conns() []network.Conn {
Steven Allen's avatar
Steven Allen committed
400 401
	s.conns.RLock()
	defer s.conns.RUnlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
402

403
	conns := make([]network.Conn, 0, len(s.conns.m))
Steven Allen's avatar
Steven Allen committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
	for _, cs := range s.conns.m {
		for _, c := range cs {
			conns = append(conns, c)
		}
	}
	return conns
}

// ClosePeer closes all connections to the given peer.
func (s *Swarm) ClosePeer(p peer.ID) error {
	conns := s.ConnsToPeer(p)
	switch len(conns) {
	case 0:
		return nil
	case 1:
		return conns[0].Close()
	default:
		errCh := make(chan error)
		for _, c := range conns {
423
			go func(c network.Conn) {
Steven Allen's avatar
Steven Allen committed
424 425
				errCh <- c.Close()
			}(c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
426 427
		}

Steven Allen's avatar
Steven Allen committed
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
		var errs []string
		for _ = range conns {
			err := <-errCh
			if err != nil {
				errs = append(errs, err.Error())
			}
		}
		if len(errs) > 0 {
			return fmt.Errorf("when disconnecting from peer %s: %s", p, strings.Join(errs, ", "))
		}
		return nil
	}
}

// Peers returns a copy of the set of peers swarm is connected to.
func (s *Swarm) Peers() []peer.ID {
	s.conns.RLock()
	defer s.conns.RUnlock()
	peers := make([]peer.ID, 0, len(s.conns.m))
	for p := range s.conns.m {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
448 449
		peers = append(peers, p)
	}
Steven Allen's avatar
Steven Allen committed
450

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
451 452 453 454 455 456 457 458
	return peers
}

// LocalPeer returns the local peer swarm is associated to.
func (s *Swarm) LocalPeer() peer.ID {
	return s.local
}

Steven Allen's avatar
Steven Allen committed
459 460
// Backoff returns the DialBackoff object for this swarm.
func (s *Swarm) Backoff() *DialBackoff {
Jeromy's avatar
Jeromy committed
461 462 463
	return &s.backf
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
464
// notifyAll sends a signal to all Notifiees
465
func (s *Swarm) notifyAll(notify func(network.Notifiee)) {
466 467
	var wg sync.WaitGroup

Steven Allen's avatar
Steven Allen committed
468
	s.notifs.RLock()
469
	wg.Add(len(s.notifs.m))
Steven Allen's avatar
Steven Allen committed
470
	for f := range s.notifs.m {
471
		go func(f network.Notifiee) {
472 473 474
			defer wg.Done()
			notify(f)
		}(f)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
475
	}
476 477

	wg.Wait()
Steven Allen's avatar
Steven Allen committed
478
	s.notifs.RUnlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
479 480 481
}

// Notify signs up Notifiee to receive signals when events happen
482
func (s *Swarm) Notify(f network.Notifiee) {
Steven Allen's avatar
Steven Allen committed
483 484 485
	s.notifs.Lock()
	s.notifs.m[f] = struct{}{}
	s.notifs.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
486 487 488
}

// StopNotify unregisters Notifiee fromr receiving signals
489
func (s *Swarm) StopNotify(f network.Notifiee) {
Steven Allen's avatar
Steven Allen committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
	s.notifs.Lock()
	delete(s.notifs.m, f)
	s.notifs.Unlock()
}

func (s *Swarm) removeConn(c *Conn) {
	p := c.RemotePeer()

	s.conns.Lock()
	defer s.conns.Unlock()
	cs := s.conns.m[p]
	for i, ci := range cs {
		if ci == c {
			if len(cs) == 1 {
				delete(s.conns.m, p)
			} else {
				// NOTE: We're intentionally preserving order.
				// This way, connections to a peer are always
				// sorted oldest to newest.
				copy(cs[i:], cs[i+1:])
				cs[len(cs)-1] = nil
				s.conns.m[p] = cs[:len(cs)-1]
			}
			return
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
515 516 517
	}
}

Steven Allen's avatar
Steven Allen committed
518 519 520
// String returns a string representation of Network.
func (s *Swarm) String() string {
	return fmt.Sprintf("<Swarm %s>", s.LocalPeer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
521 522
}

Steven Allen's avatar
Steven Allen committed
523
// Swarm is a Network.
524 525
var _ network.Network = (*Swarm)(nil)
var _ transport.TransportNetwork = (*Swarm)(nil)