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