server.go 31 KB

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