server.go 27 KB

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