github.com/beyonderyue/gochain@v2.2.26+incompatible/p2p/discover/udp.go (about) 1 // Copyright 2015 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 17 package discover 18 19 import ( 20 "bytes" 21 "container/list" 22 "crypto/ecdsa" 23 "errors" 24 "fmt" 25 "net" 26 "time" 27 28 "github.com/gochain-io/gochain/crypto" 29 "github.com/gochain-io/gochain/log" 30 "github.com/gochain-io/gochain/p2p/nat" 31 "github.com/gochain-io/gochain/p2p/netutil" 32 "github.com/gochain-io/gochain/rlp" 33 ) 34 35 const Version = 4 36 37 // Errors 38 var ( 39 errPacketTooSmall = errors.New("too small") 40 errBadHash = errors.New("bad hash") 41 errExpired = errors.New("expired") 42 errUnsolicitedReply = errors.New("unsolicited reply") 43 errUnknownNode = errors.New("unknown node") 44 errTimeout = errors.New("RPC timeout") 45 errClockWarp = errors.New("reply deadline too far in the future") 46 errClosed = errors.New("socket closed") 47 ) 48 49 // Timeouts 50 const ( 51 respTimeout = 500 * time.Millisecond 52 sendTimeout = 500 * time.Millisecond 53 expiration = 20 * time.Second 54 55 ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP 56 ntpWarningCooldown = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning 57 driftThreshold = 10 * time.Second // Allowed clock drift before warning user 58 ) 59 60 // RPC packet types 61 const ( 62 pingPacket = iota + 1 // zero is 'reserved' 63 pongPacket 64 findnodePacket 65 neighborsPacket 66 ) 67 68 // RPC request structures 69 type ( 70 ping struct { 71 Version uint 72 From, To rpcEndpoint 73 Expiration uint64 74 // Ignore additional fields (for forward compatibility). 75 Rest []rlp.RawValue `rlp:"tail"` 76 } 77 78 // pong is the reply to ping. 79 pong struct { 80 // This field should mirror the UDP envelope address 81 // of the ping packet, which provides a way to discover the 82 // the external address (after NAT). 83 To rpcEndpoint 84 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 91 // findnode is a query for nodes close to the given target. 92 findnode struct { 93 Target NodeID // doesn't need to be an actual public key 94 Expiration uint64 95 // Ignore additional fields (for forward compatibility). 96 Rest []rlp.RawValue `rlp:"tail"` 97 } 98 99 // reply to findnode 100 neighbors struct { 101 Nodes []rpcNode 102 Expiration uint64 103 // Ignore additional fields (for forward compatibility). 104 Rest []rlp.RawValue `rlp:"tail"` 105 } 106 107 rpcNode struct { 108 IP net.IP // len 4 for IPv4 or 16 for IPv6 109 UDP uint16 // for discovery protocol 110 TCP uint16 // for RLPx protocol 111 ID NodeID 112 } 113 114 rpcEndpoint struct { 115 IP net.IP // len 4 for IPv4 or 16 for IPv6 116 UDP uint16 // for discovery protocol 117 TCP uint16 // for RLPx protocol 118 } 119 ) 120 121 func makeEndpoint(addr *net.UDPAddr, tcpPort uint16) rpcEndpoint { 122 ip := addr.IP.To4() 123 if ip == nil { 124 ip = addr.IP.To16() 125 } 126 return rpcEndpoint{IP: ip, UDP: uint16(addr.Port), TCP: tcpPort} 127 } 128 129 func (t *udp) nodeFromRPC(sender *net.UDPAddr, rn rpcNode) (*Node, error) { 130 if rn.UDP <= 1024 { 131 return nil, errors.New("low port") 132 } 133 if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil { 134 return nil, err 135 } 136 if t.netrestrict != nil && !t.netrestrict.Contains(rn.IP) { 137 return nil, errors.New("not contained in netrestrict whitelist") 138 } 139 n := NewNode(rn.ID, rn.IP, rn.UDP, rn.TCP) 140 err := n.validateComplete() 141 return n, err 142 } 143 144 func nodeToRPC(n *Node) rpcNode { 145 return rpcNode{ID: n.ID, IP: n.IP, UDP: n.UDP, TCP: n.TCP} 146 } 147 148 type packet interface { 149 handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error 150 name() string 151 } 152 153 type conn interface { 154 ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) 155 WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error) 156 Close() error 157 LocalAddr() net.Addr 158 } 159 160 // udp implements the RPC protocol. 161 type udp struct { 162 conn conn 163 netrestrict *netutil.Netlist 164 priv *ecdsa.PrivateKey 165 ourEndpoint rpcEndpoint 166 167 addpending chan *pending 168 gotreply chan reply 169 170 closing chan struct{} 171 nat nat.Interface 172 173 *Table 174 } 175 176 // pending represents a pending reply. 177 // 178 // some implementations of the protocol wish to send more than one 179 // reply packet to findnode. in general, any neighbors packet cannot 180 // be matched up with a specific findnode packet. 181 // 182 // our implementation handles this by storing a callback function for 183 // each pending reply. incoming packets from a node are dispatched 184 // to all the callback functions for that node. 185 type pending struct { 186 // these fields must match in the reply. 187 from NodeID 188 ptype byte 189 190 // time when the request must complete 191 deadline time.Time 192 193 // callback is called when a matching reply arrives. if it returns 194 // true, the callback is removed from the pending reply queue. 195 // if it returns false, the reply is considered incomplete and 196 // the callback will be invoked again for the next matching reply. 197 callback func(resp interface{}) (done bool) 198 199 // errc receives nil when the callback indicates completion or an 200 // error if no further reply is received within the timeout. 201 errc chan<- error 202 } 203 204 type reply struct { 205 from NodeID 206 ptype byte 207 data interface{} 208 // loop indicates whether there was 209 // a matching request by sending on this channel. 210 matched chan<- bool 211 } 212 213 // ReadPacket is sent to the unhandled channel when it could not be processed 214 type ReadPacket struct { 215 Data []byte 216 Addr *net.UDPAddr 217 } 218 219 // Config holds Table-related settings. 220 type Config struct { 221 // These settings are required and configure the UDP listener: 222 PrivateKey *ecdsa.PrivateKey 223 224 // These settings are optional: 225 AnnounceAddr *net.UDPAddr // local address announced in the DHT 226 NodeDBPath string // if set, the node database is stored at this filesystem location 227 NetRestrict *netutil.Netlist // network whitelist 228 Bootnodes []*Node // list of bootstrap nodes 229 Unhandled chan<- ReadPacket // unhandled packets are sent on this channel 230 } 231 232 // ListenUDP returns a new table that listens for UDP packets on laddr. 233 func ListenUDP(c conn, cfg Config) (*Table, error) { 234 tab, _, err := newUDP(c, cfg) 235 if err != nil { 236 return nil, err 237 } 238 log.Info("UDP listener up", "self", tab.self) 239 return tab, nil 240 } 241 242 func newUDP(c conn, cfg Config) (*Table, *udp, error) { 243 udp := &udp{ 244 conn: c, 245 priv: cfg.PrivateKey, 246 netrestrict: cfg.NetRestrict, 247 closing: make(chan struct{}), 248 gotreply: make(chan reply), 249 addpending: make(chan *pending), 250 } 251 realaddr := c.LocalAddr().(*net.UDPAddr) 252 if cfg.AnnounceAddr != nil { 253 realaddr = cfg.AnnounceAddr 254 } 255 // TODO: separate TCP port 256 udp.ourEndpoint = makeEndpoint(realaddr, uint16(realaddr.Port)) 257 tab, err := newTable(udp, PubkeyID(&cfg.PrivateKey.PublicKey), realaddr, cfg.NodeDBPath, cfg.Bootnodes) 258 if err != nil { 259 return nil, nil, err 260 } 261 udp.Table = tab 262 263 go udp.loop() 264 go udp.readLoop(cfg.Unhandled) 265 return udp.Table, udp, nil 266 } 267 268 func (t *udp) close() { 269 close(t.closing) 270 t.conn.Close() 271 // TODO: wait for the loops to end. 272 } 273 274 // ping sends a ping message to the given node and waits for a reply. 275 func (t *udp) ping(toid NodeID, toaddr *net.UDPAddr) error { 276 req := &ping{ 277 Version: Version, 278 From: t.ourEndpoint, 279 To: makeEndpoint(toaddr, 0), // TODO: maybe use known TCP port from DB 280 Expiration: uint64(time.Now().Add(expiration).Unix()), 281 } 282 packet, hash, err := encodePacket(t.priv, pingPacket, req) 283 if err != nil { 284 return err 285 } 286 errc := t.pending(toid, pongPacket, func(p interface{}) bool { 287 return bytes.Equal(p.(*pong).ReplyTok, hash) 288 }) 289 t.write(toaddr, req.name(), packet) 290 return <-errc 291 } 292 293 func (t *udp) waitping(from NodeID) error { 294 return <-t.pending(from, pingPacket, func(interface{}) bool { return true }) 295 } 296 297 // findnode sends a findnode request to the given node and waits until 298 // the node has sent up to k neighbors. 299 func (t *udp) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node, error) { 300 nodes := make([]*Node, 0, bucketSize) 301 nreceived := 0 302 errc := t.pending(toid, neighborsPacket, func(r interface{}) bool { 303 tracing := log.Tracing() 304 reply := r.(*neighbors) 305 for _, rn := range reply.Nodes { 306 nreceived++ 307 n, err := t.nodeFromRPC(toaddr, rn) 308 if err != nil { 309 if tracing { 310 log.Trace("Invalid neighbor node received", "ip", rn.IP, "addr", toaddr, "err", err) 311 } 312 continue 313 } 314 nodes = append(nodes, n) 315 } 316 return nreceived >= bucketSize 317 }) 318 t.send(toaddr, findnodePacket, &findnode{ 319 Target: target, 320 Expiration: uint64(time.Now().Add(expiration).Unix()), 321 }) 322 err := <-errc 323 return nodes, err 324 } 325 326 // pending adds a reply callback to the pending reply queue. 327 // see the documentation of type pending for a detailed explanation. 328 func (t *udp) pending(id NodeID, ptype byte, callback func(interface{}) bool) <-chan error { 329 ch := make(chan error, 1) 330 p := &pending{from: id, ptype: ptype, callback: callback, errc: ch} 331 select { 332 case t.addpending <- p: 333 // loop will handle it 334 case <-t.closing: 335 ch <- errClosed 336 } 337 return ch 338 } 339 340 func (t *udp) handleReply(from NodeID, ptype byte, req packet) bool { 341 matched := make(chan bool, 1) 342 select { 343 case t.gotreply <- reply{from, ptype, req, matched}: 344 // loop will handle it 345 return <-matched 346 case <-t.closing: 347 return false 348 } 349 } 350 351 // loop runs in its own goroutine. it keeps track of 352 // the refresh timer and the pending reply queue. 353 func (t *udp) loop() { 354 var ( 355 plist = list.New() 356 timeout = time.NewTimer(0) 357 nextTimeout *pending // head of plist when timeout was last reset 358 contTimeouts = 0 // number of continuous timeouts to do NTP checks 359 ntpWarnTime = time.Unix(0, 0) 360 ) 361 <-timeout.C // ignore first timeout 362 defer timeout.Stop() 363 364 resetTimeout := func() { 365 if plist.Front() == nil || nextTimeout == plist.Front().Value { 366 return 367 } 368 // Start the timer so it fires when the next pending reply has expired. 369 now := time.Now() 370 for el := plist.Front(); el != nil; el = el.Next() { 371 nextTimeout = el.Value.(*pending) 372 if dist := nextTimeout.deadline.Sub(now); dist < 2*respTimeout { 373 timeout.Reset(dist) 374 return 375 } 376 // Remove pending replies whose deadline is too far in the 377 // future. These can occur if the system clock jumped 378 // backwards after the deadline was assigned. 379 nextTimeout.errc <- errClockWarp 380 plist.Remove(el) 381 } 382 nextTimeout = nil 383 timeout.Stop() 384 } 385 386 for { 387 resetTimeout() 388 389 select { 390 case <-t.closing: 391 for el := plist.Front(); el != nil; el = el.Next() { 392 el.Value.(*pending).errc <- errClosed 393 } 394 return 395 396 case p := <-t.addpending: 397 p.deadline = time.Now().Add(respTimeout) 398 plist.PushBack(p) 399 400 case r := <-t.gotreply: 401 var matched bool 402 for el := plist.Front(); el != nil; el = el.Next() { 403 p := el.Value.(*pending) 404 if p.from == r.from && p.ptype == r.ptype { 405 matched = true 406 // Remove the matcher if its callback indicates 407 // that all replies have been received. This is 408 // required for packet types that expect multiple 409 // reply packets. 410 if p.callback(r.data) { 411 p.errc <- nil 412 plist.Remove(el) 413 } 414 // Reset the continuous timeout counter (time drift detection) 415 contTimeouts = 0 416 } 417 } 418 r.matched <- matched 419 420 case now := <-timeout.C: 421 nextTimeout = nil 422 423 // Notify and remove callbacks whose deadline is in the past. 424 for el := plist.Front(); el != nil; el = el.Next() { 425 p := el.Value.(*pending) 426 if now.After(p.deadline) || now.Equal(p.deadline) { 427 p.errc <- errTimeout 428 plist.Remove(el) 429 contTimeouts++ 430 } 431 } 432 // If we've accumulated too many timeouts, do an NTP time sync check 433 if contTimeouts > ntpFailureThreshold { 434 if time.Since(ntpWarnTime) >= ntpWarningCooldown { 435 ntpWarnTime = time.Now() 436 go checkClockDrift() 437 } 438 contTimeouts = 0 439 } 440 } 441 } 442 } 443 444 const ( 445 macSize = 256 / 8 446 sigSize = 520 / 8 447 headSize = macSize + sigSize // space of packet frame data 448 ) 449 450 var ( 451 headSpace = make([]byte, headSize) 452 453 // Neighbors replies are sent across multiple packets to 454 // stay below the 1280 byte limit. We compute the maximum number 455 // of entries by stuffing a packet until it grows too large. 456 maxNeighbors int 457 ) 458 459 func init() { 460 p := neighbors{Expiration: ^uint64(0)} 461 maxSizeNode := rpcNode{IP: make(net.IP, 16), UDP: ^uint16(0), TCP: ^uint16(0)} 462 for n := 0; ; n++ { 463 p.Nodes = append(p.Nodes, maxSizeNode) 464 size, _, err := rlp.EncodeToReader(p) 465 if err != nil { 466 // If this ever happens, it will be caught by the unit tests. 467 panic("cannot encode: " + err.Error()) 468 } 469 if headSize+size+1 >= 1280 { 470 maxNeighbors = n 471 break 472 } 473 } 474 } 475 476 func (t *udp) send(toaddr *net.UDPAddr, ptype byte, req packet) ([]byte, error) { 477 packet, hash, err := encodePacket(t.priv, ptype, req) 478 if err != nil { 479 return hash, err 480 } 481 return hash, t.write(toaddr, req.name(), packet) 482 } 483 484 func (t *udp) write(toaddr *net.UDPAddr, what string, packet []byte) error { 485 _, err := t.conn.WriteToUDP(packet, toaddr) 486 if log.Tracing() { 487 log.Trace(">> "+what, "addr", toaddr, "err", err) 488 } 489 return err 490 } 491 492 func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) (packet, hash []byte, err error) { 493 b := new(bytes.Buffer) 494 b.Write(headSpace) 495 b.WriteByte(ptype) 496 if err := rlp.Encode(b, req); err != nil { 497 log.Error("Can't encode discv4 packet", "err", err) 498 return nil, nil, err 499 } 500 packet = b.Bytes() 501 sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv) 502 if err != nil { 503 log.Error("Can't sign discv4 packet", "err", err) 504 return nil, nil, err 505 } 506 copy(packet[macSize:], sig) 507 // add the hash to the front. Note: this doesn't protect the 508 // packet in any way. Our public key will be part of this hash in 509 // The future. 510 hash = crypto.Keccak256(packet[macSize:]) 511 copy(packet, hash) 512 return packet, hash, nil 513 } 514 515 // readLoop runs in its own goroutine. it handles incoming UDP packets. 516 func (t *udp) readLoop(unhandled chan<- ReadPacket) { 517 defer t.conn.Close() 518 if unhandled != nil { 519 defer close(unhandled) 520 } 521 // Discovery packets are defined to be no larger than 1280 bytes. 522 // Packets larger than this size will be cut at the end and treated 523 // as invalid because their hash won't match. 524 buf := make([]byte, 1280) 525 for { 526 nbytes, from, err := t.conn.ReadFromUDP(buf) 527 if netutil.IsTemporaryError(err) { 528 // Ignore temporary read errors. 529 log.Debug("Temporary UDP read error", "err", err) 530 continue 531 } else if err != nil { 532 // Shut down the loop for permament errors. 533 log.Debug("UDP read error", "err", err) 534 return 535 } 536 if t.handlePacket(from, buf[:nbytes]) != nil && unhandled != nil { 537 select { 538 case unhandled <- ReadPacket{buf[:nbytes], from}: 539 default: 540 } 541 } 542 } 543 } 544 545 func (t *udp) handlePacket(from *net.UDPAddr, buf []byte) error { 546 packet, fromID, hash, err := decodePacket(buf) 547 if err != nil { 548 log.Debug("Bad discv4 packet", "addr", from, "err", err) 549 return err 550 } 551 err = packet.handle(t, from, fromID, hash) 552 if log.Tracing() { 553 log.Trace("<< "+packet.name(), "addr", from, "err", err) 554 } 555 return err 556 } 557 558 func decodePacket(buf []byte) (packet, NodeID, []byte, error) { 559 if len(buf) < headSize+1 { 560 return nil, NodeID{}, nil, errPacketTooSmall 561 } 562 hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:] 563 shouldhash := crypto.Keccak256Hash(buf[macSize:]) 564 if !bytes.Equal(hash, shouldhash[:]) { 565 return nil, NodeID{}, nil, errBadHash 566 } 567 fromID, err := recoverNodeID(crypto.Keccak256(buf[headSize:]), sig) 568 if err != nil { 569 return nil, NodeID{}, hash, err 570 } 571 var req packet 572 switch ptype := sigdata[0]; ptype { 573 case pingPacket: 574 req = new(ping) 575 case pongPacket: 576 req = new(pong) 577 case findnodePacket: 578 req = new(findnode) 579 case neighborsPacket: 580 req = new(neighbors) 581 default: 582 return nil, fromID, hash, fmt.Errorf("unknown type: %d", ptype) 583 } 584 return req, fromID, hash, rlp.Decode(bytes.NewReader(sigdata[1:]), req) 585 } 586 587 func (req *ping) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 588 if expired(req.Expiration) { 589 return errExpired 590 } 591 t.send(from, pongPacket, &pong{ 592 To: makeEndpoint(from, req.From.TCP), 593 ReplyTok: mac, 594 Expiration: uint64(time.Now().Add(expiration).Unix()), 595 }) 596 if !t.handleReply(fromID, pingPacket, req) { 597 // Note: we're ignoring the provided IP address right now 598 go t.bond(true, fromID, from, req.From.TCP) 599 } 600 return nil 601 } 602 603 func (req *ping) name() string { return "PING/v4" } 604 605 func (req *pong) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 606 if expired(req.Expiration) { 607 return errExpired 608 } 609 if !t.handleReply(fromID, pongPacket, req) { 610 return errUnsolicitedReply 611 } 612 return nil 613 } 614 615 func (req *pong) name() string { return "PONG/v4" } 616 617 func (req *findnode) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 618 if expired(req.Expiration) { 619 return errExpired 620 } 621 if !t.db.hasBond(fromID) { 622 // No bond exists, we don't process the packet. This prevents 623 // an attack vector where the discovery protocol could be used 624 // to amplify traffic in a DDOS attack. A malicious actor 625 // would send a findnode request with the IP address and UDP 626 // port of the target as the source address. The recipient of 627 // the findnode packet would then send a neighbors packet 628 // (which is a much bigger packet than findnode) to the victim. 629 return errUnknownNode 630 } 631 target := crypto.Keccak256Hash(req.Target[:]) 632 t.mutex.Lock() 633 closest := t.closest(target, bucketSize).entries 634 t.mutex.Unlock() 635 636 p := neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())} 637 var sent bool 638 // Send neighbors in chunks with at most maxNeighbors per packet 639 // to stay below the 1280 byte limit. 640 for _, n := range closest { 641 if netutil.CheckRelayIP(from.IP, n.IP) == nil { 642 p.Nodes = append(p.Nodes, nodeToRPC(n)) 643 } 644 if len(p.Nodes) == maxNeighbors { 645 t.send(from, neighborsPacket, &p) 646 p.Nodes = p.Nodes[:0] 647 sent = true 648 } 649 } 650 if len(p.Nodes) > 0 || !sent { 651 t.send(from, neighborsPacket, &p) 652 } 653 return nil 654 } 655 656 func (req *findnode) name() string { return "FINDNODE/v4" } 657 658 func (req *neighbors) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 659 if expired(req.Expiration) { 660 return errExpired 661 } 662 if !t.handleReply(fromID, neighborsPacket, req) { 663 return errUnsolicitedReply 664 } 665 return nil 666 } 667 668 func (req *neighbors) name() string { return "NEIGHBORS/v4" } 669 670 func expired(ts uint64) bool { 671 return time.Unix(int64(ts), 0).Before(time.Now()) 672 }