github.com/halybang/go-ethereum@v1.0.5-0.20180325041310-3b262bc1367c/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/wanchain/go-wanchain/common"
    29  	"github.com/wanchain/go-wanchain/common/mclock"
    30  	"github.com/wanchain/go-wanchain/event"
    31  	"github.com/wanchain/go-wanchain/log"
    32  	"github.com/wanchain/go-wanchain/p2p/discover"
    33  	"github.com/wanchain/go-wanchain/p2p/discv5"
    34  	"github.com/wanchain/go-wanchain/p2p/nat"
    35  	"github.com/wanchain/go-wanchain/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  
   560  			//if err == nil && strings.Contains(truncateName(c.name),params.VersionMeta) {
   561  			if err == nil {
   562  			// The handshakes are done and it passed all checks.
   563  				p := newPeer(c, srv.Protocols)
   564  				// If message events are enabled, pass the peerFeed
   565  				// to the peer
   566  				if srv.EnableMsgEvents {
   567  					p.events = &srv.peerFeed
   568  				}
   569  				name := truncateName(c.name)
   570  
   571  
   572  				log.Debug("Adding p2p peer", "id", c.id, "name", name, "addr", c.fd.RemoteAddr(), "peers", len(peers)+1)
   573  				peers[c.id] = p
   574  				go srv.runPeer(p)
   575  			}
   576  			// The dialer logic relies on the assumption that
   577  			// dial tasks complete after the peer has been added or
   578  			// discarded. Unblock the task last.
   579  			select {
   580  			case c.cont <- err:
   581  			case <-srv.quit:
   582  				break running
   583  			}
   584  		case pd := <-srv.delpeer:
   585  			// A peer disconnected.
   586  			d := common.PrettyDuration(mclock.Now() - pd.created)
   587  			pd.log.Debug("Removing p2p peer", "duration", d, "peers", len(peers)-1, "req", pd.requested, "err", pd.err)
   588  			delete(peers, pd.ID())
   589  		}
   590  	}
   591  
   592  	log.Trace("P2P networking is spinning down")
   593  
   594  	// Terminate discovery. If there is a running lookup it will terminate soon.
   595  	if srv.ntab != nil {
   596  		srv.ntab.Close()
   597  	}
   598  	if srv.DiscV5 != nil {
   599  		srv.DiscV5.Close()
   600  	}
   601  	// Disconnect all peers.
   602  	for _, p := range peers {
   603  		p.Disconnect(DiscQuitting)
   604  	}
   605  	// Wait for peers to shut down. Pending connections and tasks are
   606  	// not handled here and will terminate soon-ish because srv.quit
   607  	// is closed.
   608  	for len(peers) > 0 {
   609  		p := <-srv.delpeer
   610  		p.log.Trace("<-delpeer (spindown)", "remainingTasks", len(runningTasks))
   611  		delete(peers, p.ID())
   612  	}
   613  }
   614  
   615  func (srv *Server) protoHandshakeChecks(peers map[discover.NodeID]*Peer, c *conn) error {
   616  	// Drop connections with no matching protocols.
   617  	if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 {
   618  		return DiscUselessPeer
   619  	}
   620  	// Repeat the encryption handshake checks because the
   621  	// peer set might have changed between the handshakes.
   622  	return srv.encHandshakeChecks(peers, c)
   623  }
   624  
   625  func (srv *Server) encHandshakeChecks(peers map[discover.NodeID]*Peer, c *conn) error {
   626  	switch {
   627  	case !c.is(trustedConn|staticDialedConn) && len(peers) >= srv.MaxPeers:
   628  		return DiscTooManyPeers
   629  	case peers[c.id] != nil:
   630  		return DiscAlreadyConnected
   631  	case c.id == srv.Self().ID:
   632  		return DiscSelf
   633  	default:
   634  		return nil
   635  	}
   636  }
   637  
   638  type tempError interface {
   639  	Temporary() bool
   640  }
   641  
   642  // listenLoop runs in its own goroutine and accepts
   643  // inbound connections.
   644  func (srv *Server) listenLoop() {
   645  	defer srv.loopWG.Done()
   646  	log.Info("RLPx listener up", "self", srv.makeSelf(srv.listener, srv.ntab))
   647  
   648  	// This channel acts as a semaphore limiting
   649  	// active inbound connections that are lingering pre-handshake.
   650  	// If all slots are taken, no further connections are accepted.
   651  	tokens := maxAcceptConns
   652  	if srv.MaxPendingPeers > 0 {
   653  		tokens = srv.MaxPendingPeers
   654  	}
   655  	slots := make(chan struct{}, tokens)
   656  	for i := 0; i < tokens; i++ {
   657  		slots <- struct{}{}
   658  	}
   659  
   660  	for {
   661  		// Wait for a handshake slot before accepting.
   662  		<-slots
   663  
   664  		var (
   665  			fd  net.Conn
   666  			err error
   667  		)
   668  		for {
   669  			fd, err = srv.listener.Accept()
   670  			if tempErr, ok := err.(tempError); ok && tempErr.Temporary() {
   671  				log.Debug("Temporary read error", "err", err)
   672  				continue
   673  			} else if err != nil {
   674  				log.Debug("Read error", "err", err)
   675  				return
   676  			}
   677  			break
   678  		}
   679  
   680  		// Reject connections that do not match NetRestrict.
   681  		if srv.NetRestrict != nil {
   682  			if tcp, ok := fd.RemoteAddr().(*net.TCPAddr); ok && !srv.NetRestrict.Contains(tcp.IP) {
   683  				log.Debug("Rejected conn (not whitelisted in NetRestrict)", "addr", fd.RemoteAddr())
   684  				fd.Close()
   685  				slots <- struct{}{}
   686  				continue
   687  			}
   688  		}
   689  
   690  		fd = newMeteredConn(fd, true)
   691  		log.Trace("Accepted connection", "addr", fd.RemoteAddr())
   692  
   693  		// Spawn the handler. It will give the slot back when the connection
   694  		// has been established.
   695  		go func() {
   696  			srv.SetupConn(fd, inboundConn, nil)
   697  			slots <- struct{}{}
   698  		}()
   699  	}
   700  }
   701  
   702  // SetupConn runs the handshakes and attempts to add the connection
   703  // as a peer. It returns when the connection has been added as a peer
   704  // or the handshakes have failed.
   705  func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *discover.Node) {
   706  	// Prevent leftover pending conns from entering the handshake.
   707  	srv.lock.Lock()
   708  	running := srv.running
   709  	srv.lock.Unlock()
   710  	c := &conn{fd: fd, transport: srv.newTransport(fd), flags: flags, cont: make(chan error)}
   711  	if !running {
   712  		c.close(errServerStopped)
   713  		return
   714  	}
   715  	// Run the encryption handshake.
   716  	var err error
   717  	if c.id, err = c.doEncHandshake(srv.PrivateKey, dialDest); err != nil {
   718  		log.Trace("Failed RLPx handshake", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err)
   719  		c.close(err)
   720  		return
   721  	}
   722  	clog := log.New("id", c.id, "addr", c.fd.RemoteAddr(), "conn", c.flags)
   723  	// For dialed connections, check that the remote public key matches.
   724  	if dialDest != nil && c.id != dialDest.ID {
   725  		c.close(DiscUnexpectedIdentity)
   726  		clog.Trace("Dialed identity mismatch", "want", c, dialDest.ID)
   727  		return
   728  	}
   729  	if err := srv.checkpoint(c, srv.posthandshake); err != nil {
   730  		clog.Trace("Rejected peer before protocol handshake", "err", err)
   731  		c.close(err)
   732  		return
   733  	}
   734  	// Run the protocol handshake
   735  	phs, err := c.doProtoHandshake(srv.ourHandshake)
   736  	if err != nil {
   737  		clog.Trace("Failed proto handshake", "err", err)
   738  		c.close(err)
   739  		return
   740  	}
   741  	if phs.ID != c.id {
   742  		clog.Trace("Wrong devp2p handshake identity", "err", phs.ID)
   743  		c.close(DiscUnexpectedIdentity)
   744  		return
   745  	}
   746  	c.caps, c.name = phs.Caps, phs.Name
   747  	if err := srv.checkpoint(c, srv.addpeer); err != nil {
   748  		clog.Trace("Rejected peer", "err", err)
   749  		c.close(err)
   750  		return
   751  	}
   752  	// If the checks completed successfully, runPeer has now been
   753  	// launched by run.
   754  }
   755  
   756  func truncateName(s string) string {
   757  	if len(s) > 20 {
   758  		return s[:20] + "..."
   759  	}
   760  	return s
   761  }
   762  
   763  // checkpoint sends the conn to run, which performs the
   764  // post-handshake checks for the stage (posthandshake, addpeer).
   765  func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error {
   766  	select {
   767  	case stage <- c:
   768  	case <-srv.quit:
   769  		return errServerStopped
   770  	}
   771  	select {
   772  	case err := <-c.cont:
   773  		return err
   774  	case <-srv.quit:
   775  		return errServerStopped
   776  	}
   777  }
   778  
   779  // runPeer runs in its own goroutine for each peer.
   780  // it waits until the Peer logic returns and removes
   781  // the peer.
   782  func (srv *Server) runPeer(p *Peer) {
   783  	if srv.newPeerHook != nil {
   784  		srv.newPeerHook(p)
   785  	}
   786  
   787  	// broadcast peer add
   788  	srv.peerFeed.Send(&PeerEvent{
   789  		Type: PeerEventTypeAdd,
   790  		Peer: p.ID(),
   791  	})
   792  
   793  	// run the protocol
   794  	remoteRequested, err := p.run()
   795  
   796  	// broadcast peer drop
   797  	srv.peerFeed.Send(&PeerEvent{
   798  		Type:  PeerEventTypeDrop,
   799  		Peer:  p.ID(),
   800  		Error: err.Error(),
   801  	})
   802  
   803  	// Note: run waits for existing peers to be sent on srv.delpeer
   804  	// before returning, so this send should not select on srv.quit.
   805  	srv.delpeer <- peerDrop{p, err, remoteRequested}
   806  }
   807  
   808  // NodeInfo represents a short summary of the information known about the host.
   809  type NodeInfo struct {
   810  	ID    string `json:"id"`    // Unique node identifier (also the encryption key)
   811  	Name  string `json:"name"`  // Name of the node, including client type, version, OS, custom data
   812  	Enode string `json:"enode"` // Enode URL for adding this peer from remote peers
   813  	IP    string `json:"ip"`    // IP address of the node
   814  	Ports struct {
   815  		Discovery int `json:"discovery"` // UDP listening port for discovery protocol
   816  		Listener  int `json:"listener"`  // TCP listening port for RLPx
   817  	} `json:"ports"`
   818  	ListenAddr string                 `json:"listenAddr"`
   819  	Protocols  map[string]interface{} `json:"protocols"`
   820  }
   821  
   822  // NodeInfo gathers and returns a collection of metadata known about the host.
   823  func (srv *Server) NodeInfo() *NodeInfo {
   824  	node := srv.Self()
   825  
   826  	// Gather and assemble the generic node infos
   827  	info := &NodeInfo{
   828  		Name:       srv.Name,
   829  		Enode:      node.String(),
   830  		ID:         node.ID.String(),
   831  		IP:         node.IP.String(),
   832  		ListenAddr: srv.ListenAddr,
   833  		Protocols:  make(map[string]interface{}),
   834  	}
   835  	info.Ports.Discovery = int(node.UDP)
   836  	info.Ports.Listener = int(node.TCP)
   837  
   838  	// Gather all the running protocol infos (only once per protocol type)
   839  	for _, proto := range srv.Protocols {
   840  		if _, ok := info.Protocols[proto.Name]; !ok {
   841  			nodeInfo := interface{}("unknown")
   842  			if query := proto.NodeInfo; query != nil {
   843  				nodeInfo = proto.NodeInfo()
   844  			}
   845  			info.Protocols[proto.Name] = nodeInfo
   846  		}
   847  	}
   848  	return info
   849  }
   850  
   851  // PeersInfo returns an array of metadata objects describing connected peers.
   852  func (srv *Server) PeersInfo() []*PeerInfo {
   853  	// Gather all the generic and sub-protocol specific infos
   854  	infos := make([]*PeerInfo, 0, srv.PeerCount())
   855  	for _, peer := range srv.Peers() {
   856  		if peer != nil {
   857  			infos = append(infos, peer.Info())
   858  		}
   859  	}
   860  	// Sort the result array alphabetically by node identifier
   861  	for i := 0; i < len(infos); i++ {
   862  		for j := i + 1; j < len(infos); j++ {
   863  			if infos[i].ID > infos[j].ID {
   864  				infos[i], infos[j] = infos[j], infos[i]
   865  			}
   866  		}
   867  	}
   868  	return infos
   869  }