v4_udp.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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. "container/list"
  20. "context"
  21. "crypto/ecdsa"
  22. crand "crypto/rand"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "net"
  27. "sync"
  28. "time"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/p2p/enode"
  32. "github.com/ethereum/go-ethereum/p2p/enr"
  33. "github.com/ethereum/go-ethereum/p2p/netutil"
  34. "github.com/ethereum/go-ethereum/rlp"
  35. )
  36. // Errors
  37. var (
  38. errPacketTooSmall = errors.New("too small")
  39. errBadHash = errors.New("bad hash")
  40. errExpired = errors.New("expired")
  41. errUnsolicitedReply = errors.New("unsolicited reply")
  42. errUnknownNode = errors.New("unknown node")
  43. errTimeout = errors.New("RPC timeout")
  44. errClockWarp = errors.New("reply deadline too far in the future")
  45. errClosed = errors.New("socket closed")
  46. )
  47. const (
  48. respTimeout = 500 * time.Millisecond
  49. expiration = 20 * time.Second
  50. bondExpiration = 24 * time.Hour
  51. maxFindnodeFailures = 5 // nodes exceeding this limit are dropped
  52. ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP
  53. ntpWarningCooldown = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning
  54. driftThreshold = 10 * time.Second // Allowed clock drift before warning user
  55. // Discovery packets are defined to be no larger than 1280 bytes.
  56. // Packets larger than this size will be cut at the end and treated
  57. // as invalid because their hash won't match.
  58. maxPacketSize = 1280
  59. )
  60. // RPC packet types
  61. const (
  62. p_pingV4 = iota + 1 // zero is 'reserved'
  63. p_pongV4
  64. p_findnodeV4
  65. p_neighborsV4
  66. p_enrRequestV4
  67. p_enrResponseV4
  68. )
  69. // RPC request structures
  70. type (
  71. pingV4 struct {
  72. senderKey *ecdsa.PublicKey // filled in by preverify
  73. Version uint
  74. From, To rpcEndpoint
  75. Expiration uint64
  76. // Ignore additional fields (for forward compatibility).
  77. Rest []rlp.RawValue `rlp:"tail"`
  78. }
  79. // pongV4 is the reply to pingV4.
  80. pongV4 struct {
  81. // This field should mirror the UDP envelope address
  82. // of the ping packet, which provides a way to discover the
  83. // the external address (after NAT).
  84. To rpcEndpoint
  85. ReplyTok []byte // This contains the hash of the ping packet.
  86. Expiration uint64 // Absolute timestamp at which the packet becomes invalid.
  87. // Ignore additional fields (for forward compatibility).
  88. Rest []rlp.RawValue `rlp:"tail"`
  89. }
  90. // findnodeV4 is a query for nodes close to the given target.
  91. findnodeV4 struct {
  92. Target encPubkey
  93. Expiration uint64
  94. // Ignore additional fields (for forward compatibility).
  95. Rest []rlp.RawValue `rlp:"tail"`
  96. }
  97. // neighborsV4 is the reply to findnodeV4.
  98. neighborsV4 struct {
  99. Nodes []rpcNode
  100. Expiration uint64
  101. // Ignore additional fields (for forward compatibility).
  102. Rest []rlp.RawValue `rlp:"tail"`
  103. }
  104. // enrRequestV4 queries for the remote node's record.
  105. enrRequestV4 struct {
  106. Expiration uint64
  107. // Ignore additional fields (for forward compatibility).
  108. Rest []rlp.RawValue `rlp:"tail"`
  109. }
  110. // enrResponseV4 is the reply to enrRequestV4.
  111. enrResponseV4 struct {
  112. ReplyTok []byte // Hash of the enrRequest packet.
  113. Record enr.Record
  114. // Ignore additional fields (for forward compatibility).
  115. Rest []rlp.RawValue `rlp:"tail"`
  116. }
  117. rpcNode struct {
  118. IP net.IP // len 4 for IPv4 or 16 for IPv6
  119. UDP uint16 // for discovery protocol
  120. TCP uint16 // for RLPx protocol
  121. ID encPubkey
  122. }
  123. rpcEndpoint struct {
  124. IP net.IP // len 4 for IPv4 or 16 for IPv6
  125. UDP uint16 // for discovery protocol
  126. TCP uint16 // for RLPx protocol
  127. }
  128. )
  129. // packetV4 is implemented by all v4 protocol messages.
  130. type packetV4 interface {
  131. // preverify checks whether the packet is valid and should be handled at all.
  132. preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error
  133. // handle handles the packet.
  134. handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte)
  135. // packet name and type for logging purposes.
  136. name() string
  137. kind() byte
  138. }
  139. func makeEndpoint(addr *net.UDPAddr, tcpPort uint16) rpcEndpoint {
  140. ip := net.IP{}
  141. if ip4 := addr.IP.To4(); ip4 != nil {
  142. ip = ip4
  143. } else if ip6 := addr.IP.To16(); ip6 != nil {
  144. ip = ip6
  145. }
  146. return rpcEndpoint{IP: ip, UDP: uint16(addr.Port), TCP: tcpPort}
  147. }
  148. func (t *UDPv4) nodeFromRPC(sender *net.UDPAddr, rn rpcNode) (*node, error) {
  149. if rn.UDP <= 1024 {
  150. return nil, errors.New("low port")
  151. }
  152. if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil {
  153. return nil, err
  154. }
  155. if t.netrestrict != nil && !t.netrestrict.Contains(rn.IP) {
  156. return nil, errors.New("not contained in netrestrict whitelist")
  157. }
  158. key, err := decodePubkey(rn.ID)
  159. if err != nil {
  160. return nil, err
  161. }
  162. n := wrapNode(enode.NewV4(key, rn.IP, int(rn.TCP), int(rn.UDP)))
  163. err = n.ValidateComplete()
  164. return n, err
  165. }
  166. func nodeToRPC(n *node) rpcNode {
  167. var key ecdsa.PublicKey
  168. var ekey encPubkey
  169. if err := n.Load((*enode.Secp256k1)(&key)); err == nil {
  170. ekey = encodePubkey(&key)
  171. }
  172. return rpcNode{ID: ekey, IP: n.IP(), UDP: uint16(n.UDP()), TCP: uint16(n.TCP())}
  173. }
  174. // UDPv4 implements the v4 wire protocol.
  175. type UDPv4 struct {
  176. conn UDPConn
  177. log log.Logger
  178. netrestrict *netutil.Netlist
  179. priv *ecdsa.PrivateKey
  180. localNode *enode.LocalNode
  181. db *enode.DB
  182. tab *Table
  183. closeOnce sync.Once
  184. wg sync.WaitGroup
  185. addReplyMatcher chan *replyMatcher
  186. gotreply chan reply
  187. closeCtx context.Context
  188. cancelCloseCtx func()
  189. }
  190. // replyMatcher represents a pending reply.
  191. //
  192. // Some implementations of the protocol wish to send more than one
  193. // reply packet to findnode. In general, any neighbors packet cannot
  194. // be matched up with a specific findnode packet.
  195. //
  196. // Our implementation handles this by storing a callback function for
  197. // each pending reply. Incoming packets from a node are dispatched
  198. // to all callback functions for that node.
  199. type replyMatcher struct {
  200. // these fields must match in the reply.
  201. from enode.ID
  202. ip net.IP
  203. ptype byte
  204. // time when the request must complete
  205. deadline time.Time
  206. // callback is called when a matching reply arrives. If it returns matched == true, the
  207. // reply was acceptable. The second return value indicates whether the callback should
  208. // be removed from the pending reply queue. If it returns false, the reply is considered
  209. // incomplete and the callback will be invoked again for the next matching reply.
  210. callback replyMatchFunc
  211. // errc receives nil when the callback indicates completion or an
  212. // error if no further reply is received within the timeout.
  213. errc chan error
  214. // reply contains the most recent reply. This field is safe for reading after errc has
  215. // received a value.
  216. reply packetV4
  217. }
  218. type replyMatchFunc func(interface{}) (matched bool, requestDone bool)
  219. // reply is a reply packet from a certain node.
  220. type reply struct {
  221. from enode.ID
  222. ip net.IP
  223. data packetV4
  224. // loop indicates whether there was
  225. // a matching request by sending on this channel.
  226. matched chan<- bool
  227. }
  228. func ListenV4(c UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv4, error) {
  229. closeCtx, cancel := context.WithCancel(context.Background())
  230. t := &UDPv4{
  231. conn: c,
  232. priv: cfg.PrivateKey,
  233. netrestrict: cfg.NetRestrict,
  234. localNode: ln,
  235. db: ln.Database(),
  236. gotreply: make(chan reply),
  237. addReplyMatcher: make(chan *replyMatcher),
  238. closeCtx: closeCtx,
  239. cancelCloseCtx: cancel,
  240. log: cfg.Log,
  241. }
  242. if t.log == nil {
  243. t.log = log.Root()
  244. }
  245. tab, err := newTable(t, ln.Database(), cfg.Bootnodes, t.log)
  246. if err != nil {
  247. return nil, err
  248. }
  249. t.tab = tab
  250. go tab.loop()
  251. t.wg.Add(2)
  252. go t.loop()
  253. go t.readLoop(cfg.Unhandled)
  254. return t, nil
  255. }
  256. // Self returns the local node.
  257. func (t *UDPv4) Self() *enode.Node {
  258. return t.localNode.Node()
  259. }
  260. // Close shuts down the socket and aborts any running queries.
  261. func (t *UDPv4) Close() {
  262. t.closeOnce.Do(func() {
  263. t.cancelCloseCtx()
  264. t.conn.Close()
  265. t.wg.Wait()
  266. t.tab.close()
  267. })
  268. }
  269. // Resolve searches for a specific node with the given ID and tries to get the most recent
  270. // version of the node record for it. It returns n if the node could not be resolved.
  271. func (t *UDPv4) Resolve(n *enode.Node) *enode.Node {
  272. // Try asking directly. This works if the node is still responding on the endpoint we have.
  273. if rn, err := t.RequestENR(n); err == nil {
  274. return rn
  275. }
  276. // Check table for the ID, we might have a newer version there.
  277. if intable := t.tab.getNode(n.ID()); intable != nil && intable.Seq() > n.Seq() {
  278. n = intable
  279. if rn, err := t.RequestENR(n); err == nil {
  280. return rn
  281. }
  282. }
  283. // Otherwise perform a network lookup.
  284. var key enode.Secp256k1
  285. if n.Load(&key) != nil {
  286. return n // no secp256k1 key
  287. }
  288. result := t.LookupPubkey((*ecdsa.PublicKey)(&key))
  289. for _, rn := range result {
  290. if rn.ID() == n.ID() {
  291. if rn, err := t.RequestENR(rn); err == nil {
  292. return rn
  293. }
  294. }
  295. }
  296. return n
  297. }
  298. func (t *UDPv4) ourEndpoint() rpcEndpoint {
  299. n := t.Self()
  300. a := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
  301. return makeEndpoint(a, uint16(n.TCP()))
  302. }
  303. // Ping sends a ping message to the given node.
  304. func (t *UDPv4) Ping(n *enode.Node) error {
  305. _, err := t.ping(n)
  306. return err
  307. }
  308. // ping sends a ping message to the given node and waits for a reply.
  309. func (t *UDPv4) ping(n *enode.Node) (seq uint64, err error) {
  310. rm := t.sendPing(n.ID(), &net.UDPAddr{IP: n.IP(), Port: n.UDP()}, nil)
  311. if err = <-rm.errc; err == nil {
  312. seq = seqFromTail(rm.reply.(*pongV4).Rest)
  313. }
  314. return seq, err
  315. }
  316. // sendPing sends a ping message to the given node and invokes the callback
  317. // when the reply arrives.
  318. func (t *UDPv4) sendPing(toid enode.ID, toaddr *net.UDPAddr, callback func()) *replyMatcher {
  319. req := t.makePing(toaddr)
  320. packet, hash, err := t.encode(t.priv, req)
  321. if err != nil {
  322. errc := make(chan error, 1)
  323. errc <- err
  324. return &replyMatcher{errc: errc}
  325. }
  326. // Add a matcher for the reply to the pending reply queue. Pongs are matched if they
  327. // reference the ping we're about to send.
  328. rm := t.pending(toid, toaddr.IP, p_pongV4, func(p interface{}) (matched bool, requestDone bool) {
  329. matched = bytes.Equal(p.(*pongV4).ReplyTok, hash)
  330. if matched && callback != nil {
  331. callback()
  332. }
  333. return matched, matched
  334. })
  335. // Send the packet.
  336. t.localNode.UDPContact(toaddr)
  337. t.write(toaddr, toid, req.name(), packet)
  338. return rm
  339. }
  340. func (t *UDPv4) makePing(toaddr *net.UDPAddr) *pingV4 {
  341. seq, _ := rlp.EncodeToBytes(t.localNode.Node().Seq())
  342. return &pingV4{
  343. Version: 4,
  344. From: t.ourEndpoint(),
  345. To: makeEndpoint(toaddr, 0),
  346. Expiration: uint64(time.Now().Add(expiration).Unix()),
  347. Rest: []rlp.RawValue{seq},
  348. }
  349. }
  350. // LookupPubkey finds the closest nodes to the given public key.
  351. func (t *UDPv4) LookupPubkey(key *ecdsa.PublicKey) []*enode.Node {
  352. if t.tab.len() == 0 {
  353. // All nodes were dropped, refresh. The very first query will hit this
  354. // case and run the bootstrapping logic.
  355. <-t.tab.refresh()
  356. }
  357. return t.newLookup(t.closeCtx, encodePubkey(key)).run()
  358. }
  359. // RandomNodes is an iterator yielding nodes from a random walk of the DHT.
  360. func (t *UDPv4) RandomNodes() enode.Iterator {
  361. return newLookupIterator(t.closeCtx, t.newRandomLookup)
  362. }
  363. // lookupRandom implements transport.
  364. func (t *UDPv4) lookupRandom() []*enode.Node {
  365. return t.newRandomLookup(t.closeCtx).run()
  366. }
  367. // lookupSelf implements transport.
  368. func (t *UDPv4) lookupSelf() []*enode.Node {
  369. return t.newLookup(t.closeCtx, encodePubkey(&t.priv.PublicKey)).run()
  370. }
  371. func (t *UDPv4) newRandomLookup(ctx context.Context) *lookup {
  372. var target encPubkey
  373. crand.Read(target[:])
  374. return t.newLookup(ctx, target)
  375. }
  376. func (t *UDPv4) newLookup(ctx context.Context, targetKey encPubkey) *lookup {
  377. target := enode.ID(crypto.Keccak256Hash(targetKey[:]))
  378. it := newLookup(ctx, t.tab, target, func(n *node) ([]*node, error) {
  379. return t.findnode(n.ID(), n.addr(), targetKey)
  380. })
  381. return it
  382. }
  383. // findnode sends a findnode request to the given node and waits until
  384. // the node has sent up to k neighbors.
  385. func (t *UDPv4) findnode(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) ([]*node, error) {
  386. t.ensureBond(toid, toaddr)
  387. // Add a matcher for 'neighbours' replies to the pending reply queue. The matcher is
  388. // active until enough nodes have been received.
  389. nodes := make([]*node, 0, bucketSize)
  390. nreceived := 0
  391. rm := t.pending(toid, toaddr.IP, p_neighborsV4, func(r interface{}) (matched bool, requestDone bool) {
  392. reply := r.(*neighborsV4)
  393. for _, rn := range reply.Nodes {
  394. nreceived++
  395. n, err := t.nodeFromRPC(toaddr, rn)
  396. if err != nil {
  397. t.log.Trace("Invalid neighbor node received", "ip", rn.IP, "addr", toaddr, "err", err)
  398. continue
  399. }
  400. nodes = append(nodes, n)
  401. }
  402. return true, nreceived >= bucketSize
  403. })
  404. t.send(toaddr, toid, &findnodeV4{
  405. Target: target,
  406. Expiration: uint64(time.Now().Add(expiration).Unix()),
  407. })
  408. return nodes, <-rm.errc
  409. }
  410. // RequestENR sends enrRequest to the given node and waits for a response.
  411. func (t *UDPv4) RequestENR(n *enode.Node) (*enode.Node, error) {
  412. addr := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
  413. t.ensureBond(n.ID(), addr)
  414. req := &enrRequestV4{
  415. Expiration: uint64(time.Now().Add(expiration).Unix()),
  416. }
  417. packet, hash, err := t.encode(t.priv, req)
  418. if err != nil {
  419. return nil, err
  420. }
  421. // Add a matcher for the reply to the pending reply queue. Responses are matched if
  422. // they reference the request we're about to send.
  423. rm := t.pending(n.ID(), addr.IP, p_enrResponseV4, func(r interface{}) (matched bool, requestDone bool) {
  424. matched = bytes.Equal(r.(*enrResponseV4).ReplyTok, hash)
  425. return matched, matched
  426. })
  427. // Send the packet and wait for the reply.
  428. t.write(addr, n.ID(), req.name(), packet)
  429. if err := <-rm.errc; err != nil {
  430. return nil, err
  431. }
  432. // Verify the response record.
  433. respN, err := enode.New(enode.ValidSchemes, &rm.reply.(*enrResponseV4).Record)
  434. if err != nil {
  435. return nil, err
  436. }
  437. if respN.ID() != n.ID() {
  438. return nil, fmt.Errorf("invalid ID in response record")
  439. }
  440. if respN.Seq() < n.Seq() {
  441. return n, nil // response record is older
  442. }
  443. if err := netutil.CheckRelayIP(addr.IP, respN.IP()); err != nil {
  444. return nil, fmt.Errorf("invalid IP in response record: %v", err)
  445. }
  446. return respN, nil
  447. }
  448. // pending adds a reply matcher to the pending reply queue.
  449. // see the documentation of type replyMatcher for a detailed explanation.
  450. func (t *UDPv4) pending(id enode.ID, ip net.IP, ptype byte, callback replyMatchFunc) *replyMatcher {
  451. ch := make(chan error, 1)
  452. p := &replyMatcher{from: id, ip: ip, ptype: ptype, callback: callback, errc: ch}
  453. select {
  454. case t.addReplyMatcher <- p:
  455. // loop will handle it
  456. case <-t.closeCtx.Done():
  457. ch <- errClosed
  458. }
  459. return p
  460. }
  461. // handleReply dispatches a reply packet, invoking reply matchers. It returns
  462. // whether any matcher considered the packet acceptable.
  463. func (t *UDPv4) handleReply(from enode.ID, fromIP net.IP, req packetV4) bool {
  464. matched := make(chan bool, 1)
  465. select {
  466. case t.gotreply <- reply{from, fromIP, req, matched}:
  467. // loop will handle it
  468. return <-matched
  469. case <-t.closeCtx.Done():
  470. return false
  471. }
  472. }
  473. // loop runs in its own goroutine. it keeps track of
  474. // the refresh timer and the pending reply queue.
  475. func (t *UDPv4) loop() {
  476. defer t.wg.Done()
  477. var (
  478. plist = list.New()
  479. timeout = time.NewTimer(0)
  480. nextTimeout *replyMatcher // head of plist when timeout was last reset
  481. contTimeouts = 0 // number of continuous timeouts to do NTP checks
  482. ntpWarnTime = time.Unix(0, 0)
  483. )
  484. <-timeout.C // ignore first timeout
  485. defer timeout.Stop()
  486. resetTimeout := func() {
  487. if plist.Front() == nil || nextTimeout == plist.Front().Value {
  488. return
  489. }
  490. // Start the timer so it fires when the next pending reply has expired.
  491. now := time.Now()
  492. for el := plist.Front(); el != nil; el = el.Next() {
  493. nextTimeout = el.Value.(*replyMatcher)
  494. if dist := nextTimeout.deadline.Sub(now); dist < 2*respTimeout {
  495. timeout.Reset(dist)
  496. return
  497. }
  498. // Remove pending replies whose deadline is too far in the
  499. // future. These can occur if the system clock jumped
  500. // backwards after the deadline was assigned.
  501. nextTimeout.errc <- errClockWarp
  502. plist.Remove(el)
  503. }
  504. nextTimeout = nil
  505. timeout.Stop()
  506. }
  507. for {
  508. resetTimeout()
  509. select {
  510. case <-t.closeCtx.Done():
  511. for el := plist.Front(); el != nil; el = el.Next() {
  512. el.Value.(*replyMatcher).errc <- errClosed
  513. }
  514. return
  515. case p := <-t.addReplyMatcher:
  516. p.deadline = time.Now().Add(respTimeout)
  517. plist.PushBack(p)
  518. case r := <-t.gotreply:
  519. var matched bool // whether any replyMatcher considered the reply acceptable.
  520. for el := plist.Front(); el != nil; el = el.Next() {
  521. p := el.Value.(*replyMatcher)
  522. if p.from == r.from && p.ptype == r.data.kind() && p.ip.Equal(r.ip) {
  523. ok, requestDone := p.callback(r.data)
  524. matched = matched || ok
  525. // Remove the matcher if callback indicates that all replies have been received.
  526. if requestDone {
  527. p.reply = r.data
  528. p.errc <- nil
  529. plist.Remove(el)
  530. }
  531. // Reset the continuous timeout counter (time drift detection)
  532. contTimeouts = 0
  533. }
  534. }
  535. r.matched <- matched
  536. case now := <-timeout.C:
  537. nextTimeout = nil
  538. // Notify and remove callbacks whose deadline is in the past.
  539. for el := plist.Front(); el != nil; el = el.Next() {
  540. p := el.Value.(*replyMatcher)
  541. if now.After(p.deadline) || now.Equal(p.deadline) {
  542. p.errc <- errTimeout
  543. plist.Remove(el)
  544. contTimeouts++
  545. }
  546. }
  547. // If we've accumulated too many timeouts, do an NTP time sync check
  548. if contTimeouts > ntpFailureThreshold {
  549. if time.Since(ntpWarnTime) >= ntpWarningCooldown {
  550. ntpWarnTime = time.Now()
  551. go checkClockDrift()
  552. }
  553. contTimeouts = 0
  554. }
  555. }
  556. }
  557. }
  558. const (
  559. macSize = 256 / 8
  560. sigSize = 520 / 8
  561. headSize = macSize + sigSize // space of packet frame data
  562. )
  563. var (
  564. headSpace = make([]byte, headSize)
  565. // Neighbors replies are sent across multiple packets to
  566. // stay below the packet size limit. We compute the maximum number
  567. // of entries by stuffing a packet until it grows too large.
  568. maxNeighbors int
  569. )
  570. func init() {
  571. p := neighborsV4{Expiration: ^uint64(0)}
  572. maxSizeNode := rpcNode{IP: make(net.IP, 16), UDP: ^uint16(0), TCP: ^uint16(0)}
  573. for n := 0; ; n++ {
  574. p.Nodes = append(p.Nodes, maxSizeNode)
  575. size, _, err := rlp.EncodeToReader(p)
  576. if err != nil {
  577. // If this ever happens, it will be caught by the unit tests.
  578. panic("cannot encode: " + err.Error())
  579. }
  580. if headSize+size+1 >= maxPacketSize {
  581. maxNeighbors = n
  582. break
  583. }
  584. }
  585. }
  586. func (t *UDPv4) send(toaddr *net.UDPAddr, toid enode.ID, req packetV4) ([]byte, error) {
  587. packet, hash, err := t.encode(t.priv, req)
  588. if err != nil {
  589. return hash, err
  590. }
  591. return hash, t.write(toaddr, toid, req.name(), packet)
  592. }
  593. func (t *UDPv4) write(toaddr *net.UDPAddr, toid enode.ID, what string, packet []byte) error {
  594. _, err := t.conn.WriteToUDP(packet, toaddr)
  595. t.log.Trace(">> "+what, "id", toid, "addr", toaddr, "err", err)
  596. return err
  597. }
  598. func (t *UDPv4) encode(priv *ecdsa.PrivateKey, req packetV4) (packet, hash []byte, err error) {
  599. name := req.name()
  600. b := new(bytes.Buffer)
  601. b.Write(headSpace)
  602. b.WriteByte(req.kind())
  603. if err := rlp.Encode(b, req); err != nil {
  604. t.log.Error(fmt.Sprintf("Can't encode %s packet", name), "err", err)
  605. return nil, nil, err
  606. }
  607. packet = b.Bytes()
  608. sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv)
  609. if err != nil {
  610. t.log.Error(fmt.Sprintf("Can't sign %s packet", name), "err", err)
  611. return nil, nil, err
  612. }
  613. copy(packet[macSize:], sig)
  614. // add the hash to the front. Note: this doesn't protect the
  615. // packet in any way. Our public key will be part of this hash in
  616. // The future.
  617. hash = crypto.Keccak256(packet[macSize:])
  618. copy(packet, hash)
  619. return packet, hash, nil
  620. }
  621. // readLoop runs in its own goroutine. it handles incoming UDP packets.
  622. func (t *UDPv4) readLoop(unhandled chan<- ReadPacket) {
  623. defer t.wg.Done()
  624. if unhandled != nil {
  625. defer close(unhandled)
  626. }
  627. buf := make([]byte, maxPacketSize)
  628. for {
  629. nbytes, from, err := t.conn.ReadFromUDP(buf)
  630. if netutil.IsTemporaryError(err) {
  631. // Ignore temporary read errors.
  632. t.log.Debug("Temporary UDP read error", "err", err)
  633. continue
  634. } else if err != nil {
  635. // Shut down the loop for permament errors.
  636. if err != io.EOF {
  637. t.log.Debug("UDP read error", "err", err)
  638. }
  639. return
  640. }
  641. if t.handlePacket(from, buf[:nbytes]) != nil && unhandled != nil {
  642. select {
  643. case unhandled <- ReadPacket{buf[:nbytes], from}:
  644. default:
  645. }
  646. }
  647. }
  648. }
  649. func (t *UDPv4) handlePacket(from *net.UDPAddr, buf []byte) error {
  650. packet, fromKey, hash, err := decodeV4(buf)
  651. if err != nil {
  652. t.log.Debug("Bad discv4 packet", "addr", from, "err", err)
  653. return err
  654. }
  655. fromID := fromKey.id()
  656. if err == nil {
  657. err = packet.preverify(t, from, fromID, fromKey)
  658. }
  659. t.log.Trace("<< "+packet.name(), "id", fromID, "addr", from, "err", err)
  660. if err == nil {
  661. packet.handle(t, from, fromID, hash)
  662. }
  663. return err
  664. }
  665. func decodeV4(buf []byte) (packetV4, encPubkey, []byte, error) {
  666. if len(buf) < headSize+1 {
  667. return nil, encPubkey{}, nil, errPacketTooSmall
  668. }
  669. hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:]
  670. shouldhash := crypto.Keccak256(buf[macSize:])
  671. if !bytes.Equal(hash, shouldhash) {
  672. return nil, encPubkey{}, nil, errBadHash
  673. }
  674. fromKey, err := recoverNodeKey(crypto.Keccak256(buf[headSize:]), sig)
  675. if err != nil {
  676. return nil, fromKey, hash, err
  677. }
  678. var req packetV4
  679. switch ptype := sigdata[0]; ptype {
  680. case p_pingV4:
  681. req = new(pingV4)
  682. case p_pongV4:
  683. req = new(pongV4)
  684. case p_findnodeV4:
  685. req = new(findnodeV4)
  686. case p_neighborsV4:
  687. req = new(neighborsV4)
  688. case p_enrRequestV4:
  689. req = new(enrRequestV4)
  690. case p_enrResponseV4:
  691. req = new(enrResponseV4)
  692. default:
  693. return nil, fromKey, hash, fmt.Errorf("unknown type: %d", ptype)
  694. }
  695. s := rlp.NewStream(bytes.NewReader(sigdata[1:]), 0)
  696. err = s.Decode(req)
  697. return req, fromKey, hash, err
  698. }
  699. // checkBond checks if the given node has a recent enough endpoint proof.
  700. func (t *UDPv4) checkBond(id enode.ID, ip net.IP) bool {
  701. return time.Since(t.db.LastPongReceived(id, ip)) < bondExpiration
  702. }
  703. // ensureBond solicits a ping from a node if we haven't seen a ping from it for a while.
  704. // This ensures there is a valid endpoint proof on the remote end.
  705. func (t *UDPv4) ensureBond(toid enode.ID, toaddr *net.UDPAddr) {
  706. tooOld := time.Since(t.db.LastPingReceived(toid, toaddr.IP)) > bondExpiration
  707. if tooOld || t.db.FindFails(toid, toaddr.IP) > maxFindnodeFailures {
  708. rm := t.sendPing(toid, toaddr, nil)
  709. <-rm.errc
  710. // Wait for them to ping back and process our pong.
  711. time.Sleep(respTimeout)
  712. }
  713. }
  714. // expired checks whether the given UNIX time stamp is in the past.
  715. func expired(ts uint64) bool {
  716. return time.Unix(int64(ts), 0).Before(time.Now())
  717. }
  718. func seqFromTail(tail []rlp.RawValue) uint64 {
  719. if len(tail) == 0 {
  720. return 0
  721. }
  722. var seq uint64
  723. rlp.DecodeBytes(tail[0], &seq)
  724. return seq
  725. }
  726. // PING/v4
  727. func (req *pingV4) name() string { return "PING/v4" }
  728. func (req *pingV4) kind() byte { return p_pingV4 }
  729. func (req *pingV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  730. if expired(req.Expiration) {
  731. return errExpired
  732. }
  733. key, err := decodePubkey(fromKey)
  734. if err != nil {
  735. return errors.New("invalid public key")
  736. }
  737. req.senderKey = key
  738. return nil
  739. }
  740. func (req *pingV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  741. // Reply.
  742. seq, _ := rlp.EncodeToBytes(t.localNode.Node().Seq())
  743. t.send(from, fromID, &pongV4{
  744. To: makeEndpoint(from, req.From.TCP),
  745. ReplyTok: mac,
  746. Expiration: uint64(time.Now().Add(expiration).Unix()),
  747. Rest: []rlp.RawValue{seq},
  748. })
  749. // Ping back if our last pong on file is too far in the past.
  750. n := wrapNode(enode.NewV4(req.senderKey, from.IP, int(req.From.TCP), from.Port))
  751. if time.Since(t.db.LastPongReceived(n.ID(), from.IP)) > bondExpiration {
  752. t.sendPing(fromID, from, func() {
  753. t.tab.addVerifiedNode(n)
  754. })
  755. } else {
  756. t.tab.addVerifiedNode(n)
  757. }
  758. // Update node database and endpoint predictor.
  759. t.db.UpdateLastPingReceived(n.ID(), from.IP, time.Now())
  760. t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
  761. }
  762. // PONG/v4
  763. func (req *pongV4) name() string { return "PONG/v4" }
  764. func (req *pongV4) kind() byte { return p_pongV4 }
  765. func (req *pongV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  766. if expired(req.Expiration) {
  767. return errExpired
  768. }
  769. if !t.handleReply(fromID, from.IP, req) {
  770. return errUnsolicitedReply
  771. }
  772. return nil
  773. }
  774. func (req *pongV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  775. t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
  776. t.db.UpdateLastPongReceived(fromID, from.IP, time.Now())
  777. }
  778. // FINDNODE/v4
  779. func (req *findnodeV4) name() string { return "FINDNODE/v4" }
  780. func (req *findnodeV4) kind() byte { return p_findnodeV4 }
  781. func (req *findnodeV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  782. if expired(req.Expiration) {
  783. return errExpired
  784. }
  785. if !t.checkBond(fromID, from.IP) {
  786. // No endpoint proof pong exists, we don't process the packet. This prevents an
  787. // attack vector where the discovery protocol could be used to amplify traffic in a
  788. // DDOS attack. A malicious actor would send a findnode request with the IP address
  789. // and UDP port of the target as the source address. The recipient of the findnode
  790. // packet would then send a neighbors packet (which is a much bigger packet than
  791. // findnode) to the victim.
  792. return errUnknownNode
  793. }
  794. return nil
  795. }
  796. func (req *findnodeV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  797. // Determine closest nodes.
  798. target := enode.ID(crypto.Keccak256Hash(req.Target[:]))
  799. t.tab.mutex.Lock()
  800. closest := t.tab.closest(target, bucketSize, true).entries
  801. t.tab.mutex.Unlock()
  802. // Send neighbors in chunks with at most maxNeighbors per packet
  803. // to stay below the packet size limit.
  804. p := neighborsV4{Expiration: uint64(time.Now().Add(expiration).Unix())}
  805. var sent bool
  806. for _, n := range closest {
  807. if netutil.CheckRelayIP(from.IP, n.IP()) == nil {
  808. p.Nodes = append(p.Nodes, nodeToRPC(n))
  809. }
  810. if len(p.Nodes) == maxNeighbors {
  811. t.send(from, fromID, &p)
  812. p.Nodes = p.Nodes[:0]
  813. sent = true
  814. }
  815. }
  816. if len(p.Nodes) > 0 || !sent {
  817. t.send(from, fromID, &p)
  818. }
  819. }
  820. // NEIGHBORS/v4
  821. func (req *neighborsV4) name() string { return "NEIGHBORS/v4" }
  822. func (req *neighborsV4) kind() byte { return p_neighborsV4 }
  823. func (req *neighborsV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  824. if expired(req.Expiration) {
  825. return errExpired
  826. }
  827. if !t.handleReply(fromID, from.IP, req) {
  828. return errUnsolicitedReply
  829. }
  830. return nil
  831. }
  832. func (req *neighborsV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  833. }
  834. // ENRREQUEST/v4
  835. func (req *enrRequestV4) name() string { return "ENRREQUEST/v4" }
  836. func (req *enrRequestV4) kind() byte { return p_enrRequestV4 }
  837. func (req *enrRequestV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  838. if expired(req.Expiration) {
  839. return errExpired
  840. }
  841. if !t.checkBond(fromID, from.IP) {
  842. return errUnknownNode
  843. }
  844. return nil
  845. }
  846. func (req *enrRequestV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  847. t.send(from, fromID, &enrResponseV4{
  848. ReplyTok: mac,
  849. Record: *t.localNode.Node().Record(),
  850. })
  851. }
  852. // ENRRESPONSE/v4
  853. func (req *enrResponseV4) name() string { return "ENRRESPONSE/v4" }
  854. func (req *enrResponseV4) kind() byte { return p_enrResponseV4 }
  855. func (req *enrResponseV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  856. if !t.handleReply(fromID, from.IP, req) {
  857. return errUnsolicitedReply
  858. }
  859. return nil
  860. }
  861. func (req *enrResponseV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  862. }