server.go 27 KB

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