server.go 29 KB

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