github.com/needkane/go-ethereum@v1.7.4-0.20180131070256-c212876ea2b7/p2p/server.go (about)

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