github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/p2p/server.go (about)

     1  // This file is part of the go-sberex library. The go-sberex library is 
     2  // free software: you can redistribute it and/or modify it under the terms 
     3  // of the GNU Lesser General Public License as published by the Free 
     4  // Software Foundation, either version 3 of the License, or (at your option)
     5  // any later version.
     6  //
     7  // The go-sberex library is distributed in the hope that it will be useful, 
     8  // but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
    10  // General Public License <http://www.gnu.org/licenses/> for more details.
    11  
    12  // Package p2p implements the Sberex p2p network protocols.
    13  package p2p
    14  
    15  import (
    16  	"crypto/ecdsa"
    17  	"errors"
    18  	"fmt"
    19  	"net"
    20  	"sync"
    21  	"time"
    22  
    23  	"github.com/Sberex/go-sberex/common"
    24  	"github.com/Sberex/go-sberex/common/mclock"
    25  	"github.com/Sberex/go-sberex/event"
    26  	"github.com/Sberex/go-sberex/log"
    27  	"github.com/Sberex/go-sberex/p2p/discover"
    28  	"github.com/Sberex/go-sberex/p2p/discv5"
    29  	"github.com/Sberex/go-sberex/p2p/nat"
    30  	"github.com/Sberex/go-sberex/p2p/netutil"
    31  )
    32  
    33  const (
    34  	defaultDialTimeout = 15 * time.Second
    35  
    36  	// Connectivity defaults.
    37  	maxActiveDialTasks     = 16
    38  	defaultMaxPendingPeers = 50
    39  	defaultDialRatio       = 3
    40  
    41  	// Maximum time allowed for reading a complete message.
    42  	// This is effectively the amount of time a connection can be idle.
    43  	frameReadTimeout = 30 * time.Second
    44  
    45  	// Maximum amount of time allowed for writing a complete message.
    46  	frameWriteTimeout = 20 * time.Second
    47  )
    48  
    49  var errServerStopped = errors.New("server stopped")
    50  
    51  // Config holds Server options.
    52  type Config struct {
    53  	// This field must be set to a valid secp256k1 private key.
    54  	PrivateKey *ecdsa.PrivateKey `toml:"-"`
    55  
    56  	// MaxPeers is the maximum number of peers that can be
    57  	// connected. It must be greater than zero.
    58  	MaxPeers int
    59  
    60  	// MaxPendingPeers is the maximum number of peers that can be pending in the
    61  	// handshake phase, counted separately for inbound and outbound connections.
    62  	// Zero defaults to preset values.
    63  	MaxPendingPeers int `toml:",omitempty"`
    64  
    65  	// DialRatio controls the ratio of inbound to dialed connections.
    66  	// Example: a DialRatio of 2 allows 1/2 of connections to be dialed.
    67  	// Setting DialRatio to zero defaults it to 3.
    68  	DialRatio int `toml:",omitempty"`
    69  
    70  	// NoDiscovery can be used to disable the peer discovery mechanism.
    71  	// Disabling is useful for protocol debugging (manual topology).
    72  	NoDiscovery bool
    73  
    74  	// DiscoveryV5 specifies whether the the new topic-discovery based V5 discovery
    75  	// protocol should be started or not.
    76  	DiscoveryV5 bool `toml:",omitempty"`
    77  
    78  	// Name sets the node name of this server.
    79  	// Use common.MakeName to create a name that follows existing conventions.
    80  	Name string `toml:"-"`
    81  
    82  	// BootstrapNodes are used to establish connectivity
    83  	// with the rest of the network.
    84  	BootstrapNodes []*discover.Node
    85  
    86  	// BootstrapNodesV5 are used to establish connectivity
    87  	// with the rest of the network using the V5 discovery
    88  	// protocol.
    89  	BootstrapNodesV5 []*discv5.Node `toml:",omitempty"`
    90  
    91  	// Static nodes are used as pre-configured connections which are always
    92  	// maintained and re-connected on disconnects.
    93  	StaticNodes []*discover.Node
    94  
    95  	// Trusted nodes are used as pre-configured connections which are always
    96  	// allowed to connect, even above the peer limit.
    97  	TrustedNodes []*discover.Node
    98  
    99  	// Connectivity can be restricted to certain IP networks.
   100  	// If this option is set to a non-nil value, only hosts which match one of the
   101  	// IP networks contained in the list are considered.
   102  	NetRestrict *netutil.Netlist `toml:",omitempty"`
   103  
   104  	// NodeDatabase is the path to the database containing the previously seen
   105  	// live nodes in the network.
   106  	NodeDatabase string `toml:",omitempty"`
   107  
   108  	// Protocols should contain the protocols supported
   109  	// by the server. Matching protocols are launched for
   110  	// each peer.
   111  	Protocols []Protocol `toml:"-"`
   112  
   113  	// If ListenAddr is set to a non-nil address, the server
   114  	// will listen for incoming connections.
   115  	//
   116  	// If the port is zero, the operating system will pick a port. The
   117  	// ListenAddr field will be updated with the actual address when
   118  	// the server is started.
   119  	ListenAddr string
   120  
   121  	// If set to a non-nil value, the given NAT port mapper
   122  	// is used to make the listening port available to the
   123  	// Internet.
   124  	NAT nat.Interface `toml:",omitempty"`
   125  
   126  	// If Dialer is set to a non-nil value, the given Dialer
   127  	// is used to dial outbound peer connections.
   128  	Dialer NodeDialer `toml:"-"`
   129  
   130  	// If NoDial is true, the server will not dial any peers.
   131  	NoDial bool `toml:",omitempty"`
   132  
   133  	// If EnableMsgEvents is set then the server will emit PeerEvents
   134  	// whenever a message is sent to or received from a peer
   135  	EnableMsgEvents bool
   136  
   137  	// Logger is a custom logger to use with the p2p.Server.
   138  	Logger log.Logger `toml:",omitempty"`
   139  }
   140  
   141  // Server manages all peer connections.
   142  type Server struct {
   143  	// Config fields may not be modified while the server is running.
   144  	Config
   145  
   146  	// Hooks for testing. These are useful because we can inhibit
   147  	// the whole protocol stack.
   148  	newTransport func(net.Conn) transport
   149  	newPeerHook  func(*Peer)
   150  
   151  	lock    sync.Mutex // protects running
   152  	running bool
   153  
   154  	ntab         discoverTable
   155  	listener     net.Listener
   156  	ourHandshake *protoHandshake
   157  	lastLookup   time.Time
   158  	DiscV5       *discv5.Network
   159  
   160  	// These are for Peers, PeerCount (and nothing else).
   161  	peerOp     chan peerOpFunc
   162  	peerOpDone chan struct{}
   163  
   164  	quit          chan struct{}
   165  	addstatic     chan *discover.Node
   166  	removestatic  chan *discover.Node
   167  	posthandshake chan *conn
   168  	addpeer       chan *conn
   169  	delpeer       chan peerDrop
   170  	loopWG        sync.WaitGroup // loop, listenLoop
   171  	peerFeed      event.Feed
   172  	log           log.Logger
   173  }
   174  
   175  type peerOpFunc func(map[discover.NodeID]*Peer)
   176  
   177  type peerDrop struct {
   178  	*Peer
   179  	err       error
   180  	requested bool // true if signaled by the peer
   181  }
   182  
   183  type connFlag int
   184  
   185  const (
   186  	dynDialedConn connFlag = 1 << iota
   187  	staticDialedConn
   188  	inboundConn
   189  	trustedConn
   190  )
   191  
   192  // conn wraps a network connection with information gathered
   193  // during the two handshakes.
   194  type conn struct {
   195  	fd net.Conn
   196  	transport
   197  	flags connFlag
   198  	cont  chan error      // The run loop uses cont to signal errors to SetupConn.
   199  	id    discover.NodeID // valid after the encryption handshake
   200  	caps  []Cap           // valid after the protocol handshake
   201  	name  string          // valid after the protocol handshake
   202  }
   203  
   204  type transport interface {
   205  	// The two handshakes.
   206  	doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.NodeID, error)
   207  	doProtoHandshake(our *protoHandshake) (*protoHandshake, error)
   208  	// The MsgReadWriter can only be used after the encryption
   209  	// handshake has completed. The code uses conn.id to track this
   210  	// by setting it to a non-nil value after the encryption handshake.
   211  	MsgReadWriter
   212  	// transports must provide Close because we use MsgPipe in some of
   213  	// the tests. Closing the actual network connection doesn't do
   214  	// anything in those tests because NsgPipe doesn't use it.
   215  	close(err error)
   216  }
   217  
   218  func (c *conn) String() string {
   219  	s := c.flags.String()
   220  	if (c.id != discover.NodeID{}) {
   221  		s += " " + c.id.String()
   222  	}
   223  	s += " " + c.fd.RemoteAddr().String()
   224  	return s
   225  }
   226  
   227  func (f connFlag) String() string {
   228  	s := ""
   229  	if f&trustedConn != 0 {
   230  		s += "-trusted"
   231  	}
   232  	if f&dynDialedConn != 0 {
   233  		s += "-dyndial"
   234  	}
   235  	if f&staticDialedConn != 0 {
   236  		s += "-staticdial"
   237  	}
   238  	if f&inboundConn != 0 {
   239  		s += "-inbound"
   240  	}
   241  	if s != "" {
   242  		s = s[1:]
   243  	}
   244  	return s
   245  }
   246  
   247  func (c *conn) is(f connFlag) bool {
   248  	return c.flags&f != 0
   249  }
   250  
   251  // Peers returns all connected peers.
   252  func (srv *Server) Peers() []*Peer {
   253  	var ps []*Peer
   254  	select {
   255  	// Note: We'd love to put this function into a variable but
   256  	// that seems to cause a weird compiler error in some
   257  	// environments.
   258  	case srv.peerOp <- func(peers map[discover.NodeID]*Peer) {
   259  		for _, p := range peers {
   260  			ps = append(ps, p)
   261  		}
   262  	}:
   263  		<-srv.peerOpDone
   264  	case <-srv.quit:
   265  	}
   266  	return ps
   267  }
   268  
   269  // PeerCount returns the number of connected peers.
   270  func (srv *Server) PeerCount() int {
   271  	var count int
   272  	select {
   273  	case srv.peerOp <- func(ps map[discover.NodeID]*Peer) { count = len(ps) }:
   274  		<-srv.peerOpDone
   275  	case <-srv.quit:
   276  	}
   277  	return count
   278  }
   279  
   280  // AddPeer connects to the given node and maintains the connection until the
   281  // server is shut down. If the connection fails for any reason, the server will
   282  // attempt to reconnect the peer.
   283  func (srv *Server) AddPeer(node *discover.Node) {
   284  	select {
   285  	case srv.addstatic <- node:
   286  	case <-srv.quit:
   287  	}
   288  }
   289  
   290  // RemovePeer disconnects from the given node
   291  func (srv *Server) RemovePeer(node *discover.Node) {
   292  	select {
   293  	case srv.removestatic <- node:
   294  	case <-srv.quit:
   295  	}
   296  }
   297  
   298  // SubscribePeers subscribes the given channel to peer events
   299  func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription {
   300  	return srv.peerFeed.Subscribe(ch)
   301  }
   302  
   303  // Self returns the local node's endpoint information.
   304  func (srv *Server) Self() *discover.Node {
   305  	srv.lock.Lock()
   306  	defer srv.lock.Unlock()
   307  
   308  	if !srv.running {
   309  		return &discover.Node{IP: net.ParseIP("0.0.0.0")}
   310  	}
   311  	return srv.makeSelf(srv.listener, srv.ntab)
   312  }
   313  
   314  func (srv *Server) makeSelf(listener net.Listener, ntab discoverTable) *discover.Node {
   315  	// If the server's not running, return an empty node.
   316  	// If the node is running but discovery is off, manually assemble the node infos.
   317  	if ntab == nil {
   318  		// Inbound connections disabled, use zero address.
   319  		if listener == nil {
   320  			return &discover.Node{IP: net.ParseIP("0.0.0.0"), ID: discover.PubkeyID(&srv.PrivateKey.PublicKey)}
   321  		}
   322  		// Otherwise inject the listener address too
   323  		addr := listener.Addr().(*net.TCPAddr)
   324  		return &discover.Node{
   325  			ID:  discover.PubkeyID(&srv.PrivateKey.PublicKey),
   326  			IP:  addr.IP,
   327  			TCP: uint16(addr.Port),
   328  		}
   329  	}
   330  	// Otherwise return the discovery node.
   331  	return ntab.Self()
   332  }
   333  
   334  // Stop terminates the server and all active peer connections.
   335  // It blocks until all active connections have been closed.
   336  func (srv *Server) Stop() {
   337  	srv.lock.Lock()
   338  	defer srv.lock.Unlock()
   339  	if !srv.running {
   340  		return
   341  	}
   342  	srv.running = false
   343  	if srv.listener != nil {
   344  		// this unblocks listener Accept
   345  		srv.listener.Close()
   346  	}
   347  	close(srv.quit)
   348  	srv.loopWG.Wait()
   349  }
   350  
   351  // sharedUDPConn implements a shared connection. Write sends messages to the underlying connection while read returns
   352  // messages that were found unprocessable and sent to the unhandled channel by the primary listener.
   353  type sharedUDPConn struct {
   354  	*net.UDPConn
   355  	unhandled chan discover.ReadPacket
   356  }
   357  
   358  // ReadFromUDP implements discv5.conn
   359  func (s *sharedUDPConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
   360  	packet, ok := <-s.unhandled
   361  	if !ok {
   362  		return 0, nil, fmt.Errorf("Connection was closed")
   363  	}
   364  	l := len(packet.Data)
   365  	if l > len(b) {
   366  		l = len(b)
   367  	}
   368  	copy(b[:l], packet.Data[:l])
   369  	return l, packet.Addr, nil
   370  }
   371  
   372  // Close implements discv5.conn
   373  func (s *sharedUDPConn) Close() error {
   374  	return nil
   375  }
   376  
   377  // Start starts running the server.
   378  // Servers can not be re-used after stopping.
   379  func (srv *Server) Start() (err error) {
   380  	srv.lock.Lock()
   381  	defer srv.lock.Unlock()
   382  	if srv.running {
   383  		return errors.New("server already running")
   384  	}
   385  	srv.running = true
   386  	srv.log = srv.Config.Logger
   387  	if srv.log == nil {
   388  		srv.log = log.New()
   389  	}
   390  	srv.log.Info("Starting P2P networking")
   391  
   392  	// static fields
   393  	if srv.PrivateKey == nil {
   394  		return fmt.Errorf("Server.PrivateKey must be set to a non-nil key")
   395  	}
   396  	if srv.newTransport == nil {
   397  		srv.newTransport = newRLPX
   398  	}
   399  	if srv.Dialer == nil {
   400  		srv.Dialer = TCPDialer{&net.Dialer{Timeout: defaultDialTimeout}}
   401  	}
   402  	srv.quit = make(chan struct{})
   403  	srv.addpeer = make(chan *conn)
   404  	srv.delpeer = make(chan peerDrop)
   405  	srv.posthandshake = make(chan *conn)
   406  	srv.addstatic = make(chan *discover.Node)
   407  	srv.removestatic = make(chan *discover.Node)
   408  	srv.peerOp = make(chan peerOpFunc)
   409  	srv.peerOpDone = make(chan struct{})
   410  
   411  	var (
   412  		conn      *net.UDPConn
   413  		sconn     *sharedUDPConn
   414  		realaddr  *net.UDPAddr
   415  		unhandled chan discover.ReadPacket
   416  	)
   417  
   418  	if !srv.NoDiscovery || srv.DiscoveryV5 {
   419  		addr, err := net.ResolveUDPAddr("udp", srv.ListenAddr)
   420  		if err != nil {
   421  			return err
   422  		}
   423  		conn, err = net.ListenUDP("udp", addr)
   424  		if err != nil {
   425  			return err
   426  		}
   427  		realaddr = conn.LocalAddr().(*net.UDPAddr)
   428  		if srv.NAT != nil {
   429  			if !realaddr.IP.IsLoopback() {
   430  				go nat.Map(srv.NAT, srv.quit, "udp", realaddr.Port, realaddr.Port, "sberex discovery")
   431  			}
   432  			// TODO: react to external IP changes over time.
   433  			if ext, err := srv.NAT.ExternalIP(); err == nil {
   434  				realaddr = &net.UDPAddr{IP: ext, Port: realaddr.Port}
   435  			}
   436  		}
   437  	}
   438  
   439  	if !srv.NoDiscovery && srv.DiscoveryV5 {
   440  		unhandled = make(chan discover.ReadPacket, 100)
   441  		sconn = &sharedUDPConn{conn, unhandled}
   442  	}
   443  
   444  	// node table
   445  	if !srv.NoDiscovery {
   446  		cfg := discover.Config{
   447  			PrivateKey:   srv.PrivateKey,
   448  			AnnounceAddr: realaddr,
   449  			NodeDBPath:   srv.NodeDatabase,
   450  			NetRestrict:  srv.NetRestrict,
   451  			Bootnodes:    srv.BootstrapNodes,
   452  			Unhandled:    unhandled,
   453  		}
   454  		ntab, err := discover.ListenUDP(conn, cfg)
   455  		if err != nil {
   456  			return err
   457  		}
   458  		srv.ntab = ntab
   459  	}
   460  
   461  	if srv.DiscoveryV5 {
   462  		var (
   463  			ntab *discv5.Network
   464  			err  error
   465  		)
   466  		if sconn != nil {
   467  			ntab, err = discv5.ListenUDP(srv.PrivateKey, sconn, realaddr, "", srv.NetRestrict) //srv.NodeDatabase)
   468  		} else {
   469  			ntab, err = discv5.ListenUDP(srv.PrivateKey, conn, realaddr, "", srv.NetRestrict) //srv.NodeDatabase)
   470  		}
   471  		if err != nil {
   472  			return err
   473  		}
   474  		if err := ntab.SetFallbackNodes(srv.BootstrapNodesV5); err != nil {
   475  			return err
   476  		}
   477  		srv.DiscV5 = ntab
   478  	}
   479  
   480  	dynPeers := srv.maxDialedConns()
   481  	dialer := newDialState(srv.StaticNodes, srv.BootstrapNodes, srv.ntab, dynPeers, srv.NetRestrict)
   482  
   483  	// handshake
   484  	srv.ourHandshake = &protoHandshake{Version: baseProtocolVersion, Name: srv.Name, ID: discover.PubkeyID(&srv.PrivateKey.PublicKey)}
   485  	for _, p := range srv.Protocols {
   486  		srv.ourHandshake.Caps = append(srv.ourHandshake.Caps, p.cap())
   487  	}
   488  	// listen/dial
   489  	if srv.ListenAddr != "" {
   490  		if err := srv.startListening(); err != nil {
   491  			return err
   492  		}
   493  	}
   494  	if srv.NoDial && srv.ListenAddr == "" {
   495  		srv.log.Warn("P2P server will be useless, neither dialing nor listening")
   496  	}
   497  
   498  	srv.loopWG.Add(1)
   499  	go srv.run(dialer)
   500  	srv.running = true
   501  	return nil
   502  }
   503  
   504  func (srv *Server) startListening() error {
   505  	// Launch the TCP listener.
   506  	listener, err := net.Listen("tcp", srv.ListenAddr)
   507  	if err != nil {
   508  		return err
   509  	}
   510  	laddr := listener.Addr().(*net.TCPAddr)
   511  	srv.ListenAddr = laddr.String()
   512  	srv.listener = listener
   513  	srv.loopWG.Add(1)
   514  	go srv.listenLoop()
   515  	// Map the TCP listening port if NAT is configured.
   516  	if !laddr.IP.IsLoopback() && srv.NAT != nil {
   517  		srv.loopWG.Add(1)
   518  		go func() {
   519  			nat.Map(srv.NAT, srv.quit, "tcp", laddr.Port, laddr.Port, "sberex p2p")
   520  			srv.loopWG.Done()
   521  		}()
   522  	}
   523  	return nil
   524  }
   525  
   526  type dialer interface {
   527  	newTasks(running int, peers map[discover.NodeID]*Peer, now time.Time) []task
   528  	taskDone(task, time.Time)
   529  	addStatic(*discover.Node)
   530  	removeStatic(*discover.Node)
   531  }
   532  
   533  func (srv *Server) run(dialstate dialer) {
   534  	defer srv.loopWG.Done()
   535  	var (
   536  		peers        = make(map[discover.NodeID]*Peer)
   537  		inboundCount = 0
   538  		trusted      = make(map[discover.NodeID]bool, len(srv.TrustedNodes))
   539  		taskdone     = make(chan task, maxActiveDialTasks)
   540  		runningTasks []task
   541  		queuedTasks  []task // tasks that can't run yet
   542  	)
   543  	// Put trusted nodes into a map to speed up checks.
   544  	// Trusted peers are loaded on startup and cannot be
   545  	// modified while the server is running.
   546  	for _, n := range srv.TrustedNodes {
   547  		trusted[n.ID] = true
   548  	}
   549  
   550  	// removes t from runningTasks
   551  	delTask := func(t task) {
   552  		for i := range runningTasks {
   553  			if runningTasks[i] == t {
   554  				runningTasks = append(runningTasks[:i], runningTasks[i+1:]...)
   555  				break
   556  			}
   557  		}
   558  	}
   559  	// starts until max number of active tasks is satisfied
   560  	startTasks := func(ts []task) (rest []task) {
   561  		i := 0
   562  		for ; len(runningTasks) < maxActiveDialTasks && i < len(ts); i++ {
   563  			t := ts[i]
   564  			srv.log.Trace("New dial task", "task", t)
   565  			go func() { t.Do(srv); taskdone <- t }()
   566  			runningTasks = append(runningTasks, t)
   567  		}
   568  		return ts[i:]
   569  	}
   570  	scheduleTasks := func() {
   571  		// Start from queue first.
   572  		queuedTasks = append(queuedTasks[:0], startTasks(queuedTasks)...)
   573  		// Query dialer for new tasks and start as many as possible now.
   574  		if len(runningTasks) < maxActiveDialTasks {
   575  			nt := dialstate.newTasks(len(runningTasks)+len(queuedTasks), peers, time.Now())
   576  			queuedTasks = append(queuedTasks, startTasks(nt)...)
   577  		}
   578  	}
   579  
   580  running:
   581  	for {
   582  		scheduleTasks()
   583  
   584  		select {
   585  		case <-srv.quit:
   586  			// The server was stopped. Run the cleanup logic.
   587  			break running
   588  		case n := <-srv.addstatic:
   589  			// This channel is used by AddPeer to add to the
   590  			// ephemeral static peer list. Add it to the dialer,
   591  			// it will keep the node connected.
   592  			srv.log.Debug("Adding static node", "node", n)
   593  			dialstate.addStatic(n)
   594  		case n := <-srv.removestatic:
   595  			// This channel is used by RemovePeer to send a
   596  			// disconnect request to a peer and begin the
   597  			// stop keeping the node connected
   598  			srv.log.Debug("Removing static node", "node", n)
   599  			dialstate.removeStatic(n)
   600  			if p, ok := peers[n.ID]; ok {
   601  				p.Disconnect(DiscRequested)
   602  			}
   603  		case op := <-srv.peerOp:
   604  			// This channel is used by Peers and PeerCount.
   605  			op(peers)
   606  			srv.peerOpDone <- struct{}{}
   607  		case t := <-taskdone:
   608  			// A task got done. Tell dialstate about it so it
   609  			// can update its state and remove it from the active
   610  			// tasks list.
   611  			srv.log.Trace("Dial task done", "task", t)
   612  			dialstate.taskDone(t, time.Now())
   613  			delTask(t)
   614  		case c := <-srv.posthandshake:
   615  			// A connection has passed the encryption handshake so
   616  			// the remote identity is known (but hasn't been verified yet).
   617  			if trusted[c.id] {
   618  				// Ensure that the trusted flag is set before checking against MaxPeers.
   619  				c.flags |= trustedConn
   620  			}
   621  			// TODO: track in-progress inbound node IDs (pre-Peer) to avoid dialing them.
   622  			select {
   623  			case c.cont <- srv.encHandshakeChecks(peers, inboundCount, c):
   624  			case <-srv.quit:
   625  				break running
   626  			}
   627  		case c := <-srv.addpeer:
   628  			// At this point the connection is past the protocol handshake.
   629  			// Its capabilities are known and the remote identity is verified.
   630  			err := srv.protoHandshakeChecks(peers, inboundCount, c)
   631  			if err == nil {
   632  				// The handshakes are done and it passed all checks.
   633  				p := newPeer(c, srv.Protocols)
   634  				// If message events are enabled, pass the peerFeed
   635  				// to the peer
   636  				if srv.EnableMsgEvents {
   637  					p.events = &srv.peerFeed
   638  				}
   639  				name := truncateName(c.name)
   640  				srv.log.Debug("Adding p2p peer", "name", name, "addr", c.fd.RemoteAddr(), "peers", len(peers)+1)
   641  				go srv.runPeer(p)
   642  				peers[c.id] = p
   643  				if p.Inbound() {
   644  					inboundCount++
   645  				}
   646  			}
   647  			// The dialer logic relies on the assumption that
   648  			// dial tasks complete after the peer has been added or
   649  			// discarded. Unblock the task last.
   650  			select {
   651  			case c.cont <- err:
   652  			case <-srv.quit:
   653  				break running
   654  			}
   655  		case pd := <-srv.delpeer:
   656  			// A peer disconnected.
   657  			d := common.PrettyDuration(mclock.Now() - pd.created)
   658  			pd.log.Debug("Removing p2p peer", "duration", d, "peers", len(peers)-1, "req", pd.requested, "err", pd.err)
   659  			delete(peers, pd.ID())
   660  			if pd.Inbound() {
   661  				inboundCount--
   662  			}
   663  		}
   664  	}
   665  
   666  	srv.log.Trace("P2P networking is spinning down")
   667  
   668  	// Terminate discovery. If there is a running lookup it will terminate soon.
   669  	if srv.ntab != nil {
   670  		srv.ntab.Close()
   671  	}
   672  	if srv.DiscV5 != nil {
   673  		srv.DiscV5.Close()
   674  	}
   675  	// Disconnect all peers.
   676  	for _, p := range peers {
   677  		p.Disconnect(DiscQuitting)
   678  	}
   679  	// Wait for peers to shut down. Pending connections and tasks are
   680  	// not handled here and will terminate soon-ish because srv.quit
   681  	// is closed.
   682  	for len(peers) > 0 {
   683  		p := <-srv.delpeer
   684  		p.log.Trace("<-delpeer (spindown)", "remainingTasks", len(runningTasks))
   685  		delete(peers, p.ID())
   686  	}
   687  }
   688  
   689  func (srv *Server) protoHandshakeChecks(peers map[discover.NodeID]*Peer, inboundCount int, c *conn) error {
   690  	// Drop connections with no matching protocols.
   691  	if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 {
   692  		return DiscUselessPeer
   693  	}
   694  	// Repeat the encryption handshake checks because the
   695  	// peer set might have changed between the handshakes.
   696  	return srv.encHandshakeChecks(peers, inboundCount, c)
   697  }
   698  
   699  func (srv *Server) encHandshakeChecks(peers map[discover.NodeID]*Peer, inboundCount int, c *conn) error {
   700  	switch {
   701  	case !c.is(trustedConn|staticDialedConn) && len(peers) >= srv.MaxPeers:
   702  		return DiscTooManyPeers
   703  	case !c.is(trustedConn) && c.is(inboundConn) && inboundCount >= srv.maxInboundConns():
   704  		return DiscTooManyPeers
   705  	case peers[c.id] != nil:
   706  		return DiscAlreadyConnected
   707  	case c.id == srv.Self().ID:
   708  		return DiscSelf
   709  	default:
   710  		return nil
   711  	}
   712  }
   713  
   714  func (srv *Server) maxInboundConns() int {
   715  	return srv.MaxPeers - srv.maxDialedConns()
   716  }
   717  
   718  func (srv *Server) maxDialedConns() int {
   719  	if srv.NoDiscovery || srv.NoDial {
   720  		return 0
   721  	}
   722  	r := srv.DialRatio
   723  	if r == 0 {
   724  		r = defaultDialRatio
   725  	}
   726  	return srv.MaxPeers / r
   727  }
   728  
   729  type tempError interface {
   730  	Temporary() bool
   731  }
   732  
   733  // listenLoop runs in its own goroutine and accepts
   734  // inbound connections.
   735  func (srv *Server) listenLoop() {
   736  	defer srv.loopWG.Done()
   737  	srv.log.Info("RLPx listener up", "self", srv.makeSelf(srv.listener, srv.ntab))
   738  
   739  	tokens := defaultMaxPendingPeers
   740  	if srv.MaxPendingPeers > 0 {
   741  		tokens = srv.MaxPendingPeers
   742  	}
   743  	slots := make(chan struct{}, tokens)
   744  	for i := 0; i < tokens; i++ {
   745  		slots <- struct{}{}
   746  	}
   747  
   748  	for {
   749  		// Wait for a handshake slot before accepting.
   750  		<-slots
   751  
   752  		var (
   753  			fd  net.Conn
   754  			err error
   755  		)
   756  		for {
   757  			fd, err = srv.listener.Accept()
   758  			if tempErr, ok := err.(tempError); ok && tempErr.Temporary() {
   759  				srv.log.Debug("Temporary read error", "err", err)
   760  				continue
   761  			} else if err != nil {
   762  				srv.log.Debug("Read error", "err", err)
   763  				return
   764  			}
   765  			break
   766  		}
   767  
   768  		// Reject connections that do not match NetRestrict.
   769  		if srv.NetRestrict != nil {
   770  			if tcp, ok := fd.RemoteAddr().(*net.TCPAddr); ok && !srv.NetRestrict.Contains(tcp.IP) {
   771  				srv.log.Debug("Rejected conn (not whitelisted in NetRestrict)", "addr", fd.RemoteAddr())
   772  				fd.Close()
   773  				slots <- struct{}{}
   774  				continue
   775  			}
   776  		}
   777  
   778  		fd = newMeteredConn(fd, true)
   779  		srv.log.Trace("Accepted connection", "addr", fd.RemoteAddr())
   780  		go func() {
   781  			srv.SetupConn(fd, inboundConn, nil)
   782  			slots <- struct{}{}
   783  		}()
   784  	}
   785  }
   786  
   787  // SetupConn runs the handshakes and attempts to add the connection
   788  // as a peer. It returns when the connection has been added as a peer
   789  // or the handshakes have failed.
   790  func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *discover.Node) error {
   791  	self := srv.Self()
   792  	if self == nil {
   793  		return errors.New("shutdown")
   794  	}
   795  	c := &conn{fd: fd, transport: srv.newTransport(fd), flags: flags, cont: make(chan error)}
   796  	err := srv.setupConn(c, flags, dialDest)
   797  	if err != nil {
   798  		c.close(err)
   799  		srv.log.Trace("Setting up connection failed", "id", c.id, "err", err)
   800  	}
   801  	return err
   802  }
   803  
   804  func (srv *Server) setupConn(c *conn, flags connFlag, dialDest *discover.Node) error {
   805  	// Prevent leftover pending conns from entering the handshake.
   806  	srv.lock.Lock()
   807  	running := srv.running
   808  	srv.lock.Unlock()
   809  	if !running {
   810  		return errServerStopped
   811  	}
   812  	// Run the encryption handshake.
   813  	var err error
   814  	if c.id, err = c.doEncHandshake(srv.PrivateKey, dialDest); err != nil {
   815  		srv.log.Trace("Failed RLPx handshake", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err)
   816  		return err
   817  	}
   818  	clog := srv.log.New("id", c.id, "addr", c.fd.RemoteAddr(), "conn", c.flags)
   819  	// For dialed connections, check that the remote public key matches.
   820  	if dialDest != nil && c.id != dialDest.ID {
   821  		clog.Trace("Dialed identity mismatch", "want", c, dialDest.ID)
   822  		return DiscUnexpectedIdentity
   823  	}
   824  	err = srv.checkpoint(c, srv.posthandshake)
   825  	if err != nil {
   826  		clog.Trace("Rejected peer before protocol handshake", "err", err)
   827  		return err
   828  	}
   829  	// Run the protocol handshake
   830  	phs, err := c.doProtoHandshake(srv.ourHandshake)
   831  	if err != nil {
   832  		clog.Trace("Failed proto handshake", "err", err)
   833  		return err
   834  	}
   835  	if phs.ID != c.id {
   836  		clog.Trace("Wrong devp2p handshake identity", "err", phs.ID)
   837  		return DiscUnexpectedIdentity
   838  	}
   839  	c.caps, c.name = phs.Caps, phs.Name
   840  	err = srv.checkpoint(c, srv.addpeer)
   841  	if err != nil {
   842  		clog.Trace("Rejected peer", "err", err)
   843  		return err
   844  	}
   845  	// If the checks completed successfully, runPeer has now been
   846  	// launched by run.
   847  	clog.Trace("connection set up", "inbound", dialDest == nil)
   848  	return nil
   849  }
   850  
   851  func truncateName(s string) string {
   852  	if len(s) > 20 {
   853  		return s[:20] + "..."
   854  	}
   855  	return s
   856  }
   857  
   858  // checkpoint sends the conn to run, which performs the
   859  // post-handshake checks for the stage (posthandshake, addpeer).
   860  func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error {
   861  	select {
   862  	case stage <- c:
   863  	case <-srv.quit:
   864  		return errServerStopped
   865  	}
   866  	select {
   867  	case err := <-c.cont:
   868  		return err
   869  	case <-srv.quit:
   870  		return errServerStopped
   871  	}
   872  }
   873  
   874  // runPeer runs in its own goroutine for each peer.
   875  // it waits until the Peer logic returns and removes
   876  // the peer.
   877  func (srv *Server) runPeer(p *Peer) {
   878  	if srv.newPeerHook != nil {
   879  		srv.newPeerHook(p)
   880  	}
   881  
   882  	// broadcast peer add
   883  	srv.peerFeed.Send(&PeerEvent{
   884  		Type: PeerEventTypeAdd,
   885  		Peer: p.ID(),
   886  	})
   887  
   888  	// run the protocol
   889  	remoteRequested, err := p.run()
   890  
   891  	// broadcast peer drop
   892  	srv.peerFeed.Send(&PeerEvent{
   893  		Type:  PeerEventTypeDrop,
   894  		Peer:  p.ID(),
   895  		Error: err.Error(),
   896  	})
   897  
   898  	// Note: run waits for existing peers to be sent on srv.delpeer
   899  	// before returning, so this send should not select on srv.quit.
   900  	srv.delpeer <- peerDrop{p, err, remoteRequested}
   901  }
   902  
   903  // NodeInfo represents a short summary of the information known about the host.
   904  type NodeInfo struct {
   905  	ID    string `json:"id"`    // Unique node identifier (also the encryption key)
   906  	Name  string `json:"name"`  // Name of the node, including client type, version, OS, custom data
   907  	Enode string `json:"enode"` // Enode URL for adding this peer from remote peers
   908  	IP    string `json:"ip"`    // IP address of the node
   909  	Ports struct {
   910  		Discovery int `json:"discovery"` // UDP listening port for discovery protocol
   911  		Listener  int `json:"listener"`  // TCP listening port for RLPx
   912  	} `json:"ports"`
   913  	ListenAddr string                 `json:"listenAddr"`
   914  	Protocols  map[string]interface{} `json:"protocols"`
   915  }
   916  
   917  // NodeInfo gathers and returns a collection of metadata known about the host.
   918  func (srv *Server) NodeInfo() *NodeInfo {
   919  	node := srv.Self()
   920  
   921  	// Gather and assemble the generic node infos
   922  	info := &NodeInfo{
   923  		Name:       srv.Name,
   924  		Enode:      node.String(),
   925  		ID:         node.ID.String(),
   926  		IP:         node.IP.String(),
   927  		ListenAddr: srv.ListenAddr,
   928  		Protocols:  make(map[string]interface{}),
   929  	}
   930  	info.Ports.Discovery = int(node.UDP)
   931  	info.Ports.Listener = int(node.TCP)
   932  
   933  	// Gather all the running protocol infos (only once per protocol type)
   934  	for _, proto := range srv.Protocols {
   935  		if _, ok := info.Protocols[proto.Name]; !ok {
   936  			nodeInfo := interface{}("unknown")
   937  			if query := proto.NodeInfo; query != nil {
   938  				nodeInfo = proto.NodeInfo()
   939  			}
   940  			info.Protocols[proto.Name] = nodeInfo
   941  		}
   942  	}
   943  	return info
   944  }
   945  
   946  // PeersInfo returns an array of metadata objects describing connected peers.
   947  func (srv *Server) PeersInfo() []*PeerInfo {
   948  	// Gather all the generic and sub-protocol specific infos
   949  	infos := make([]*PeerInfo, 0, srv.PeerCount())
   950  	for _, peer := range srv.Peers() {
   951  		if peer != nil {
   952  			infos = append(infos, peer.Info())
   953  		}
   954  	}
   955  	// Sort the result array alphabetically by node identifier
   956  	for i := 0; i < len(infos); i++ {
   957  		for j := i + 1; j < len(infos); j++ {
   958  			if infos[i].ID > infos[j].ID {
   959  				infos[i], infos[j] = infos[j], infos[i]
   960  			}
   961  		}
   962  	}
   963  	return infos
   964  }