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