v5_udp.go 24 KB

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