server.go 30 KB

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