server.go 27 KB

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