v5_udp.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. // Copyright 2019 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 discover
  17. import (
  18. "bytes"
  19. "context"
  20. "crypto/ecdsa"
  21. crand "crypto/rand"
  22. "errors"
  23. "fmt"
  24. "io"
  25. "math"
  26. "net"
  27. "sync"
  28. "time"
  29. "github.com/ethereum/go-ethereum/common/mclock"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/p2p/discover/v5wire"
  32. "github.com/ethereum/go-ethereum/p2p/enode"
  33. "github.com/ethereum/go-ethereum/p2p/enr"
  34. "github.com/ethereum/go-ethereum/p2p/netutil"
  35. )
  36. const (
  37. lookupRequestLimit = 3 // max requests against a single node during lookup
  38. findnodeResultLimit = 16 // applies in FINDNODE handler
  39. totalNodesResponseLimit = 5 // applies in waitForNodes
  40. nodesResponseItemLimit = 3 // applies in sendNodes
  41. respTimeoutV5 = 700 * time.Millisecond
  42. )
  43. // codecV5 is implemented by v5wire.Codec (and testCodec).
  44. //
  45. // The UDPv5 transport is split into two objects: the codec object deals with
  46. // encoding/decoding and with the handshake; the UDPv5 object handles higher-level concerns.
  47. type codecV5 interface {
  48. // Encode encodes a packet.
  49. Encode(enode.ID, string, v5wire.Packet, *v5wire.Whoareyou) ([]byte, v5wire.Nonce, error)
  50. // decode decodes a packet. It returns a *v5wire.Unknown packet if decryption fails.
  51. // The *enode.Node return value is non-nil when the input contains a handshake response.
  52. Decode([]byte, string) (enode.ID, *enode.Node, v5wire.Packet, error)
  53. }
  54. // UDPv5 is the implementation of protocol version 5.
  55. type UDPv5 struct {
  56. // static fields
  57. conn UDPConn
  58. tab *Table
  59. netrestrict *netutil.Netlist
  60. priv *ecdsa.PrivateKey
  61. localNode *enode.LocalNode
  62. db *enode.DB
  63. log log.Logger
  64. clock mclock.Clock
  65. validSchemes enr.IdentityScheme
  66. // talkreq handler registry
  67. trlock sync.Mutex
  68. trhandlers map[string]TalkRequestHandler
  69. // channels into dispatch
  70. packetInCh chan ReadPacket
  71. readNextCh chan struct{}
  72. callCh chan *callV5
  73. callDoneCh chan *callV5
  74. respTimeoutCh chan *callTimeout
  75. // state of dispatch
  76. codec codecV5
  77. activeCallByNode map[enode.ID]*callV5
  78. activeCallByAuth map[v5wire.Nonce]*callV5
  79. callQueue map[enode.ID][]*callV5
  80. // shutdown stuff
  81. closeOnce sync.Once
  82. closeCtx context.Context
  83. cancelCloseCtx context.CancelFunc
  84. wg sync.WaitGroup
  85. }
  86. // TalkRequestHandler callback processes a talk request and optionally returns a reply
  87. type TalkRequestHandler func(enode.ID, *net.UDPAddr, []byte) []byte
  88. // callV5 represents a remote procedure call against another node.
  89. type callV5 struct {
  90. node *enode.Node
  91. packet v5wire.Packet
  92. responseType byte // expected packet type of response
  93. reqid []byte
  94. ch chan v5wire.Packet // responses sent here
  95. err chan error // errors sent here
  96. // Valid for active calls only:
  97. nonce v5wire.Nonce // nonce of request packet
  98. handshakeCount int // # times we attempted handshake for this call
  99. challenge *v5wire.Whoareyou // last sent handshake challenge
  100. timeout mclock.Timer
  101. }
  102. // callTimeout is the response timeout event of a call.
  103. type callTimeout struct {
  104. c *callV5
  105. timer mclock.Timer
  106. }
  107. // ListenV5 listens on the given connection.
  108. func ListenV5(conn UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv5, error) {
  109. t, err := newUDPv5(conn, ln, cfg)
  110. if err != nil {
  111. return nil, err
  112. }
  113. go t.tab.loop()
  114. t.wg.Add(2)
  115. go t.readLoop()
  116. go t.dispatch()
  117. return t, nil
  118. }
  119. // newUDPv5 creates a UDPv5 transport, but doesn't start any goroutines.
  120. func newUDPv5(conn UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv5, error) {
  121. closeCtx, cancelCloseCtx := context.WithCancel(context.Background())
  122. cfg = cfg.withDefaults()
  123. t := &UDPv5{
  124. // static fields
  125. conn: conn,
  126. localNode: ln,
  127. db: ln.Database(),
  128. netrestrict: cfg.NetRestrict,
  129. priv: cfg.PrivateKey,
  130. log: cfg.Log,
  131. validSchemes: cfg.ValidSchemes,
  132. clock: cfg.Clock,
  133. trhandlers: make(map[string]TalkRequestHandler),
  134. // channels into dispatch
  135. packetInCh: make(chan ReadPacket, 1),
  136. readNextCh: make(chan struct{}, 1),
  137. callCh: make(chan *callV5),
  138. callDoneCh: make(chan *callV5),
  139. respTimeoutCh: make(chan *callTimeout),
  140. // state of dispatch
  141. codec: v5wire.NewCodec(ln, cfg.PrivateKey, cfg.Clock),
  142. activeCallByNode: make(map[enode.ID]*callV5),
  143. activeCallByAuth: make(map[v5wire.Nonce]*callV5),
  144. callQueue: make(map[enode.ID][]*callV5),
  145. // shutdown
  146. closeCtx: closeCtx,
  147. cancelCloseCtx: cancelCloseCtx,
  148. }
  149. tab, err := newTable(t, t.db, cfg.Bootnodes, cfg.Log)
  150. if err != nil {
  151. return nil, err
  152. }
  153. t.tab = tab
  154. return t, nil
  155. }
  156. // Self returns the local node record.
  157. func (t *UDPv5) Self() *enode.Node {
  158. return t.localNode.Node()
  159. }
  160. // Close shuts down packet processing.
  161. func (t *UDPv5) Close() {
  162. t.closeOnce.Do(func() {
  163. t.cancelCloseCtx()
  164. t.conn.Close()
  165. t.wg.Wait()
  166. t.tab.close()
  167. })
  168. }
  169. // Ping sends a ping message to the given node.
  170. func (t *UDPv5) Ping(n *enode.Node) error {
  171. _, err := t.ping(n)
  172. return err
  173. }
  174. // Resolve searches for a specific node with the given ID and tries to get the most recent
  175. // version of the node record for it. It returns n if the node could not be resolved.
  176. func (t *UDPv5) Resolve(n *enode.Node) *enode.Node {
  177. if intable := t.tab.getNode(n.ID()); intable != nil && intable.Seq() > n.Seq() {
  178. n = intable
  179. }
  180. // Try asking directly. This works if the node is still responding on the endpoint we have.
  181. if resp, err := t.RequestENR(n); err == nil {
  182. return resp
  183. }
  184. // Otherwise do a network lookup.
  185. result := t.Lookup(n.ID())
  186. for _, rn := range result {
  187. if rn.ID() == n.ID() && rn.Seq() > n.Seq() {
  188. return rn
  189. }
  190. }
  191. return n
  192. }
  193. // AllNodes returns all the nodes stored in the local table.
  194. func (t *UDPv5) AllNodes() []*enode.Node {
  195. t.tab.mutex.Lock()
  196. defer t.tab.mutex.Unlock()
  197. nodes := make([]*enode.Node, 0)
  198. for _, b := range &t.tab.buckets {
  199. for _, n := range b.entries {
  200. nodes = append(nodes, unwrapNode(n))
  201. }
  202. }
  203. return nodes
  204. }
  205. // LocalNode returns the current local node running the
  206. // protocol.
  207. func (t *UDPv5) LocalNode() *enode.LocalNode {
  208. return t.localNode
  209. }
  210. // RegisterTalkHandler adds a handler for 'talk requests'. The handler function is called
  211. // whenever a request for the given protocol is received and should return the response
  212. // data or nil.
  213. func (t *UDPv5) RegisterTalkHandler(protocol string, handler TalkRequestHandler) {
  214. t.trlock.Lock()
  215. defer t.trlock.Unlock()
  216. t.trhandlers[protocol] = handler
  217. }
  218. // TalkRequest sends a talk request to n and waits for a response.
  219. func (t *UDPv5) TalkRequest(n *enode.Node, protocol string, request []byte) ([]byte, error) {
  220. req := &v5wire.TalkRequest{Protocol: protocol, Message: request}
  221. resp := t.call(n, v5wire.TalkResponseMsg, req)
  222. defer t.callDone(resp)
  223. select {
  224. case respMsg := <-resp.ch:
  225. return respMsg.(*v5wire.TalkResponse).Message, nil
  226. case err := <-resp.err:
  227. return nil, err
  228. }
  229. }
  230. // RandomNodes returns an iterator that finds random nodes in the DHT.
  231. func (t *UDPv5) RandomNodes() enode.Iterator {
  232. if t.tab.len() == 0 {
  233. // All nodes were dropped, refresh. The very first query will hit this
  234. // case and run the bootstrapping logic.
  235. <-t.tab.refresh()
  236. }
  237. return newLookupIterator(t.closeCtx, t.newRandomLookup)
  238. }
  239. // Lookup performs a recursive lookup for the given target.
  240. // It returns the closest nodes to target.
  241. func (t *UDPv5) Lookup(target enode.ID) []*enode.Node {
  242. return t.newLookup(t.closeCtx, target).run()
  243. }
  244. // lookupRandom looks up a random target.
  245. // This is needed to satisfy the transport interface.
  246. func (t *UDPv5) lookupRandom() []*enode.Node {
  247. return t.newRandomLookup(t.closeCtx).run()
  248. }
  249. // lookupSelf looks up our own node ID.
  250. // This is needed to satisfy the transport interface.
  251. func (t *UDPv5) lookupSelf() []*enode.Node {
  252. return t.newLookup(t.closeCtx, t.Self().ID()).run()
  253. }
  254. func (t *UDPv5) newRandomLookup(ctx context.Context) *lookup {
  255. var target enode.ID
  256. crand.Read(target[:])
  257. return t.newLookup(ctx, target)
  258. }
  259. func (t *UDPv5) newLookup(ctx context.Context, target enode.ID) *lookup {
  260. return newLookup(ctx, t.tab, target, func(n *node) ([]*node, error) {
  261. return t.lookupWorker(n, target)
  262. })
  263. }
  264. // lookupWorker performs FINDNODE calls against a single node during lookup.
  265. func (t *UDPv5) lookupWorker(destNode *node, target enode.ID) ([]*node, error) {
  266. var (
  267. dists = lookupDistances(target, destNode.ID())
  268. nodes = nodesByDistance{target: target}
  269. err error
  270. )
  271. var r []*enode.Node
  272. r, err = t.findnode(unwrapNode(destNode), dists)
  273. if err == errClosed {
  274. return nil, err
  275. }
  276. for _, n := range r {
  277. if n.ID() != t.Self().ID() {
  278. nodes.push(wrapNode(n), findnodeResultLimit)
  279. }
  280. }
  281. return nodes.entries, err
  282. }
  283. // lookupDistances computes the distance parameter for FINDNODE calls to dest.
  284. // It chooses distances adjacent to logdist(target, dest), e.g. for a target
  285. // with logdist(target, dest) = 255 the result is [255, 256, 254].
  286. func lookupDistances(target, dest enode.ID) (dists []uint) {
  287. td := enode.LogDist(target, dest)
  288. dists = append(dists, uint(td))
  289. for i := 1; len(dists) < lookupRequestLimit; i++ {
  290. if td+i < 256 {
  291. dists = append(dists, uint(td+i))
  292. }
  293. if td-i > 0 {
  294. dists = append(dists, uint(td-i))
  295. }
  296. }
  297. return dists
  298. }
  299. // ping calls PING on a node and waits for a PONG response.
  300. func (t *UDPv5) ping(n *enode.Node) (uint64, error) {
  301. req := &v5wire.Ping{ENRSeq: t.localNode.Node().Seq()}
  302. resp := t.call(n, v5wire.PongMsg, req)
  303. defer t.callDone(resp)
  304. select {
  305. case pong := <-resp.ch:
  306. return pong.(*v5wire.Pong).ENRSeq, nil
  307. case err := <-resp.err:
  308. return 0, err
  309. }
  310. }
  311. // requestENR requests n's record.
  312. func (t *UDPv5) RequestENR(n *enode.Node) (*enode.Node, error) {
  313. nodes, err := t.findnode(n, []uint{0})
  314. if err != nil {
  315. return nil, err
  316. }
  317. if len(nodes) != 1 {
  318. return nil, fmt.Errorf("%d nodes in response for distance zero", len(nodes))
  319. }
  320. return nodes[0], nil
  321. }
  322. // findnode calls FINDNODE on a node and waits for responses.
  323. func (t *UDPv5) findnode(n *enode.Node, distances []uint) ([]*enode.Node, error) {
  324. resp := t.call(n, v5wire.NodesMsg, &v5wire.Findnode{Distances: distances})
  325. return t.waitForNodes(resp, distances)
  326. }
  327. // waitForNodes waits for NODES responses to the given call.
  328. func (t *UDPv5) waitForNodes(c *callV5, distances []uint) ([]*enode.Node, error) {
  329. defer t.callDone(c)
  330. var (
  331. nodes []*enode.Node
  332. seen = make(map[enode.ID]struct{})
  333. received, total = 0, -1
  334. )
  335. for {
  336. select {
  337. case responseP := <-c.ch:
  338. response := responseP.(*v5wire.Nodes)
  339. for _, record := range response.Nodes {
  340. node, err := t.verifyResponseNode(c, record, distances, seen)
  341. if err != nil {
  342. t.log.Debug("Invalid record in "+response.Name(), "id", c.node.ID(), "err", err)
  343. continue
  344. }
  345. nodes = append(nodes, node)
  346. }
  347. if total == -1 {
  348. total = min(int(response.Total), totalNodesResponseLimit)
  349. }
  350. if received++; received == total {
  351. return nodes, nil
  352. }
  353. case err := <-c.err:
  354. return nodes, err
  355. }
  356. }
  357. }
  358. // verifyResponseNode checks validity of a record in a NODES response.
  359. func (t *UDPv5) verifyResponseNode(c *callV5, r *enr.Record, distances []uint, seen map[enode.ID]struct{}) (*enode.Node, error) {
  360. node, err := enode.New(t.validSchemes, r)
  361. if err != nil {
  362. return nil, err
  363. }
  364. if err := netutil.CheckRelayIP(c.node.IP(), node.IP()); err != nil {
  365. return nil, err
  366. }
  367. if c.node.UDP() <= 1024 {
  368. return nil, errLowPort
  369. }
  370. if distances != nil {
  371. nd := enode.LogDist(c.node.ID(), node.ID())
  372. if !containsUint(uint(nd), distances) {
  373. return nil, errors.New("does not match any requested distance")
  374. }
  375. }
  376. if _, ok := seen[node.ID()]; ok {
  377. return nil, fmt.Errorf("duplicate record")
  378. }
  379. seen[node.ID()] = struct{}{}
  380. return node, nil
  381. }
  382. func containsUint(x uint, xs []uint) bool {
  383. for _, v := range xs {
  384. if x == v {
  385. return true
  386. }
  387. }
  388. return false
  389. }
  390. // call sends the given call and sets up a handler for response packets (of message type
  391. // responseType). Responses are dispatched to the call's response channel.
  392. func (t *UDPv5) call(node *enode.Node, responseType byte, packet v5wire.Packet) *callV5 {
  393. c := &callV5{
  394. node: node,
  395. packet: packet,
  396. responseType: responseType,
  397. reqid: make([]byte, 8),
  398. ch: make(chan v5wire.Packet, 1),
  399. err: make(chan error, 1),
  400. }
  401. // Assign request ID.
  402. crand.Read(c.reqid)
  403. packet.SetRequestID(c.reqid)
  404. // Send call to dispatch.
  405. select {
  406. case t.callCh <- c:
  407. case <-t.closeCtx.Done():
  408. c.err <- errClosed
  409. }
  410. return c
  411. }
  412. // callDone tells dispatch that the active call is done.
  413. func (t *UDPv5) callDone(c *callV5) {
  414. // This needs a loop because further responses may be incoming until the
  415. // send to callDoneCh has completed. Such responses need to be discarded
  416. // in order to avoid blocking the dispatch loop.
  417. for {
  418. select {
  419. case <-c.ch:
  420. // late response, discard.
  421. case <-c.err:
  422. // late error, discard.
  423. case t.callDoneCh <- c:
  424. return
  425. case <-t.closeCtx.Done():
  426. return
  427. }
  428. }
  429. }
  430. // dispatch runs in its own goroutine, handles incoming packets and deals with calls.
  431. //
  432. // For any destination node there is at most one 'active call', stored in the t.activeCall*
  433. // maps. A call is made active when it is sent. The active call can be answered by a
  434. // matching response, in which case c.ch receives the response; or by timing out, in which case
  435. // c.err receives the error. When the function that created the call signals the active
  436. // call is done through callDone, the next call from the call queue is started.
  437. //
  438. // Calls may also be answered by a WHOAREYOU packet referencing the call packet's authTag.
  439. // When that happens the call is simply re-sent to complete the handshake. We allow one
  440. // handshake attempt per call.
  441. func (t *UDPv5) dispatch() {
  442. defer t.wg.Done()
  443. // Arm first read.
  444. t.readNextCh <- struct{}{}
  445. for {
  446. select {
  447. case c := <-t.callCh:
  448. id := c.node.ID()
  449. t.callQueue[id] = append(t.callQueue[id], c)
  450. t.sendNextCall(id)
  451. case ct := <-t.respTimeoutCh:
  452. active := t.activeCallByNode[ct.c.node.ID()]
  453. if ct.c == active && ct.timer == active.timeout {
  454. ct.c.err <- errTimeout
  455. }
  456. case c := <-t.callDoneCh:
  457. id := c.node.ID()
  458. active := t.activeCallByNode[id]
  459. if active != c {
  460. panic("BUG: callDone for inactive call")
  461. }
  462. c.timeout.Stop()
  463. delete(t.activeCallByAuth, c.nonce)
  464. delete(t.activeCallByNode, id)
  465. t.sendNextCall(id)
  466. case p := <-t.packetInCh:
  467. t.handlePacket(p.Data, p.Addr)
  468. // Arm next read.
  469. t.readNextCh <- struct{}{}
  470. case <-t.closeCtx.Done():
  471. close(t.readNextCh)
  472. for id, queue := range t.callQueue {
  473. for _, c := range queue {
  474. c.err <- errClosed
  475. }
  476. delete(t.callQueue, id)
  477. }
  478. for id, c := range t.activeCallByNode {
  479. c.err <- errClosed
  480. delete(t.activeCallByNode, id)
  481. delete(t.activeCallByAuth, c.nonce)
  482. }
  483. return
  484. }
  485. }
  486. }
  487. // startResponseTimeout sets the response timer for a call.
  488. func (t *UDPv5) startResponseTimeout(c *callV5) {
  489. if c.timeout != nil {
  490. c.timeout.Stop()
  491. }
  492. var (
  493. timer mclock.Timer
  494. done = make(chan struct{})
  495. )
  496. timer = t.clock.AfterFunc(respTimeoutV5, func() {
  497. <-done
  498. select {
  499. case t.respTimeoutCh <- &callTimeout{c, timer}:
  500. case <-t.closeCtx.Done():
  501. }
  502. })
  503. c.timeout = timer
  504. close(done)
  505. }
  506. // sendNextCall sends the next call in the call queue if there is no active call.
  507. func (t *UDPv5) sendNextCall(id enode.ID) {
  508. queue := t.callQueue[id]
  509. if len(queue) == 0 || t.activeCallByNode[id] != nil {
  510. return
  511. }
  512. t.activeCallByNode[id] = queue[0]
  513. t.sendCall(t.activeCallByNode[id])
  514. if len(queue) == 1 {
  515. delete(t.callQueue, id)
  516. } else {
  517. copy(queue, queue[1:])
  518. t.callQueue[id] = queue[:len(queue)-1]
  519. }
  520. }
  521. // sendCall encodes and sends a request packet to the call's recipient node.
  522. // This performs a handshake if needed.
  523. func (t *UDPv5) sendCall(c *callV5) {
  524. // The call might have a nonce from a previous handshake attempt. Remove the entry for
  525. // the old nonce because we're about to generate a new nonce for this call.
  526. if c.nonce != (v5wire.Nonce{}) {
  527. delete(t.activeCallByAuth, c.nonce)
  528. }
  529. addr := &net.UDPAddr{IP: c.node.IP(), Port: c.node.UDP()}
  530. newNonce, _ := t.send(c.node.ID(), addr, c.packet, c.challenge)
  531. c.nonce = newNonce
  532. t.activeCallByAuth[newNonce] = c
  533. t.startResponseTimeout(c)
  534. }
  535. // sendResponse sends a response packet to the given node.
  536. // This doesn't trigger a handshake even if no keys are available.
  537. func (t *UDPv5) sendResponse(toID enode.ID, toAddr *net.UDPAddr, packet v5wire.Packet) error {
  538. _, err := t.send(toID, toAddr, packet, nil)
  539. return err
  540. }
  541. // send sends a packet to the given node.
  542. func (t *UDPv5) send(toID enode.ID, toAddr *net.UDPAddr, packet v5wire.Packet, c *v5wire.Whoareyou) (v5wire.Nonce, error) {
  543. addr := toAddr.String()
  544. enc, nonce, err := t.codec.Encode(toID, addr, packet, c)
  545. if err != nil {
  546. t.log.Warn(">> "+packet.Name(), "id", toID, "addr", addr, "err", err)
  547. return nonce, err
  548. }
  549. _, err = t.conn.WriteToUDP(enc, toAddr)
  550. t.log.Trace(">> "+packet.Name(), "id", toID, "addr", addr)
  551. return nonce, err
  552. }
  553. // readLoop runs in its own goroutine and reads packets from the network.
  554. func (t *UDPv5) readLoop() {
  555. defer t.wg.Done()
  556. buf := make([]byte, maxPacketSize)
  557. for range t.readNextCh {
  558. nbytes, from, err := t.conn.ReadFromUDP(buf)
  559. if netutil.IsTemporaryError(err) {
  560. // Ignore temporary read errors.
  561. t.log.Debug("Temporary UDP read error", "err", err)
  562. continue
  563. } else if err != nil {
  564. // Shut down the loop for permament errors.
  565. if err != io.EOF {
  566. t.log.Debug("UDP read error", "err", err)
  567. }
  568. return
  569. }
  570. t.dispatchReadPacket(from, buf[:nbytes])
  571. }
  572. }
  573. // dispatchReadPacket sends a packet into the dispatch loop.
  574. func (t *UDPv5) dispatchReadPacket(from *net.UDPAddr, content []byte) bool {
  575. select {
  576. case t.packetInCh <- ReadPacket{content, from}:
  577. return true
  578. case <-t.closeCtx.Done():
  579. return false
  580. }
  581. }
  582. // handlePacket decodes and processes an incoming packet from the network.
  583. func (t *UDPv5) handlePacket(rawpacket []byte, fromAddr *net.UDPAddr) error {
  584. addr := fromAddr.String()
  585. fromID, fromNode, packet, err := t.codec.Decode(rawpacket, addr)
  586. if err != nil {
  587. t.log.Debug("Bad discv5 packet", "id", fromID, "addr", addr, "err", err)
  588. return err
  589. }
  590. if fromNode != nil {
  591. // Handshake succeeded, add to table.
  592. t.tab.addSeenNode(wrapNode(fromNode))
  593. }
  594. if packet.Kind() != v5wire.WhoareyouPacket {
  595. // WHOAREYOU logged separately to report errors.
  596. t.log.Trace("<< "+packet.Name(), "id", fromID, "addr", addr)
  597. }
  598. t.handle(packet, fromID, fromAddr)
  599. return nil
  600. }
  601. // handleCallResponse dispatches a response packet to the call waiting for it.
  602. func (t *UDPv5) handleCallResponse(fromID enode.ID, fromAddr *net.UDPAddr, p v5wire.Packet) bool {
  603. ac := t.activeCallByNode[fromID]
  604. if ac == nil || !bytes.Equal(p.RequestID(), ac.reqid) {
  605. t.log.Debug(fmt.Sprintf("Unsolicited/late %s response", p.Name()), "id", fromID, "addr", fromAddr)
  606. return false
  607. }
  608. if !fromAddr.IP.Equal(ac.node.IP()) || fromAddr.Port != ac.node.UDP() {
  609. t.log.Debug(fmt.Sprintf("%s from wrong endpoint", p.Name()), "id", fromID, "addr", fromAddr)
  610. return false
  611. }
  612. if p.Kind() != ac.responseType {
  613. t.log.Debug(fmt.Sprintf("Wrong discv5 response type %s", p.Name()), "id", fromID, "addr", fromAddr)
  614. return false
  615. }
  616. t.startResponseTimeout(ac)
  617. ac.ch <- p
  618. return true
  619. }
  620. // getNode looks for a node record in table and database.
  621. func (t *UDPv5) getNode(id enode.ID) *enode.Node {
  622. if n := t.tab.getNode(id); n != nil {
  623. return n
  624. }
  625. if n := t.localNode.Database().Node(id); n != nil {
  626. return n
  627. }
  628. return nil
  629. }
  630. // handle processes incoming packets according to their message type.
  631. func (t *UDPv5) handle(p v5wire.Packet, fromID enode.ID, fromAddr *net.UDPAddr) {
  632. switch p := p.(type) {
  633. case *v5wire.Unknown:
  634. t.handleUnknown(p, fromID, fromAddr)
  635. case *v5wire.Whoareyou:
  636. t.handleWhoareyou(p, fromID, fromAddr)
  637. case *v5wire.Ping:
  638. t.handlePing(p, fromID, fromAddr)
  639. case *v5wire.Pong:
  640. if t.handleCallResponse(fromID, fromAddr, p) {
  641. t.localNode.UDPEndpointStatement(fromAddr, &net.UDPAddr{IP: p.ToIP, Port: int(p.ToPort)})
  642. }
  643. case *v5wire.Findnode:
  644. t.handleFindnode(p, fromID, fromAddr)
  645. case *v5wire.Nodes:
  646. t.handleCallResponse(fromID, fromAddr, p)
  647. case *v5wire.TalkRequest:
  648. t.handleTalkRequest(p, fromID, fromAddr)
  649. case *v5wire.TalkResponse:
  650. t.handleCallResponse(fromID, fromAddr, p)
  651. }
  652. }
  653. // handleUnknown initiates a handshake by responding with WHOAREYOU.
  654. func (t *UDPv5) handleUnknown(p *v5wire.Unknown, fromID enode.ID, fromAddr *net.UDPAddr) {
  655. challenge := &v5wire.Whoareyou{Nonce: p.Nonce}
  656. crand.Read(challenge.IDNonce[:])
  657. if n := t.getNode(fromID); n != nil {
  658. challenge.Node = n
  659. challenge.RecordSeq = n.Seq()
  660. }
  661. t.sendResponse(fromID, fromAddr, challenge)
  662. }
  663. var (
  664. errChallengeNoCall = errors.New("no matching call")
  665. errChallengeTwice = errors.New("second handshake")
  666. )
  667. // handleWhoareyou resends the active call as a handshake packet.
  668. func (t *UDPv5) handleWhoareyou(p *v5wire.Whoareyou, fromID enode.ID, fromAddr *net.UDPAddr) {
  669. c, err := t.matchWithCall(fromID, p.Nonce)
  670. if err != nil {
  671. t.log.Debug("Invalid "+p.Name(), "addr", fromAddr, "err", err)
  672. return
  673. }
  674. // Resend the call that was answered by WHOAREYOU.
  675. t.log.Trace("<< "+p.Name(), "id", c.node.ID(), "addr", fromAddr)
  676. c.handshakeCount++
  677. c.challenge = p
  678. p.Node = c.node
  679. t.sendCall(c)
  680. }
  681. // matchWithCall checks whether a handshake attempt matches the active call.
  682. func (t *UDPv5) matchWithCall(fromID enode.ID, nonce v5wire.Nonce) (*callV5, error) {
  683. c := t.activeCallByAuth[nonce]
  684. if c == nil {
  685. return nil, errChallengeNoCall
  686. }
  687. if c.handshakeCount > 0 {
  688. return nil, errChallengeTwice
  689. }
  690. return c, nil
  691. }
  692. // handlePing sends a PONG response.
  693. func (t *UDPv5) handlePing(p *v5wire.Ping, fromID enode.ID, fromAddr *net.UDPAddr) {
  694. remoteIP := fromAddr.IP
  695. // Handle IPv4 mapped IPv6 addresses in the
  696. // event the local node is binded to an
  697. // ipv6 interface.
  698. if remoteIP.To4() != nil {
  699. remoteIP = remoteIP.To4()
  700. }
  701. t.sendResponse(fromID, fromAddr, &v5wire.Pong{
  702. ReqID: p.ReqID,
  703. ToIP: remoteIP,
  704. ToPort: uint16(fromAddr.Port),
  705. ENRSeq: t.localNode.Node().Seq(),
  706. })
  707. }
  708. // handleFindnode returns nodes to the requester.
  709. func (t *UDPv5) handleFindnode(p *v5wire.Findnode, fromID enode.ID, fromAddr *net.UDPAddr) {
  710. nodes := t.collectTableNodes(fromAddr.IP, p.Distances, findnodeResultLimit)
  711. for _, resp := range packNodes(p.ReqID, nodes) {
  712. t.sendResponse(fromID, fromAddr, resp)
  713. }
  714. }
  715. // collectTableNodes creates a FINDNODE result set for the given distances.
  716. func (t *UDPv5) collectTableNodes(rip net.IP, distances []uint, limit int) []*enode.Node {
  717. var nodes []*enode.Node
  718. var processed = make(map[uint]struct{})
  719. for _, dist := range distances {
  720. // Reject duplicate / invalid distances.
  721. _, seen := processed[dist]
  722. if seen || dist > 256 {
  723. continue
  724. }
  725. // Get the nodes.
  726. var bn []*enode.Node
  727. if dist == 0 {
  728. bn = []*enode.Node{t.Self()}
  729. } else if dist <= 256 {
  730. t.tab.mutex.Lock()
  731. bn = unwrapNodes(t.tab.bucketAtDistance(int(dist)).entries)
  732. t.tab.mutex.Unlock()
  733. }
  734. processed[dist] = struct{}{}
  735. // Apply some pre-checks to avoid sending invalid nodes.
  736. for _, n := range bn {
  737. // TODO livenessChecks > 1
  738. if netutil.CheckRelayIP(rip, n.IP()) != nil {
  739. continue
  740. }
  741. nodes = append(nodes, n)
  742. if len(nodes) >= limit {
  743. return nodes
  744. }
  745. }
  746. }
  747. return nodes
  748. }
  749. // packNodes creates NODES response packets for the given node list.
  750. func packNodes(reqid []byte, nodes []*enode.Node) []*v5wire.Nodes {
  751. if len(nodes) == 0 {
  752. return []*v5wire.Nodes{{ReqID: reqid, Total: 1}}
  753. }
  754. total := uint8(math.Ceil(float64(len(nodes)) / 3))
  755. var resp []*v5wire.Nodes
  756. for len(nodes) > 0 {
  757. p := &v5wire.Nodes{ReqID: reqid, Total: total}
  758. items := min(nodesResponseItemLimit, len(nodes))
  759. for i := 0; i < items; i++ {
  760. p.Nodes = append(p.Nodes, nodes[i].Record())
  761. }
  762. nodes = nodes[items:]
  763. resp = append(resp, p)
  764. }
  765. return resp
  766. }
  767. // handleTalkRequest runs the talk request handler of the requested protocol.
  768. func (t *UDPv5) handleTalkRequest(p *v5wire.TalkRequest, fromID enode.ID, fromAddr *net.UDPAddr) {
  769. t.trlock.Lock()
  770. handler := t.trhandlers[p.Protocol]
  771. t.trlock.Unlock()
  772. var response []byte
  773. if handler != nil {
  774. response = handler(fromID, fromAddr, p.Message)
  775. }
  776. resp := &v5wire.TalkResponse{ReqID: p.ReqID, Message: response}
  777. t.sendResponse(fromID, fromAddr, resp)
  778. }