github.com/needkane/go-ethereum@v1.7.4-0.20180131070256-c212876ea2b7/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/ethereum/go-ethereum/crypto" 29 "github.com/ethereum/go-ethereum/log" 30 "github.com/ethereum/go-ethereum/p2p/nat" 31 "github.com/ethereum/go-ethereum/p2p/netutil" 32 "github.com/ethereum/go-ethereum/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 // ListenUDP returns a new table that listens for UDP packets on laddr. 220 func ListenUDP(priv *ecdsa.PrivateKey, conn conn, realaddr *net.UDPAddr, unhandled chan ReadPacket, nodeDBPath string, netrestrict *netutil.Netlist) (*Table, error) { 221 tab, _, err := newUDP(priv, conn, realaddr, unhandled, nodeDBPath, netrestrict) 222 if err != nil { 223 return nil, err 224 } 225 log.Info("UDP listener up", "self", tab.self) 226 return tab, nil 227 } 228 229 func newUDP(priv *ecdsa.PrivateKey, c conn, realaddr *net.UDPAddr, unhandled chan ReadPacket, nodeDBPath string, netrestrict *netutil.Netlist) (*Table, *udp, error) { 230 udp := &udp{ 231 conn: c, 232 priv: priv, 233 netrestrict: netrestrict, 234 closing: make(chan struct{}), 235 gotreply: make(chan reply), 236 addpending: make(chan *pending), 237 } 238 // TODO: separate TCP port 239 udp.ourEndpoint = makeEndpoint(realaddr, uint16(realaddr.Port)) 240 tab, err := newTable(udp, PubkeyID(&priv.PublicKey), realaddr, nodeDBPath) 241 if err != nil { 242 return nil, nil, err 243 } 244 udp.Table = tab 245 246 go udp.loop() 247 go udp.readLoop(unhandled) 248 return udp.Table, udp, nil 249 } 250 251 func (t *udp) close() { 252 close(t.closing) 253 t.conn.Close() 254 // TODO: wait for the loops to end. 255 } 256 257 // ping sends a ping message to the given node and waits for a reply. 258 func (t *udp) ping(toid NodeID, toaddr *net.UDPAddr) error { 259 // TODO: maybe check for ReplyTo field in callback to measure RTT 260 errc := t.pending(toid, pongPacket, func(interface{}) bool { return true }) 261 t.send(toaddr, pingPacket, &ping{ 262 Version: Version, 263 From: t.ourEndpoint, 264 To: makeEndpoint(toaddr, 0), // TODO: maybe use known TCP port from DB 265 Expiration: uint64(time.Now().Add(expiration).Unix()), 266 }) 267 return <-errc 268 } 269 270 func (t *udp) waitping(from NodeID) error { 271 return <-t.pending(from, pingPacket, func(interface{}) bool { return true }) 272 } 273 274 // findnode sends a findnode request to the given node and waits until 275 // the node has sent up to k neighbors. 276 func (t *udp) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node, error) { 277 nodes := make([]*Node, 0, bucketSize) 278 nreceived := 0 279 errc := t.pending(toid, neighborsPacket, func(r interface{}) bool { 280 reply := r.(*neighbors) 281 for _, rn := range reply.Nodes { 282 nreceived++ 283 n, err := t.nodeFromRPC(toaddr, rn) 284 if err != nil { 285 log.Trace("Invalid neighbor node received", "ip", rn.IP, "addr", toaddr, "err", err) 286 continue 287 } 288 nodes = append(nodes, n) 289 } 290 return nreceived >= bucketSize 291 }) 292 t.send(toaddr, findnodePacket, &findnode{ 293 Target: target, 294 Expiration: uint64(time.Now().Add(expiration).Unix()), 295 }) 296 err := <-errc 297 return nodes, err 298 } 299 300 // pending adds a reply callback to the pending reply queue. 301 // see the documentation of type pending for a detailed explanation. 302 func (t *udp) pending(id NodeID, ptype byte, callback func(interface{}) bool) <-chan error { 303 ch := make(chan error, 1) 304 p := &pending{from: id, ptype: ptype, callback: callback, errc: ch} 305 select { 306 case t.addpending <- p: 307 // loop will handle it 308 case <-t.closing: 309 ch <- errClosed 310 } 311 return ch 312 } 313 314 func (t *udp) handleReply(from NodeID, ptype byte, req packet) bool { 315 matched := make(chan bool, 1) 316 select { 317 case t.gotreply <- reply{from, ptype, req, matched}: 318 // loop will handle it 319 return <-matched 320 case <-t.closing: 321 return false 322 } 323 } 324 325 // loop runs in its own goroutine. it keeps track of 326 // the refresh timer and the pending reply queue. 327 func (t *udp) loop() { 328 var ( 329 plist = list.New() 330 timeout = time.NewTimer(0) 331 nextTimeout *pending // head of plist when timeout was last reset 332 contTimeouts = 0 // number of continuous timeouts to do NTP checks 333 ntpWarnTime = time.Unix(0, 0) 334 ) 335 <-timeout.C // ignore first timeout 336 defer timeout.Stop() 337 338 resetTimeout := func() { 339 if plist.Front() == nil || nextTimeout == plist.Front().Value { 340 return 341 } 342 // Start the timer so it fires when the next pending reply has expired. 343 now := time.Now() 344 for el := plist.Front(); el != nil; el = el.Next() { 345 nextTimeout = el.Value.(*pending) 346 if dist := nextTimeout.deadline.Sub(now); dist < 2*respTimeout { 347 timeout.Reset(dist) 348 return 349 } 350 // Remove pending replies whose deadline is too far in the 351 // future. These can occur if the system clock jumped 352 // backwards after the deadline was assigned. 353 nextTimeout.errc <- errClockWarp 354 plist.Remove(el) 355 } 356 nextTimeout = nil 357 timeout.Stop() 358 } 359 360 for { 361 resetTimeout() 362 363 select { 364 case <-t.closing: 365 for el := plist.Front(); el != nil; el = el.Next() { 366 el.Value.(*pending).errc <- errClosed 367 } 368 return 369 370 case p := <-t.addpending: 371 p.deadline = time.Now().Add(respTimeout) 372 plist.PushBack(p) 373 374 case r := <-t.gotreply: 375 var matched bool 376 for el := plist.Front(); el != nil; el = el.Next() { 377 p := el.Value.(*pending) 378 if p.from == r.from && p.ptype == r.ptype { 379 matched = true 380 // Remove the matcher if its callback indicates 381 // that all replies have been received. This is 382 // required for packet types that expect multiple 383 // reply packets. 384 if p.callback(r.data) { 385 p.errc <- nil 386 plist.Remove(el) 387 } 388 // Reset the continuous timeout counter (time drift detection) 389 contTimeouts = 0 390 } 391 } 392 r.matched <- matched 393 394 case now := <-timeout.C: 395 nextTimeout = nil 396 397 // Notify and remove callbacks whose deadline is in the past. 398 for el := plist.Front(); el != nil; el = el.Next() { 399 p := el.Value.(*pending) 400 if now.After(p.deadline) || now.Equal(p.deadline) { 401 p.errc <- errTimeout 402 plist.Remove(el) 403 contTimeouts++ 404 } 405 } 406 // If we've accumulated too many timeouts, do an NTP time sync check 407 if contTimeouts > ntpFailureThreshold { 408 if time.Since(ntpWarnTime) >= ntpWarningCooldown { 409 ntpWarnTime = time.Now() 410 go checkClockDrift() 411 } 412 contTimeouts = 0 413 } 414 } 415 } 416 } 417 418 const ( 419 macSize = 256 / 8 420 sigSize = 520 / 8 421 headSize = macSize + sigSize // space of packet frame data 422 ) 423 424 var ( 425 headSpace = make([]byte, headSize) 426 427 // Neighbors replies are sent across multiple packets to 428 // stay below the 1280 byte limit. We compute the maximum number 429 // of entries by stuffing a packet until it grows too large. 430 maxNeighbors int 431 ) 432 433 func init() { 434 p := neighbors{Expiration: ^uint64(0)} 435 maxSizeNode := rpcNode{IP: make(net.IP, 16), UDP: ^uint16(0), TCP: ^uint16(0)} 436 for n := 0; ; n++ { 437 p.Nodes = append(p.Nodes, maxSizeNode) 438 size, _, err := rlp.EncodeToReader(p) 439 if err != nil { 440 // If this ever happens, it will be caught by the unit tests. 441 panic("cannot encode: " + err.Error()) 442 } 443 if headSize+size+1 >= 1280 { 444 maxNeighbors = n 445 break 446 } 447 } 448 } 449 450 func (t *udp) send(toaddr *net.UDPAddr, ptype byte, req packet) error { 451 packet, err := encodePacket(t.priv, ptype, req) 452 if err != nil { 453 return err 454 } 455 _, err = t.conn.WriteToUDP(packet, toaddr) 456 log.Trace(">> "+req.name(), "addr", toaddr, "err", err) 457 return err 458 } 459 460 func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) ([]byte, error) { 461 b := new(bytes.Buffer) 462 b.Write(headSpace) 463 b.WriteByte(ptype) 464 if err := rlp.Encode(b, req); err != nil { 465 log.Error("Can't encode discv4 packet", "err", err) 466 return nil, err 467 } 468 packet := b.Bytes() 469 sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv) 470 if err != nil { 471 log.Error("Can't sign discv4 packet", "err", err) 472 return nil, err 473 } 474 copy(packet[macSize:], sig) 475 // add the hash to the front. Note: this doesn't protect the 476 // packet in any way. Our public key will be part of this hash in 477 // The future. 478 copy(packet, crypto.Keccak256(packet[macSize:])) 479 return packet, nil 480 } 481 482 // readLoop runs in its own goroutine. it handles incoming UDP packets. 483 func (t *udp) readLoop(unhandled chan ReadPacket) { 484 defer t.conn.Close() 485 if unhandled != nil { 486 defer close(unhandled) 487 } 488 // Discovery packets are defined to be no larger than 1280 bytes. 489 // Packets larger than this size will be cut at the end and treated 490 // as invalid because their hash won't match. 491 buf := make([]byte, 1280) 492 for { 493 nbytes, from, err := t.conn.ReadFromUDP(buf) 494 if netutil.IsTemporaryError(err) { 495 // Ignore temporary read errors. 496 log.Debug("Temporary UDP read error", "err", err) 497 continue 498 } else if err != nil { 499 // Shut down the loop for permament errors. 500 log.Debug("UDP read error", "err", err) 501 return 502 } 503 if t.handlePacket(from, buf[:nbytes]) != nil && unhandled != nil { 504 select { 505 case unhandled <- ReadPacket{buf[:nbytes], from}: 506 default: 507 } 508 } 509 } 510 } 511 512 func (t *udp) handlePacket(from *net.UDPAddr, buf []byte) error { 513 packet, fromID, hash, err := decodePacket(buf) 514 if err != nil { 515 log.Debug("Bad discv4 packet", "addr", from, "err", err) 516 return err 517 } 518 err = packet.handle(t, from, fromID, hash) 519 log.Trace("<< "+packet.name(), "addr", from, "err", err) 520 return err 521 } 522 523 func decodePacket(buf []byte) (packet, NodeID, []byte, error) { 524 if len(buf) < headSize+1 { 525 return nil, NodeID{}, nil, errPacketTooSmall 526 } 527 hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:] 528 shouldhash := crypto.Keccak256(buf[macSize:]) 529 if !bytes.Equal(hash, shouldhash) { 530 return nil, NodeID{}, nil, errBadHash 531 } 532 fromID, err := recoverNodeID(crypto.Keccak256(buf[headSize:]), sig) 533 if err != nil { 534 return nil, NodeID{}, hash, err 535 } 536 var req packet 537 switch ptype := sigdata[0]; ptype { 538 case pingPacket: 539 req = new(ping) 540 case pongPacket: 541 req = new(pong) 542 case findnodePacket: 543 req = new(findnode) 544 case neighborsPacket: 545 req = new(neighbors) 546 default: 547 return nil, fromID, hash, fmt.Errorf("unknown type: %d", ptype) 548 } 549 s := rlp.NewStream(bytes.NewReader(sigdata[1:]), 0) 550 err = s.Decode(req) 551 return req, fromID, hash, err 552 } 553 554 func (req *ping) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 555 if expired(req.Expiration) { 556 return errExpired 557 } 558 t.send(from, pongPacket, &pong{ 559 To: makeEndpoint(from, req.From.TCP), 560 ReplyTok: mac, 561 Expiration: uint64(time.Now().Add(expiration).Unix()), 562 }) 563 if !t.handleReply(fromID, pingPacket, req) { 564 // Note: we're ignoring the provided IP address right now 565 go t.bond(true, fromID, from, req.From.TCP) 566 } 567 return nil 568 } 569 570 func (req *ping) name() string { return "PING/v4" } 571 572 func (req *pong) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 573 if expired(req.Expiration) { 574 return errExpired 575 } 576 if !t.handleReply(fromID, pongPacket, req) { 577 return errUnsolicitedReply 578 } 579 return nil 580 } 581 582 func (req *pong) name() string { return "PONG/v4" } 583 584 func (req *findnode) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 585 if expired(req.Expiration) { 586 return errExpired 587 } 588 if t.db.node(fromID) == nil { 589 // No bond exists, we don't process the packet. This prevents 590 // an attack vector where the discovery protocol could be used 591 // to amplify traffic in a DDOS attack. A malicious actor 592 // would send a findnode request with the IP address and UDP 593 // port of the target as the source address. The recipient of 594 // the findnode packet would then send a neighbors packet 595 // (which is a much bigger packet than findnode) to the victim. 596 return errUnknownNode 597 } 598 target := crypto.Keccak256Hash(req.Target[:]) 599 t.mutex.Lock() 600 closest := t.closest(target, bucketSize).entries 601 t.mutex.Unlock() 602 603 p := neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())} 604 // Send neighbors in chunks with at most maxNeighbors per packet 605 // to stay below the 1280 byte limit. 606 for i, n := range closest { 607 if netutil.CheckRelayIP(from.IP, n.IP) != nil { 608 continue 609 } 610 p.Nodes = append(p.Nodes, nodeToRPC(n)) 611 if len(p.Nodes) == maxNeighbors || i == len(closest)-1 { 612 t.send(from, neighborsPacket, &p) 613 p.Nodes = p.Nodes[:0] 614 } 615 } 616 return nil 617 } 618 619 func (req *findnode) name() string { return "FINDNODE/v4" } 620 621 func (req *neighbors) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 622 if expired(req.Expiration) { 623 return errExpired 624 } 625 if !t.handleReply(fromID, neighborsPacket, req) { 626 return errUnsolicitedReply 627 } 628 return nil 629 } 630 631 func (req *neighbors) name() string { return "NEIGHBORS/v4" } 632 633 func expired(ts uint64) bool { 634 return time.Unix(int64(ts), 0).Before(time.Now()) 635 }